-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
55 lines (45 loc) · 1.46 KB
/
middleware.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
package main
import (
"net/http"
)
// Middleware is a wrapper for router, which allows to add
// interceptors to every request, e.g. to add CORS headers
type Middleware struct {
mux *http.ServeMux
}
// ServeHTTP intercepts requests before passing it on to the actual
// handler function
func (m *Middleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
fn := m.mux.ServeHTTP
// Can add additional middleware interceptors here
fn = RestrictionWrapper(fn)
fn(rw, req)
}
// RestrictionWrapper is used to block any other methods but GET and
// POST
func RestrictionWrapper(fn http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Access-Control-Allow-Methods", "GET,POST")
fn(rw, req)
}
}
// PostOnlyWrapper will only allow POST as HTTP method and returns an status code 406
func PostOnlyWrapper(fn http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.Error(rw, "You are only allowed POST requests at this endpoint", http.StatusNotAcceptable)
return
}
fn(rw, req)
}
}
// GetOnlyWrapper will only allow POST as HTTP method and returns an status code 406
func GetOnlyWrapper(fn http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
http.Error(rw, "You are only allowed GET requests at this endpoint", http.StatusNotAcceptable)
return
}
fn(rw, req)
}
}