forked from pewpewlive/ppl-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
94 lines (84 loc) · 2.47 KB
/
server.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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strings"
)
func setHeaders(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Cache-Control", "no-store")
}
func cacheControlWrapper(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
setHeaders(w, r)
h.ServeHTTP(w, r)
})
}
func list(w http.ResponseWriter, r *http.Request) {
setHeaders(w, r)
levels := ListLevels(GetDir())
jsonStr, marshalingError := json.Marshal(levels)
if marshalingError != nil {
http.Error(w, marshalingError.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, string(jsonStr))
}
func getStrippedLevelID(r *http.Request) (string, error) {
levelID := r.FormValue("level_id")
if levelID == "" {
return "", errors.New("Missing level_id paramenter in request")
}
if !strings.HasPrefix(levelID, "/dev/") {
return "", errors.New("level_is is not prefixed with /dev/")
}
return levelID[5:], nil
}
func getLevel(w http.ResponseWriter, r *http.Request) {
setHeaders(w, r)
var strippedLevelID, err = getStrippedLevelID(r)
if err != nil {
log.Print(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
levelData, err := GetLevelData(strippedLevelID, len(os.Args) > 1 && os.Args[1] == "--disable-ext-filter")
if err != nil {
log.Print("Failed to GetLevelData:" + err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(levelData.Bytes())
}
func getLevelManifest(w http.ResponseWriter, r *http.Request) {
setHeaders(w, r)
var strippedLevelID, err = getStrippedLevelID(r)
if err != nil {
log.Print(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
levelManifest, err := GetLevelManifest(strippedLevelID)
if err != nil {
log.Print(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(levelManifest)
}
func main() {
// Serves the static files
fs := cacheControlWrapper(http.FileServer(http.Dir(GetDir())))
http.Handle("/", fs)
http.HandleFunc("/custom_levels/list2", list)
http.HandleFunc("/custom_levels/get_level", getLevel)
http.HandleFunc("/custom_levels/get_level_manifest", getLevelManifest)
log.Print("Starting server on port 9000")
log.Print("open http://localhost:9000/pewpew.html to run PewPew")
log.Fatal(http.ListenAndServe(":9000", nil))
}