Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
240 lines (195 loc) · 7.69 KB
/
Copy pathexample_test.go
File metadata and controls
240 lines (195 loc) · 7.69 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package apihandler_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
apihandler "github.com/wickedbyte/api-handler-go"
)
// ExampleRead wires a Resolver and a Transformer into a GET handler: the
// domain object is resolved from the request, lazily transformed into its
// representation, and encoded as JSON by the zero-value Writer.
func ExampleRead() {
repo := UserRepo{"1": {ID: "1", Name: "Ada Lovelace"}}
transformer := apihandler.TransformerFunc[*User, UserPayload](
func(_ *http.Request, user *User) (UserPayload, error) {
return UserPayload{ID: user.ID, Name: user.Name}, nil
},
)
mux := http.NewServeMux()
mux.Handle("GET /users/{id}", apihandler.Writer{}.Handler(apihandler.Read(repo, transformer)))
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/users/1", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
fmt.Println(strings.TrimSpace(rec.Body.String()))
// Output:
// 200 application/json
// {"id":"1","name":"Ada Lovelace"}
}
// ExampleCreate builds a POST handler from a Creator. A created resource
// responds 201 with its transformed representation; WithLocation derives the
// Location header from the created resource.
func ExampleCreate() {
repo := UserRepo{}
handler := apihandler.Create(repo, userTransformer,
apihandler.WithLocation(func(_ *http.Request, user *User) string {
return "/users/" + user.ID
}),
)
mux := http.NewServeMux()
mux.Handle("POST /users", apihandler.Writer{}.Handler(handler))
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/users",
strings.NewReader(`{"id":"7","name":"Grace Hopper"}`))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Header().Get("Location"))
fmt.Println(strings.TrimSpace(rec.Body.String()))
// Output:
// 201 /users/7
// {"id":"7","name":"Grace Hopper"}
}
// ExampleUpdate builds a PATCH handler that resolves the current resource,
// applies the update, and responds 200 with the transformed updated resource.
func ExampleUpdate() {
repo := UserRepo{"2": {ID: "2", Name: "Margaret"}}
handler := apihandler.Update(repo, repo, userTransformer)
mux := http.NewServeMux()
mux.Handle("PATCH /users/{id}", apihandler.Writer{}.Handler(handler))
req := httptest.NewRequestWithContext(context.Background(), http.MethodPatch, "/users/2",
strings.NewReader(`{"name":"Margaret Hamilton"}`))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println(rec.Code)
fmt.Println(strings.TrimSpace(rec.Body.String()))
// Output:
// 200
// {"id":"2","name":"Margaret Hamilton"}
}
// ExampleDelete builds a DELETE handler. A Deleter that returns ok == false
// yields 204 No Content with an empty body; returning the deleted resource
// would yield 200 with its representation instead.
func ExampleDelete() {
repo := UserRepo{"3": {ID: "3", Name: "Radia Perlman"}}
handler := apihandler.Delete(repo, repo, userTransformer)
mux := http.NewServeMux()
mux.Handle("DELETE /users/{id}", apihandler.Writer{}.Handler(handler))
req := httptest.NewRequestWithContext(context.Background(), http.MethodDelete, "/users/3", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Body.Len())
// Output:
// 204 0
}
// ExampleWrap composes middleware around a Handler as plain functions. The
// envelope middleware decorates the response body with MapBody, which keeps
// the body lazy and preserves Resourcer access to the untransformed domain
// object for other middleware.
func ExampleWrap() {
envelope := func(next apihandler.Handler) apihandler.Handler {
return func(r *http.Request) (apihandler.Result, error) {
result, err := next(r)
if err != nil {
return result, err
}
return apihandler.MapBody(result, func(content any) (any, error) {
return map[string]any{"data": content}, nil
}), nil
}
}
repo := UserRepo{"4": {ID: "4", Name: "Barbara Liskov"}}
handler := apihandler.Wrap(apihandler.Read(repo, userTransformer), envelope)
mux := http.NewServeMux()
mux.Handle("GET /users/{id}", apihandler.Writer{}.Handler(handler))
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/users/4", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println(strings.TrimSpace(rec.Body.String()))
// Output:
// {"data":{"id":"4","name":"Barbara Liskov"}}
}
// ExampleError shows the error contract: any error carrying an HTTP status —
// Error's StatusError, or a caller's own type with an HTTPStatus() int
// method — renders as an RFC 9457 problem document by default.
func ExampleError() {
resolver := apihandler.ResolverFunc[*User](func(_ *http.Request) (*User, error) {
return nil, apihandler.Error(http.StatusNotFound, "no such user")
})
handler := apihandler.Writer{}.Handler(apihandler.Read(resolver, userTransformer))
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/users/0", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
fmt.Println(strings.TrimSpace(rec.Body.String()))
// Output:
// 404 application/problem+json
// {"type":"about:blank","title":"Not Found","status":404,"detail":"no such user","instance":"/users/0"}
}
// ExampleWriter swaps the Writer's Encoder — the single seam where content
// reaches the wire — for a plain-text encoding. The zero value of Writer
// encodes JSON and writes problem documents for errors.
func ExampleWriter() {
writer := apihandler.Writer{
Encode: func(w http.ResponseWriter, _ *http.Request, status int, content any) error {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
_, err := fmt.Fprintf(w, "%+v", content)
if err != nil {
return fmt.Errorf("writing plain-text response: %w", err)
}
return nil
},
}
repo := UserRepo{"5": {ID: "5", Name: "Katherine Johnson"}}
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/users/5", nil)
req.SetPathValue("id", "5")
rec := httptest.NewRecorder()
writer.Handler(apihandler.Read(repo, userTransformer)).ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
fmt.Println(rec.Body.String())
// Output:
// 200 text/plain; charset=utf-8
// {ID:5 Name:Katherine Johnson}
}
// Example_dispatch is a recipe for mounting an API mux inside an
// existing handler chain with pass-through. It relies on
// http.ServeMux.Handler reporting an empty pattern when nothing matches, and
// is deliberately documentation rather than exported API — it is six lines.
func Example_dispatch() {
repo := UserRepo{"6": {ID: "6", Name: "Annie Easley"}}
api := http.NewServeMux()
api.Handle(
"GET /users/{id}",
apihandler.Writer{}.Handler(apihandler.Read(repo, userTransformer)),
)
dispatch := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, pattern := api.Handler(r); pattern != "" {
api.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r)
})
}
app := dispatch(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprint(w, "not an API route")
}))
// A request matching the API mux is dispatched to it...
rec := httptest.NewRecorder()
app.ServeHTTP(
rec,
httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/users/6", nil),
)
fmt.Println(strings.TrimSpace(rec.Body.String()))
// ...anything else passes through to the next handler.
rec = httptest.NewRecorder()
app.ServeHTTP(
rec,
httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/health", nil),
)
fmt.Println(rec.Body.String())
// Output:
// {"id":"6","name":"Annie Easley"}
// not an API route
}