Skip to content

Instantly share code, notes, and snippets.

@bobvanluijt
Last active July 13, 2017 17:34
Show Gist options
  • Save bobvanluijt/da010c4fafd7910109534fba41eb6414 to your computer and use it in GitHub Desktop.
Save bobvanluijt/da010c4fafd7910109534fba41eb6414 to your computer and use it in GitHub Desktop.
Idea for SPA server instead of NGINX - Dorel IO
/**
* Idea for SPA server instead of NGINX - Dorel IO
*
* You can run this locally: `$ go run dorel-io-static-server.go`
* The concept is that the Wordpress API is asked if the page exsists, if yes, it sends the correct meta data and status code.
* If you try: localhost:8080/foobar you will get a 404
* If yountry: localhost:8080/about-us (or another exsisting page) you will get a 200 with the correct metadata
*
* Bower compontents is always skipped and shown.
*
* Writtin this in Go because it will scale for production
*/
package main
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
)
type WordPressApi []struct {
Link string `json:"link"`
Title struct {
Rendered string `json:"rendered"`
} `json:"title"`
Acf struct {
MetaTitle string `json:"meta_title"`
MetaDescription string `json:"meta_description"`
} `json:"acf"`
}
func validate(w http.ResponseWriter, r *http.Request) {
// return 200 by default
returnStatusCode := 200
// set to not found meta data by default
metaTitle := "404 - page not found"
metaDescription := "This page is not found."
validateCurrentUrl, _ := url.Parse(r.RequestURI)
currentUrlSlice := strings.Split(validateCurrentUrl.Path, "/")
currentUrl := strings.Join(currentUrlSlice, "/")
if currentUrlSlice[0] != "bower_components" && currentUrlSlice[1] != "bower_components" {
var wpapi WordPressApi
// Point this to the correct Docker container
resp, _ := http.Get("https://wrps.api.www.maxi-cosi.com.au/wp-json/wp/v2/pages?per_page=100")
bs, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(bs, &wpapi)
for _, singleWpapi := range wpapi {
returnStatusCode = 404
validateWordpressUrl, _ := url.Parse(singleWpapi.Link)
wordpressUrl := strings.Join(strings.Split(validateWordpressUrl.Path, "/"), "/")
if currentUrl == wordpressUrl || currentUrl+"/" == wordpressUrl {
returnStatusCode = 200
metaTitle = singleWpapi.Acf.MetaTitle
metaDescription = singleWpapi.Acf.MetaDescription
break
}
}
}
w.WriteHeader(returnStatusCode)
io.WriteString(w, "This returns a http status code "+strconv.Itoa(returnStatusCode)+" you can replace this with the actual static file. The title will be '"+metaTitle+"' and the description will be '"+metaDescription+"'")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", validate)
log.Println("Running locally on port :8080")
http.ListenAndServe(":8080", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment