-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
60 lines (51 loc) · 1.7 KB
/
app.go
File metadata and controls
60 lines (51 loc) · 1.7 KB
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
package app
import (
"net/http"
"github.com/gorilla/mux"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
)
func init() {
r := mux.NewRouter()
r.HandleFunc("/", defaultHandler)
r.HandleFunc("/courses", coursesHandler).Methods("GET")
r.HandleFunc("/course/{name}/menu", courseMenuHandler).Methods("GET")
r.HandleFunc("/course/{name}/{chapter}", courseContentHandler).Methods("GET")
http.Handle("/", r)
}
func coursesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"courses":[{"name":"Foo","slug":"foo"}]}`))
}
func courseMenuHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
courseName := vars["name"]
ctx := appengine.NewContext(r)
content, err := readFileFromBucket(ctx, "courses/"+courseName+"/_menu.json")
if err != nil {
log.Errorf(ctx, "could not read _menu.json of %s: %v", courseName, err)
w.WriteHeader(http.StatusTeapot)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.Write(content)
}
func courseContentHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
courseName := vars["name"]
chapterName := vars["chapter"]
ctx := appengine.NewContext(r)
content, err := readFileFromBucket(ctx, "courses/"+courseName+"/"+chapterName+".html")
if err != nil {
log.Errorf(ctx, "could not read %s chapter %s: %v", courseName, chapterName, err)
w.WriteHeader(http.StatusTeapot)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(content)
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}