-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
94 lines (81 loc) · 1.77 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"
"net/http"
"strconv"
"strings"
"time"
)
func root(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
http.Redirect(w, r, "/home", http.StatusSeeOther)
}
func apiv1(w http.ResponseWriter, r *http.Request) {
var apiWriteNotFound = func(w http.ResponseWriter) {
message, err := json.Marshal(apiErrorObject{
Message: "Page Not Found",
})
if err != nil {
logError(err)
giveError(w, err)
return
}
w.WriteHeader(http.StatusNotFound)
w.Write(message)
}
var apiWriteError = func(w http.ResponseWriter, err error) {
message, err := json.Marshal(apiErrorObject{
Message: err.Error(),
})
if err != nil {
logError(err)
giveError(w, err)
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write(message)
}
var apiWrite = func(w http.ResponseWriter, v any) {
message, err := json.Marshal(v)
if err != nil {
logError(err)
giveError(w, err)
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write(message)
}
var url []string = strings.Split(r.PathValue("endpoint"), "/")
w.Header().Set("Content-Type", "application/json")
switch url[0] {
case "user":
query := r.URL.Query()
id, err := strconv.Atoi(query.Get("id"))
if err != nil {
apiWriteError(w, err)
return
}
obj, err := userFromId(id, permUser)
if err != nil {
logError(err)
apiWriteError(w, err)
return
}
apiWrite(w, obj)
default:
apiWriteNotFound(w)
return
}
}
func removeTokenCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: "",
Path: "/",
Expires: time.Unix(1, 0),
MaxAge: -1,
})
}
func giveError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}