-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
94 lines (85 loc) · 2.21 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 ghost
import (
"net/http"
)
type Server interface {
Create(http.ResponseWriter, *http.Request) error
Read(http.ResponseWriter, *http.Request) error
Update(http.ResponseWriter, *http.Request) error
Delete(http.ResponseWriter, *http.Request) error
List(http.ResponseWriter, *http.Request) error
}
type server[R Resource, Q Query, P PKey] struct {
store Store[R, Q, P]
encoding Encoding[R]
identifier Identifier[P]
querier Querier[Q]
}
func NewServer[R Resource, Q Query, P PKey](store Store[R, Q, P], encoding Encoding[R], identifier Identifier[P], querier Querier[Q]) Server {
return server[R, Q, P]{
store: store,
encoding: encoding,
identifier: identifier,
querier: querier,
}
}
func (g server[R, Q, P]) Create(w http.ResponseWriter, r *http.Request) error {
res, err := g.encoding.Decode(r)
if err != nil {
return err
}
if err := g.store.Create(r.Context(), &res); err != nil {
return err
}
return g.encoding.Encode(w, res, http.StatusCreated)
}
func (g server[R, Q, P]) Read(w http.ResponseWriter, r *http.Request) error {
pkey, err := g.identifier.PKey(r)
if err != nil {
return err
}
q, err := g.querier.Query(r)
if err != nil {
return err
}
res, err := g.store.Read(r.Context(), pkey, &q)
if err != nil {
return err
}
return g.encoding.Encode(w, *res, http.StatusOK)
}
func (g server[R, Q, P]) Update(w http.ResponseWriter, r *http.Request) error {
pkey, err := g.identifier.PKey(r)
if err != nil {
return err
}
res, err := g.encoding.Decode(r)
if err != nil {
return err
}
if err := g.store.Update(r.Context(), pkey, &res); err != nil {
return err
}
return g.encoding.Encode(w, res, http.StatusOK)
}
func (g server[R, Q, P]) Delete(w http.ResponseWriter, r *http.Request) error {
pkey, err := g.identifier.PKey(r)
if err != nil {
return err
}
if err := g.store.Delete(r.Context(), pkey); err != nil {
return err
}
return g.encoding.EncodeEmpty(w, http.StatusNoContent)
}
func (g server[R, Q, P]) List(w http.ResponseWriter, r *http.Request) error {
q, err := g.querier.Query(r)
if err != nil {
return err
}
res, err := g.store.List(r.Context(), &q)
if err != nil {
return err
}
return g.encoding.EncodeList(w, res, http.StatusOK)
}