Last active
February 27, 2017 06:53
-
-
Save simt2/48f80570b64a7ca456c4cdd3475d46aa to your computer and use it in GitHub Desktop.
mesh-go-example main logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
// Log into the Gentics Mesh backend to retrieve session cookie | |
MeshLogin(USERNAME, PASSWORD) | |
// Set up router handling incoming requests | |
router := mux.NewRouter() | |
router.HandleFunc("/", IndexHandler) | |
router.HandleFunc("/{path:.*}", PathHandler) | |
loggedRouter := handlers.LoggingHandler(os.Stdout, router) | |
// Start http server | |
log.Print("Starting HTTP Server on \"http://localhost:8081\"") | |
err := http.ListenAndServe(":8081", loggedRouter) | |
log.Print(err) | |
} | |
// IndexHandler handles requests to the webroot | |
func IndexHandler(w http.ResponseWriter, req *http.Request) { | |
t, _ := template.ParseFiles("templates/base.html", "templates/navigation.html", "templates/welcome.html") | |
data := templateData{ | |
Breadcrumb: LoadBreadcrumb(), | |
} | |
t.Execute(w, data) | |
} | |
// PathHandler handles requests all pages except the index | |
func PathHandler(w http.ResponseWriter, req *http.Request) { | |
// Use the requested path on the webroot endpoint to get a node | |
path := mux.Vars(req)["path"] | |
r := MeshGetRequest("demo/webroot/" + path + "?resolveLinks=short") | |
defer r.Body.Close() | |
// Check if the loaded node is an image and simply pass through the data if | |
// it is. | |
if match, _ := regexp.MatchString("^image/.*", r.Header["Content-Type"][0]); match { | |
w.Header().Set("Content-Type", r.Header["Content-Type"][0]) | |
io.Copy(w, r.Body) | |
} else { | |
// Otherwise parse the body to json | |
bytes, _ := ioutil.ReadAll(r.Body) | |
node := gjson.ParseBytes(bytes) | |
// If the loaded node is a vehicle, render the product | |
// detail page. | |
if node.Get("schema.name").String() == "vehicle" { | |
t, _ := template.ParseFiles("templates/base.html", "templates/navigation.html", "templates/productDetail.html") | |
data := templateData{ | |
Breadcrumb: LoadBreadcrumb(), | |
Products: &[]gjson.Result{node}, | |
} | |
t.Execute(w, data) | |
} else { | |
// In all other cases the node is a category, render product | |
// list. | |
t, _ := template.ParseFiles("templates/base.html", "templates/navigation.html", "templates/productList.html") | |
data := templateData{ | |
Breadcrumb: LoadBreadcrumb(), | |
Category: &node, | |
Products: LoadChildren(node.Get("uuid").String()), | |
} | |
t.Execute(w, data) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment