-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.go
75 lines (67 loc) · 2.06 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
70
71
72
73
74
75
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/ascarter/requestid"
"github.com/go-chi/cors"
"github.com/google/uuid"
)
// Auth 認証(dbはフェイク)
func Auth(db string) (fn func(http.Handler) http.Handler) {
fn = func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token != "admin" {
respondError(w, http.StatusUnauthorized, fmt.Errorf("利用権限がありません"))
return
}
h.ServeHTTP(w, r)
})
}
return
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
t := t2.Sub(t1)
reqID, ok := requestid.FromContext(r.Context())
if !ok {
reqID = uuid.New().String()
}
log.Printf("request_id %s req_time %s req_time_nsec %v", reqID, t.String(), t.Nanoseconds())
})
}
var devCORS = cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
var stagingCORS = cors.New(cors.Options{
AllowedOrigins: []string{"staging.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
var productionCORS = cors.New(cors.Options{
AllowedOrigins: []string{"production.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
// CorsConfig CORSの設定を環境別に持っている
var CorsConfig = map[string]*cors.Cors{
"develop": devCORS,
"staging": stagingCORS,
"production": productionCORS,
}