Blame view

middleware.go 1.03 KB
ad8e9dd2a   Marko Tikvić   added middleware ...
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
  package webutility
  
  import (
  	"net/http"
  	"time"
  )
  
  func WithSetHeaders(h http.Handler) http.Handler {
  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  		SetDefaultHeaders(w)
  		if req.Method == http.MethodOptions {
  			return
  		}
  		h.ServeHTTP(w, req)
  	})
  }
  
  func WithParseForm(h http.Handler) http.Handler {
  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  		err := req.ParseForm()
  		if err != nil {
  			BadRequest(w, req, err.Error())
  			return
  		}
  		h.ServeHTTP(w, req)
  	})
  }
  
  func WithLog(h http.Handler) http.Handler {
  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  		reqLogger.LogRequest(req, "")
  		t1 := time.Now()
  		h.ServeHTTP(w, req)
  		t2 := time.Now()
  		reqLogger.LogResponse(w, t2.Sub(t1))
  	})
  }
  
  func WithAuth(h http.Handler, authorizedRoles []string) http.Handler {
  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  		if _, ok := AuthCheck(req, authorizedRoles); !ok {
  			Unauthorized(w, req, "")
  			return
  		}
  		h.ServeHTTP(w, req)
  	})
  }