-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
69 lines (61 loc) · 1.76 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package controller
import (
"errors"
"fmt"
"github.com/spf13/viper"
"github.com/zembrodt/showtunes-api/util/global"
"log"
"net/http"
"strings"
)
func allowedHeaders() string {
return strings.Join([]string{
"Content-Type", "accept", "origin",
}, ", ")
}
func allowedMethods() string {
return strings.Join([]string{
http.MethodOptions, http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete,
}, ", ")
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", viper.GetString(global.OriginKey))
w.Header().Add("Access-Control-Allow-Credentials", "true")
w.Header().Add("Access-Control-Allow-Headers", allowedHeaders())
w.Header().Add("Access-Control-Allow-Methods", allowedMethods())
w.Header().Add("Access-Control-Max-Age", viper.GetString(global.MaxAgeKey))
if r.Method == http.MethodOptions {
http.Error(w, "No Content", http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func loggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
log.Printf("%s [%s]", r.URL, r.Method)
next.ServeHTTP(w, r)
})
}
func recoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
var err error
rec := recover()
if rec != nil {
switch t := rec.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = fmt.Errorf("unexpected error type %v: %v", t, rec)
}
log.Printf("Recovered from panic: %v", err)
http.Error(w,"Unexpected error occurred", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}