-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_kit.go
89 lines (78 loc) · 2.4 KB
/
http_kit.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
package go_http_kit
import (
"net/http"
"sync"
)
// HttpKit represents a wrapper around net/http package.
type HttpKit struct {
// mu - A mutex for ensuring synchronization when accessing HttpKit's data.
mu *sync.Mutex
// mux - ServeMux to handle HTTP requests
mux *http.ServeMux
// routes - List of routes
routes []*Route
// groupRoutes - List of groups of routes.
groupRoutes []*Group
// MethodNotAllowedHandler - Handler for Method Not Allowed responses.
MethodNotAllowedHandler http.HandlerFunc
// middlewares - List of middlewares to apply to all routes
middlewares []Middleware
cors *CORS
}
// New creates a new instance of HttpKit.
func New() *HttpKit {
return &HttpKit{
mu: &sync.Mutex{},
mux: http.NewServeMux(),
MethodNotAllowedHandler: func(rw http.ResponseWriter, r *http.Request) {
http.Error(rw, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
},
}
}
// Mux configures and returns the http.ServeMux for handling HTTP requests by iterating over defined routes.
func (hk *HttpKit) Mux() *http.ServeMux {
for _, route := range hk.routes {
handler := hk.configureRoute(route)
hk.mux.HandleFunc(route.pattern, handler)
}
return hk.mux
}
func (hk *HttpKit) Cors(c *CORS) *HttpKit {
hk.cors = c
return hk
}
// configureRoute applies middlewares and configurations to a route's handler function.
// It returns the configured handler for the route.
func (hk *HttpKit) configureRoute(route *Route) func(http.ResponseWriter, *http.Request) {
handler := route.handler
if route.middlewares != nil {
for i := len(route.middlewares) - 1; i >= 0; i-- {
handler = route.middlewares[i](handler)
}
}
if route.group != nil {
for i := len(route.group.middlewares) - 1; i >= 0; i-- {
handler = route.group.middlewares[i](handler)
}
}
if hk.middlewares != nil {
for i := len(hk.middlewares) - 1; i >= 0; i-- {
handler = hk.middlewares[i](handler)
}
}
handler = hk.methodMiddleware(handler, route.method)
if hk.cors != nil {
handler = hk.cors.Middleware(handler)
}
return handler
}
// methodMiddleware returns a middleware that checks if the incoming request uses the correct HTTP method.
func (hk *HttpKit) methodMiddleware(next http.HandlerFunc, method string) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
if r.Method != method {
hk.MethodNotAllowedHandler.ServeHTTP(rw, r)
return
}
next.ServeHTTP(rw, r)
}
}