1
|
|
|
package main |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"io/ioutil" |
5
|
|
|
"log" |
6
|
|
|
"net/http" |
7
|
|
|
"os" |
8
|
|
|
"strings" |
9
|
|
|
|
10
|
|
|
"github.com/gin-gonic/gin" |
11
|
|
|
uuid "github.com/satori/go.uuid" |
12
|
|
|
|
13
|
|
|
"github.com/rfinochi/golang-workshop-todo/pkg/common" |
14
|
|
|
) |
15
|
|
|
|
16
|
|
|
func logRequestMiddleware(infoLog *log.Logger) gin.HandlerFunc { |
17
|
|
|
return func(c *gin.Context) { |
18
|
|
|
infoLog.Printf("%s - %s %s %s", c.Request.RemoteAddr, c.Request.Proto, c.Request.Method, c.Request.URL.RequestURI()) |
19
|
|
|
c.Next() |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
func requestIDMiddleware() gin.HandlerFunc { |
24
|
|
|
return func(c *gin.Context) { |
25
|
|
|
c.Writer.Header().Set(common.APIRequestIDHeaderName, uuid.NewV4().String()) |
26
|
|
|
c.Next() |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
func revisionMiddleware(errorLog *log.Logger) gin.HandlerFunc { |
31
|
|
|
data, err := ioutil.ReadFile("REVISION") |
32
|
|
|
|
33
|
|
|
if err != nil { |
34
|
|
|
errorLog.Println("Revision Middleware error: ", err) |
35
|
|
|
|
36
|
|
|
return func(c *gin.Context) { |
37
|
|
|
c.Next() |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
revision := strings.TrimSpace(string(data)) |
42
|
|
|
|
43
|
|
|
return func(c *gin.Context) { |
44
|
|
|
c.Writer.Header().Set(common.APIRevisionHeaderName, revision) |
45
|
|
|
c.Next() |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
func tokenAuthMiddleware(errorLog *log.Logger) gin.HandlerFunc { |
50
|
|
|
requiredToken := os.Getenv(common.APITokenEnvVarName) |
51
|
|
|
|
52
|
|
|
if requiredToken == "" { |
53
|
|
|
errorLog.Fatal("Please set environment variable ", common.APITokenEnvVarName) |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return func(c *gin.Context) { |
57
|
|
|
if !strings.Contains(c.Request.RequestURI, "api-docs") { |
58
|
|
|
token := c.Request.Header.Get(common.APITokenHeaderName) |
59
|
|
|
|
60
|
|
|
if token == "" { |
61
|
|
|
common.RespondError(c, http.StatusUnauthorized, "API token required") |
62
|
|
|
return |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if token != requiredToken { |
66
|
|
|
common.RespondError(c, http.StatusUnauthorized, "Invalid API token (request one via e-mail to [email protected]") |
67
|
|
|
return |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
c.Next() |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|