-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmux.go
More file actions
60 lines (48 loc) · 1.26 KB
/
Copy pathmux.go
File metadata and controls
60 lines (48 loc) · 1.26 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
package main
import (
"log"
"net/http"
"twitter-clone-backend/handlers"
"twitter-clone-backend/models"
)
type AppMux struct {
http.ServeMux
middlewares []func(next http.Handler) http.Handler
}
func (mux *AppMux) RegisterMiddleware(next func(next http.Handler) http.Handler) {
mux.middlewares = append(mux.middlewares, next)
}
/*
Not in order with struct
struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
Request body:
{
"email": "Heaven_Hegmann50@hotmail.com",
"password": "example",
"username": "Garrick"
}
*/
func (mux *AppMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var current http.Handler = &mux.ServeMux
// the middlewares wrap the current handler. ex: current = loggingMiddleware(authMiddleware(current))
for _, next := range mux.middlewares {
current = next(current)
}
current.ServeHTTP(w, r)
}
func (mux *AppMux) Handle(pattern string, handler any) {
var wrappedHandler http.Handler
switch h := handler.(type) {
case func(http.ResponseWriter, *http.Request) *models.AppError:
wrappedHandler = handlers.AppHandler(h)
case http.Handler:
wrappedHandler = h
default:
log.Fatal("Unsupported handler type")
}
mux.ServeMux.Handle(pattern, wrappedHandler)
}