-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhx.go
More file actions
287 lines (243 loc) · 7.65 KB
/
hx.go
File metadata and controls
287 lines (243 loc) · 7.65 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package hx
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"github.com/struct0x/hx/internal"
"github.com/struct0x/hx/internal/out"
)
// ProblemDetails is a JSON object that describes an error.
// https://datatracker.ietf.org/doc/html/rfc9457
type ProblemDetails = out.ProblemDetails
// Response representing an HTTP response with status, body, and headers.
type Response = out.Response
// HandlerFunc is a function type that handles HTTP requests in HX framework.
// It receives a context.Context and *http.Request as input parameters and returns an error.
// Context is identical to http.Request.Context, but it includes a ResponseWriter that can be hijacked.
//
// If HandlerFunc returns:
// - nil: panics in dev mode, 500 in production — use hx.NoContent() for 204 responses
// - ProblemDetails: the response will be encoded as application/problem+json
// - Response: the response will be encoded as application/json with custom headers
// - any other error: the response will be 500 Internal Server Error
//
// Example usage:
//
// hx.HandlerFunc(func(ctx context.Context, r *http.Request) error {
// // HandleFunc the request
// return hx.Ok("Hello, World!")
// })
type HandlerFunc func(ctx context.Context, r *http.Request) error
type Handler interface {
ServeHX(ctx context.Context, r *http.Request) error
}
// Mux is an interface that wraps the http.Handler.
type Mux interface {
http.Handler
Handle(pattern string, handler http.Handler)
}
// HX is a framework for building HTTP APIs with enhanced error handling and middleware support.
// It provides a convenient way to handle HTTP requests, manage middleware chains, and standardize
// error responses using ProblemDetails (RFC 9457).
//
// Example usage:
//
// hx := hx.New(
// hx.WithLogger(slog.Default()),
// hx.WithCustomMux(http.NewServeMux()),
// hx.WithMiddleware(loggingMiddleware),
// )
//
// // HandleFunc requests
// hx.HandleFunc("/api/users", func(ctx context.Context, r *http.Request) error {
// // HandleFunc the request
// return nil
// })
//
// // Start the server
// http.ListenAndServe(":8080", hx)
type HX struct {
logger *slog.Logger
mux Mux
mids []Middleware
prefix string
production bool
routes *[]RouteInfo
problemInstanceGetter func(ctx context.Context) string
}
// New creates a new HX instance.
func New(opts ...Opt) *HX {
routes := make([]RouteInfo, 0)
hx := &HX{
logger: slog.Default(),
mux: http.DefaultServeMux,
routes: &routes,
}
for _, o := range opts {
o.applyHXOpt(hx)
}
return hx
}
func (h *HX) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mux.ServeHTTP(w, r)
}
// HandleFunc registers a new request handler with the given pattern and route options.
// Options can be Middleware values or a Doc describing the route for spec generation.
func (h *HX) HandleFunc(pattern string, handler HandlerFunc, opts ...RouteOpt) {
var mids []Middleware
var doc *RouteDoc
for _, opt := range opts {
switch o := opt.(type) {
case Middleware:
mids = append(mids, o)
case docOpt:
d := o.d
doc = &d
}
}
all := make([]Middleware, len(h.mids), len(h.mids)+len(mids))
copy(all, h.mids)
all = append(all, mids...)
full := buildPattern(h.prefix, pattern)
method, path := splitPattern(full)
*h.routes = append(*h.routes, RouteInfo{Method: method, Path: path, Doc: doc})
h.mux.Handle(full, h.handle(chain(handler, all)))
}
func (h *HX) Handle(pattern string, handler Handler, mids ...Middleware) {
var doc *RouteDoc
if documented, ok := handler.(Documented); ok {
docs := documented.Doc()
doc = &docs
}
all := make([]Middleware, len(h.mids), len(h.mids)+len(mids))
copy(all, h.mids)
all = append(all, mids...)
full := buildPattern(h.prefix, pattern)
method, path := splitPattern(full)
*h.routes = append(*h.routes, RouteInfo{Method: method, Path: path, Doc: doc})
h.mux.Handle(full, h.handle(chain(handler.ServeHX, all)))
}
// Group creates a sub-router sharing the same mux, with the given path prefix
// and additional middlewares appended to the current chain.
//
// Example:
//
// api := server.Group("/api/v1", authMiddleware)
// api.HandleFunc("POST /users", createUserHandler) // registers "POST /api/v1/users"
// api.HandleFunc("/orders", listOrdersHandler) // registers "/api/v1/orders"
//
// admin := api.Group("/admin", adminOnlyMiddleware)
// admin.HandleFunc("/stats", statsHandler) // registers "/api/v1/admin/stats"
func (h *HX) Group(prefix string, mids ...Middleware) *HX {
inherited := make([]Middleware, len(h.mids), len(h.mids)+len(mids))
copy(inherited, h.mids)
return &HX{
logger: h.logger,
mux: h.mux,
prefix: h.prefix + prefix,
mids: append(inherited, mids...),
production: h.production,
routes: h.routes,
problemInstanceGetter: h.problemInstanceGetter,
}
}
// buildPattern prepends prefix to a ServeMux pattern, handling the optional
// method prefix in Go 1.22+ patterns (e.g. "POST /path").
func buildPattern(prefix, pattern string) string {
if i := strings.Index(pattern, " "); i != -1 {
return pattern[:i+1] + prefix + pattern[i+1:]
}
return prefix + pattern
}
func (h *HX) handle(handler HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rwRead := new(atomic.Bool)
ctx := internal.WithResponseWriter(r.Context(), rwRead, w)
hxErr := handler(ctx, r.WithContext(ctx))
if rwRead.Load() {
if !h.production && hxErr != nil {
panic(fmt.Sprintf("hx: hijacked response writer, but handler returned error: %v", hxErr))
}
// Handler took control of the response writer.
// No need to write anything.
return
}
if hxErr == nil {
if !h.production {
panic("hx: handler returned nil; use hx.NoContent() for 204 responses")
}
w.WriteHeader(http.StatusInternalServerError)
return
}
enc := json.NewEncoder(w)
var pd ProblemDetails
if errors.As(hxErr, &pd) {
if h.problemInstanceGetter != nil && pd.Instance == "" {
pd.Instance = h.problemInstanceGetter(ctx)
}
for _, c := range pd.Cookies {
http.SetCookie(w, c)
}
w.Header().Add("Content-Type", "application/problem+json")
for name, values := range pd.Headers {
for _, value := range values {
w.Header().Add(name, value)
}
}
w.WriteHeader(pd.StatusCode)
if err := enc.Encode(pd); err != nil {
h.logger.ErrorContext(
ctx,
"hx: error encoding problem details",
"error",
err,
"path",
r.URL.Path,
)
}
return
}
var resp out.Response
if errors.As(hxErr, &resp) {
for _, c := range resp.Cookies {
http.SetCookie(w, c)
}
w.Header().Add("Content-Type", resp.ContentType)
for name, values := range resp.Headers {
for _, value := range values {
w.Header().Add(name, value)
}
}
w.WriteHeader(resp.StatusCode)
r, isReader := resp.Body.(io.Reader)
if isReader {
_, err := io.Copy(w, r)
if err != nil {
h.logger.ErrorContext(ctx, "hx: error copying response body", "error", err)
return
}
return
}
if resp.Body != nil {
if err := enc.Encode(resp.Body); err != nil {
h.logger.ErrorContext(ctx, "hx: error encoding response body", "error", err)
}
}
return
}
w.WriteHeader(http.StatusInternalServerError)
var opts []ProblemOpt
if h.problemInstanceGetter != nil {
opts = append(opts, WithInstance(h.problemInstanceGetter(ctx)))
}
if err := enc.Encode(Problem(http.StatusInternalServerError, "internal server error", opts...)); err != nil {
h.logger.ErrorContext(ctx, "hx: error encoding problem details", "error", err)
}
})
}