-
Notifications
You must be signed in to change notification settings - Fork 3
/
middlewares.go
80 lines (69 loc) · 1.82 KB
/
middlewares.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
package main
import (
"bytes"
"encoding/base64"
"net/http"
"os"
"strings"
"github.com/gorilla/handlers"
)
func BasicAuth(user, pass []byte, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const basicAuthPrefix string = "Basic "
// Get the Basic Authentication credentials
auth := r.Header.Get("Authorization")
if strings.HasPrefix(auth, basicAuthPrefix) {
// Check credentials
payload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):])
if err == nil {
pair := bytes.SplitN(payload, []byte(":"), 2)
if len(pair) == 2 &&
bytes.Equal(pair[0], user) &&
bytes.Equal(pair[1], pass) {
// Delegate request to the given handle
h.ServeHTTP(w, r)
return
}
}
}
// Request Basic Authentication otherwise
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
})
}
func redirectOnTrailingSlash(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path != "/" && strings.HasSuffix(path, "/") {
http.Redirect(w, r, path[0:len(path)-1], http.StatusMovedPermanently)
return
}
h.ServeHTTP(w, r)
})
}
func middlewares(final http.Handler) http.Handler {
chain := func(h http.Handler) http.Handler {
return h
}
user := []byte(mustGetenv("CRUD_USER"))
pw := []byte(mustGetenv("CRUD_PW"))
authenticate := func(h http.Handler) http.Handler {
return BasicAuth(user, pw, h)
}
dev := true
logger := func(h http.Handler) http.Handler {
if dev {
// gin logger
return appLogger(os.Stdout, h)
} else {
return handlers.LoggingHandler(os.Stdout, h)
}
}
return chain(
timerMiddleware(
authenticate(
logger(final),
),
),
)
}