-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
147 lines (128 loc) · 4.07 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package main
import (
"bytes"
"encoding/json"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/tidwall/gjson"
)
const (
BASEURL = "http://localhost:8080/api/v1/"
USERNAME = "webclient"
PASSWORD = "webclient"
)
var (
// MeshSession used to login on the mesh backend
MeshCookie *http.Cookie
)
// templateData is the struct that we pass to our HTML templates, containing
// necessary data to render pages
type templateData struct {
Breadcrumb []gjson.Result
Category *gjson.Result
Products *[]gjson.Result
}
func main() {
// Log into 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)
}
}
}
// MeshLogin logs into the mesh backend and sets the session id
func MeshLogin(username string, password string) {
body := map[string]string{
"username": USERNAME,
"password": PASSWORD,
}
payload, _ := json.Marshal(body)
r, _ := http.Post(BASEURL+"auth/login", "application/json", bytes.NewBuffer(payload))
for _, cookie := range r.Cookies() {
if cookie.Name == "mesh.token" {
MeshCookie = cookie
}
}
}
// MeshGetRequest issues a logged in request to the mesh backend
func MeshGetRequest(path string) *http.Response {
url := BASEURL + path
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.AddCookie(MeshCookie)
client := http.Client{}
resp, _ := client.Do(req)
return resp
}
// LoadBreadcrumb retrieves the top level nodes used to display the navigation
func LoadBreadcrumb() []gjson.Result {
r := MeshGetRequest("demo/navroot/?maxDepth=1&resolveLinks=short")
defer r.Body.Close()
bytes, _ := ioutil.ReadAll(r.Body)
json := gjson.ParseBytes(bytes).Get("children").Array()
return json
}
// LoadChildren takes a nodes uuid and returns its children.
func LoadChildren(uuid string) *[]gjson.Result {
r := MeshGetRequest("demo/nodes/" + uuid + "/children?expandAll=true&resolveLinks=short")
defer r.Body.Close()
bytes, _ := ioutil.ReadAll(r.Body)
json := gjson.ParseBytes(bytes).Get("data").Array()
return &json
}