Blame view

middleware.go 1.11 KB
ad8e9dd2a   Marko Tikvić   added middleware ...
1
2
3
4
5
  package webutility
  
  import (
  	"net/http"
  	"time"
1b7dfab73   Marko Tikvić   Payload changed t...
6
7
  
  	"git.to-net.rs/marko.tikvic/gologger"
ad8e9dd2a   Marko Tikvić   added middleware ...
8
  )
3fffcb954   Marko Tikvić   removed old http API
9
  func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
10
  	return func(w http.ResponseWriter, req *http.Request) {
ad8e9dd2a   Marko Tikvić   added middleware ...
11
12
13
14
  		SetDefaultHeaders(w)
  		if req.Method == http.MethodOptions {
  			return
  		}
0a60d9a1c   Marko Tikvić   switched from han...
15
16
  		h(w, req)
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
17
  }
3fffcb954   Marko Tikvić   removed old http API
18
  func ParseForm(h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
19
  	return func(w http.ResponseWriter, req *http.Request) {
ad8e9dd2a   Marko Tikvić   added middleware ...
20
21
22
23
24
  		err := req.ParseForm()
  		if err != nil {
  			BadRequest(w, req, err.Error())
  			return
  		}
0a60d9a1c   Marko Tikvić   switched from han...
25
26
  		h(w, req)
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
27
  }
3fffcb954   Marko Tikvić   removed old http API
28
  var reqLogger *gologger.Logger
1b7dfab73   Marko Tikvić   Payload changed t...
29
30
31
32
33
  func EnableLogging(log string) error {
  	var err error
  	reqLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
  	return err
  }
3fffcb954   Marko Tikvić   removed old http API
34
  func Log(h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
35
  	return func(w http.ResponseWriter, req *http.Request) {
ad8e9dd2a   Marko Tikvić   added middleware ...
36
37
  		reqLogger.LogRequest(req, "")
  		t1 := time.Now()
0a60d9a1c   Marko Tikvić   switched from han...
38
  		h(w, req)
ad8e9dd2a   Marko Tikvić   added middleware ...
39
  		t2 := time.Now()
932f81461   Marko Tikvić   changes to gologger
40
  		reqLogger.LogResponse(w, req, t2.Sub(t1))
0a60d9a1c   Marko Tikvić   switched from han...
41
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
42
  }
3fffcb954   Marko Tikvić   removed old http API
43
  func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
0a60d9a1c   Marko Tikvić   switched from han...
44
  	return func(w http.ResponseWriter, req *http.Request) {
3fffcb954   Marko Tikvić   removed old http API
45
  		if _, ok := AuthCheck(req, roles); !ok {
ad8e9dd2a   Marko Tikvić   added middleware ...
46
47
48
  			Unauthorized(w, req, "")
  			return
  		}
0a60d9a1c   Marko Tikvić   switched from han...
49
50
  		h(w, req)
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
51
  }