-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
239 lines (211 loc) · 8.86 KB
/
handler.go
File metadata and controls
239 lines (211 loc) · 8.86 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
// Package hx provides a lightweight and type-safe HTTP handler framework with generic support.
// It focuses on request handling, response rendering, and middleware composition.
package hx
import (
"context"
"net/http"
"reflect"
"unsafe"
"github.com/eatmoreapple/hx/binding"
"github.com/eatmoreapple/hx/httpx"
)
// ErrorHandler is a function type that handles errors occurred during request processing.
// It receives the ResponseWriter to write the error response, the original Request that caused the error,
// and the error itself. This allows for custom error handling and formatting across the application.
type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
// HandlerFunc is the standard handler type for processing HTTP requests in evo.
// It follows a similar pattern to http.HandlerFunc but returns an error instead of void.
// This allows for better error handling and middleware composition.
// If an error is returned, it will be passed to the ErrorHandler for processing.
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
// Warp is a convenience function that wraps an http.HandlerFunc into a HandlerFunc.
func Warp(h http.HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
h(w, r)
return nil
}
}
// Generic creates a type-safe handler with specified Request and Response types.
// It's a type assertion function that ensures the handler conforms to the TypedHandlerFunc interface.
// This function is particularly useful when you want to explicitly declare the types of your handler
// or when type inference isn't sufficient.
//
// Example:
//
// handler := Generic[UserRequest, UserResponse](func(ctx context.Context, req UserRequest) (UserResponse, error) {
// return UserResponse{Name: req.Name}, nil
// })
func Generic[Request, Response any](h TypedHandlerFunc[Request, Response]) TypedHandlerFunc[Request, Response] {
return h
}
// G is a shortcut for Generic
func G[Request, Response any](h TypedHandlerFunc[Request, Response]) TypedHandlerFunc[Request, Response] {
return Generic(h)
}
// Render is a generic handler function that processes requests of type Request
// and returns responses of type httpx.ResponseRender. It operates within a context and may return an error.
//
// Example:
//
// handler := Renderer[UserRequest](func(ctx context.Context, req UserRequest) (httpx.ResponseRender, error) {
// return httpx.JSONResponse{Data: req}, nil
// })
func Render[Request any](h TypedHandlerFunc[Request, httpx.ResponseRender]) HandlerFunc {
var handler requestHandler[Request] = func(ctx context.Context, req Request) (httpx.ResponseRender, error) {
responseRender, err := h(ctx, req)
if err != nil {
return nil, err
}
return responseRender, nil
}
return handler.asHandlerFunc()
}
// R is a shortcut for Renderer function.
// It provides the same functionality as Renderer but with a more concise name.
func R[Request any](h TypedHandlerFunc[Request, httpx.ResponseRender]) HandlerFunc {
return Render(h)
}
// E is a convenience function for creating a handler that doesn't require any request data.
// It takes a function that accepts a context and returns a response of type Response.
func E[Response any](h func(ctx context.Context) (Response, error)) TypedHandlerFunc[httpx.Empty, Response] {
return func(ctx context.Context, req httpx.Empty) (Response, error) {
return h(ctx)
}
}
// TypedHandlerFunc is a generic handler function that processes requests of type Request
// and returns responses of type Response. It operates within a context and may return an error.
type TypedHandlerFunc[Request, Response any] func(context.Context, Request) (Response, error)
// JSON converts the handler into a JSON response handler.
// The response will be automatically serialized to JSON format.
func (h TypedHandlerFunc[Request, Response]) JSON() HandlerFunc {
var handler requestHandler[Request] = func(ctx context.Context, req Request) (httpx.ResponseRender, error) {
resp, err := h(ctx, req)
if err != nil {
return nil, err
}
return httpx.JSONResponse{Data: resp}, nil
}
return handler.asHandlerFunc()
}
// String converts the handler into a string response handler.
// This method panics if the Response type is not string.
func (h TypedHandlerFunc[Request, Response]) String() HandlerFunc {
if _, ok := any((*Response)(nil)).(*string); !ok {
panic("String() only supports string response type")
}
var handler requestHandler[Request] = func(ctx context.Context, req Request) (httpx.ResponseRender, error) {
resp, err := h(ctx, req)
if err != nil {
return nil, err
}
str := *(*string)(unsafe.Pointer(&resp))
return httpx.StringResponse{Data: str}, nil
}
return handler.asHandlerFunc()
}
// XML converts the handler into an XML response handler.
// The response will be automatically serialized to XML format.
func (h TypedHandlerFunc[Request, Response]) XML() HandlerFunc {
var handler requestHandler[Request] = func(ctx context.Context, req Request) (httpx.ResponseRender, error) {
resp, err := h(ctx, req)
if err != nil {
return nil, err
}
return httpx.XMLResponse{Data: resp}, nil
}
return handler.asHandlerFunc()
}
// Pipe composes the handler with a series of middleware functions.
// Each middleware function has the signature func(ctx context.Context, req Request) error
// and can perform operations such as logging, authentication, or request modification.
// The middleware functions are executed in the order they are provided before the main handler is called.
//
// Note: When chaining multiple Pipe calls, the execution order is reversed.
// For example, with hx.G(app).Pipe(app2).Pipe(app3), app3 will execute first,
// followed by app2, and finally app (the original handler).
func (h TypedHandlerFunc[Request, Response]) Pipe(steps ...func(ctx context.Context, req Request) error) TypedHandlerFunc[Request, Response] {
if len(steps) == 0 {
return h
}
return func(ctx context.Context, request Request) (resp Response, err error) {
// Execute middleware functions in order
for _, middleware := range steps {
if err := middleware(ctx, request); err != nil {
return resp, err
}
}
// Execute the final handler
return h(ctx, request)
}
}
// requestHandler is an internal type that handles the processing of requests
// and produces a ResponseRender for rendering the response.
type requestHandler[Request any] func(context.Context, Request) (httpx.ResponseRender, error)
// call executes the handler with the given request and writes the response.
func (h requestHandler[Request]) call(w http.ResponseWriter, r *http.Request, req Request) error {
resp, err := h(r.Context(), req)
if err != nil {
return err
}
return resp.IntoResponse(w)
}
// asHandlerFunc converts the requestHandler into a standard HandlerFunc.
// It automatically determines whether to use extraction or binding based on the Request type.
func (h requestHandler[Request]) asHandlerFunc() HandlerFunc {
isImplementRequestExtractor := httpx.IsRequestExtractorType(reflect.TypeFor[Request]())
if isImplementRequestExtractor {
return h.extractAndHandle()
}
return h.bindAndHandle()
}
// createHandler encapsulates common logic for request handling.
func (h requestHandler[Request]) createHandler(extractFunc func(any, *http.Request) error) HandlerFunc {
requestType := reflect.TypeFor[Request]()
isPointer := requestType.Kind() == reflect.Pointer
// cache request element type
var elemType reflect.Type
if isPointer {
elemType = requestType.Elem()
}
newRequest := func() Request {
if isPointer {
instance, _ := reflect.TypeAssert[Request](reflect.New(elemType))
return instance
}
return *new(Request)
}
return func(w http.ResponseWriter, r *http.Request) error {
request := newRequest()
bindTarget := any(&request)
if isPointer {
bindTarget = request
}
if err := extractFunc(bindTarget, r); err != nil {
return err
}
return h.call(w, r, request)
}
}
// extractAndHandle creates a HandlerFunc that extracts request data using the RequestExtractor interface.
func (h requestHandler[Request]) extractAndHandle() HandlerFunc {
return h.createHandler(func(target any, r *http.Request) error {
return target.(httpx.RequestExtractor).FromRequest(r)
})
}
// bindAndHandle creates a HandlerFunc that binds request data using the ShouldBind function.
func (h requestHandler[Request]) bindAndHandle() HandlerFunc {
return h.createHandler(func(target any, r *http.Request) error {
return ShouldBind(r, target)
})
}
// ShouldBind binds the request data to the given interface.
// It first tries to bind using the default binder based on Content-Type,
// then attempts to bind using the GenericBinder if the type implements RequestExtractor.
func ShouldBind(r *http.Request, e any) error {
binder := binding.Default(r.Method, r.Header.Get("Content-Type"))
if err := binder.Bind(r, e); err != nil {
return err
}
// if each field has implemented RequestExtractor
return binding.Generic().Bind(r, e)
}