-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.go
50 lines (41 loc) · 1.38 KB
/
example.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
package main
import (
"fmt"
middleware "github.com/0x0000F1/chainware/pkg"
"net/http"
)
func main() {
// Create a new middleware table
mt := middleware.NewMiddlewareTable()
// Define some example middlewares
loggingMiddleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Logging middleware")
next.ServeHTTP(w, r)
})
}
authMiddleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Auth middleware")
next.ServeHTTP(w, r)
})
}
// Add middlewares to the table for a specific route
mt.AddMiddleware("/example", loggingMiddleware)
mt.AddMiddleware("/example", authMiddleware)
// Define the final handler
finalHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
// Create the server
http.HandleFunc("/example", func(w http.ResponseWriter, r *http.Request) {
chain := mt.GetChain("/example")
if chain != nil {
handler := chain.ChainMiddlewares(finalHandler)
handler.ServeHTTP(w, r)
} else {
finalHandler.ServeHTTP(w, r)
}
})
http.ListenAndServe(":8080", nil)
}