Blame view

middleware.go 1.52 KB
ad8e9dd2a   Marko Tikvić   added middleware ...
1
2
3
4
  package webutility
  
  import (
  	"net/http"
954ce8ddd   Marko Tikvić   moved mw logging ...
5
6
7
  	"time"
  
  	"git.to-net.rs/marko.tikvic/gologger"
ad8e9dd2a   Marko Tikvić   added middleware ...
8
  )
954ce8ddd   Marko Tikvić   moved mw logging ...
9
  var httpLogger *gologger.Logger
3fffcb954   Marko Tikvić   removed old http API
10
  func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
11
  	return func(w http.ResponseWriter, req *http.Request) {
ad8e9dd2a   Marko Tikvić   added middleware ...
12
13
14
15
  		SetDefaultHeaders(w)
  		if req.Method == http.MethodOptions {
  			return
  		}
0a60d9a1c   Marko Tikvić   switched from han...
16
17
  		h(w, req)
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
18
  }
3fffcb954   Marko Tikvić   removed old http API
19
  func ParseForm(h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
20
  	return func(w http.ResponseWriter, req *http.Request) {
ad8e9dd2a   Marko Tikvić   added middleware ...
21
22
23
24
25
  		err := req.ParseForm()
  		if err != nil {
  			BadRequest(w, req, err.Error())
  			return
  		}
0a60d9a1c   Marko Tikvić   switched from han...
26
27
  		h(w, req)
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
28
  }
3f8e3c437   Marko Tikvić   minor changes
29
30
31
32
33
34
35
36
37
38
  func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
  	return func(w http.ResponseWriter, req *http.Request) {
  		err := req.ParseMultipartForm(32 << 20)
  		if err != nil {
  			BadRequest(w, req, err.Error())
  			return
  		}
  		h(w, req)
  	}
  }
954ce8ddd   Marko Tikvić   moved mw logging ...
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  func EnableLogging(log string) (err error) {
  	httpLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
  	return err
  }
  
  func Log(h http.HandlerFunc) http.HandlerFunc {
  	return func(w http.ResponseWriter, req *http.Request) {
  		t1 := time.Now()
  
  		claims, _ := GetTokenClaims(req)
  		in := httpLogger.LogHTTPRequest(req, claims.Username)
  
  		rec := NewStatusRecorder(w)
  
  		h(rec, req)
  
  		t2 := time.Now()
  		out := httpLogger.LogHTTPResponse(rec.Status(), t2.Sub(t1), rec.Size())
  
  		httpLogger.CombineHTTPLogs(in, out)
  	}
  }
3fffcb954   Marko Tikvić   removed old http API
61
  func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
62
  	return func(w http.ResponseWriter, req *http.Request) {
3f8e3c437   Marko Tikvić   minor changes
63
64
  		if _, err := AuthCheck(req, roles); err != nil {
  			Unauthorized(w, req, err.Error())
ad8e9dd2a   Marko Tikvić   added middleware ...
65
66
  			return
  		}
0a60d9a1c   Marko Tikvić   switched from han...
67
68
  		h(w, req)
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
69
  }