-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmw.go
105 lines (82 loc) · 2.02 KB
/
mw.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Package mw provides a Decorate function to cleanly decorate
// http.Handler interfaces with multiple middlewares.
//
/*
Go http middleware uses the following form
func Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// middleware logic
h.ServeHTTP(w, r)
})
}
You can use it with any existing middleware.
import (
// ...
"github.com/collinglass/mw"
"github.com/justinas/nosurf"
)
// decorate router
server := mw.Decorate(
http.NewServeMux(),
// add middleware from existing packages
nosurf.NewPure,
)
Or you can build your own custom middleware.
import (
// ...
"github.com/collinglass/mw"
)
// Create middleware from scratch
func JSONMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set Response Content-Type to application/json
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
})
}
You can use it with gorilla mux.
// new router
r := mux.NewRouter()
r.HandleFunc("/api/data", DataHandler).Methods("GET")
// decorate router
server := mw.Decorate(
r,
nosurf.NewPure,
JSONMiddleware,
)
http.Handle("/api/", server)
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
Or with the standard library http.ServeMux.
// new router
r := http.NewServeMux()
r.HandleFunc("/api/data", DataHandler)
// decorate router
server := mw.Decorate(
r,
nosurf.NewPure,
JSONMiddleware,
)
http.Handle("/api/", server)
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
*/
package mw
import (
"net/http"
)
// Middleware takes an http.Handler interface and decorates it.
type Middleware func(http.Handler) http.Handler
// Decorate ranges over a variadic number of middleware and
// decorates the http.Handler with them.
func Decorate(h http.Handler, ds ...Middleware) http.Handler {
decorated := h
for _, decorate := range ds {
decorated = decorate(decorated)
}
return decorated
}