-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
83 lines (64 loc) · 1.44 KB
/
handler.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
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
)
func HandleBase(w http.ResponseWriter, r *http.Request, s *Source, opt *ServeOptions) {
if !opt.queit {
log.Printf("%s %s", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
if !opt.noCors {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
path := r.URL.Path[1:]
response := s.data[path]
if path == "" {
availableRoutes := make([]string, 0, len(s.data))
for k := range s.data {
availableRoutes = append(availableRoutes, k)
}
json.NewEncoder(w).Encode(
map[string]interface{}{
"availableRoutes": availableRoutes,
},
)
return
}
if strings.HasPrefix(path, "static/") && opt.tmp {
mimeType := "application/octet-stream"
w.Header().Set("Content-Type", mimeType)
http.ServeFile(w, r, "/tmp/"+strings.TrimPrefix(path, "static/"))
return
}
if response == nil {
w.WriteHeader(http.StatusNotFound)
return
}
switch r.Method {
case http.MethodGet:
data := GetAll(
r.URL.Query(),
response,
)
json.NewEncoder(w).Encode(data)
case http.MethodPost:
Create(
r.Body,
response,
)
w.WriteHeader(http.StatusCreated)
case http.MethodDelete:
id := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
Delete(
id,
response,
)
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}