-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
71 lines (57 loc) · 1.34 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
package webfinger
import (
"encoding/json"
"errors"
"net/http"
)
// HandlerOption handler option func
type HandlerOption func(h *Handler)
// Handler is a HTTP handler that implements the webinger protocol
type Handler struct {
db DB
allowOrigin *string
}
// WithAllowOrigin sets Access-Control-Allow-Origin header to "orgn"
func WithAllowOrigin(orgn string) HandlerOption {
return func(h *Handler) {
h.allowOrigin = new(string)
*h.allowOrigin = orgn
}
}
// NewHandler returns a new handler instance
func NewHandler(db DB, opts ...HandlerOption) *Handler {
h := &Handler{
db: db,
}
for _, o := range opts {
o(h)
}
return h
}
// ServeHTTP handles HTTP requests
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// parse user query
q := QueryFromValues(r.URL.Query())
// get ther resource from DB
res, err := h.db.Get(q)
if err != nil {
if errors.Is(err, ErrResNotFound) {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
// add headers
if h.allowOrigin != nil {
w.Header().Add("Access-Control-Allow-Origin", *h.allowOrigin)
}
w.Header().Add("Content-Type", "application/jrd+json")
// encode response to json
ret, err := json.Marshal(res)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(ret)
}