-
Notifications
You must be signed in to change notification settings - Fork 0
/
usersRouter.go
78 lines (68 loc) · 1.82 KB
/
usersRouter.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
package handlers
import (
"net/http"
"strings"
"gopkg.in/mgo.v2/bson"
)
// UsersRouter handles the users route
func UsersRouter(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
path := strings.TrimSuffix(r.URL.Path, "/")
if path == "/users" {
switch r.Method {
case http.MethodGet:
usersGetAll(w, r)
return
case http.MethodPost:
usersPostOne(w, r)
return
case http.MethodHead:
usersGetAll(w, r)
return
case http.MethodOptions:
postOptionsResponse(w, []string{http.MethodGet, http.MethodPost, http.MethodHead, http.MethodOptions}, nil)
return
default:
postError(w, http.StatusMethodNotAllowed)
return
}
}
path = strings.TrimPrefix(path, "/users/")
if !bson.IsObjectIdHex(path) {
postError(w, http.StatusNotFound)
return
}
id := bson.ObjectIdHex(path)
switch r.Method {
case http.MethodGet:
usersGetOne(w, r, id)
return
case http.MethodPut:
usersPutOne(w, r, id)
return
case http.MethodPatch:
usersPatchOne(w, r, id)
return
case http.MethodDelete:
usersDeleteOne(w, r, id)
return
case http.MethodHead:
usersGetOne(w, r, id)
return
case http.MethodOptions:
postOptionsResponse(w, []string{http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions}, nil)
return
default:
postError(w, http.StatusMethodNotAllowed)
return
}
}
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Expose-Headers", "Access-Token, Uid, Location")
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}