-
Notifications
You must be signed in to change notification settings - Fork 43
/
handler.go
89 lines (79 loc) · 2.27 KB
/
handler.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
81
82
83
84
85
86
87
88
89
package server
import (
"bytes"
"github.com/baetyl/baetyl-cloud/common"
"github.com/baetyl/baetyl-go/v2/log"
"github.com/gin-gonic/gin"
"io/ioutil"
"strconv"
"strings"
"time"
)
var (
HeaderCommonName = "common-name"
)
func noRouteHandler(c *gin.Context) {
common.PopulateFailedResponse(common.NewContext(c), common.Error(common.ErrRequestMethodNotFound), true)
}
func noMethodHandler(c *gin.Context) {
common.PopulateFailedResponse(common.NewContext(c), common.Error(common.ErrRequestMethodNotFound), true)
}
func requestIDHandler(c *gin.Context) {
cc := common.NewContext(c)
cc.SetTrace()
cc.Next()
}
func loggerHandler(c *gin.Context) {
cc := common.NewContext(c)
log.L().Info("start request",
log.Any(cc.GetTrace()),
log.Any("method", cc.Request.Method),
log.Any("url", cc.Request.URL.Path),
log.Any("clientip", cc.ClientIP()),
)
if c.Request.Body != nil {
if buf, err := ioutil.ReadAll(c.Request.Body); err == nil {
c.Request.Body = ioutil.NopCloser(bytes.NewReader(buf[:]))
log.L().Info("request body",
log.Any(cc.GetTrace()),
log.Any("body", string(buf)),
)
}
}
start := time.Now()
c.Next()
log.L().Info("finish request",
log.Any(cc.GetTrace()),
log.Any("status", strconv.Itoa(c.Writer.Status())),
log.Any("latency", time.Since(start)),
)
}
func health(c *gin.Context) {
c.JSON(common.PackageResponse(nil))
}
func extractNodeCommonNameFromCert(c *gin.Context) {
cc := common.NewContext(c)
if len(c.Request.TLS.PeerCertificates) == 0 {
common.PopulateFailedResponse(cc, common.Error(common.ErrRequestAccessDenied), true)
return
}
cert := c.Request.TLS.PeerCertificates[0]
extractNodeCommonName(cc, cert.Subject.CommonName)
}
func extractNodeCommonNameFromHeader(c *gin.Context) {
cc := common.NewContext(c)
extractNodeCommonName(cc, c.GetHeader(HeaderCommonName))
}
func extractNodeCommonName(cc *common.Context, commonName string) {
res := strings.SplitN(commonName, ".", 2)
if len(res) != 2 || res[0] == "" || res[1] == "" {
log.L().Error("extract node common name error",
log.Any(cc.GetTrace()),
log.Any("commonName", commonName),
log.Any("HeaderCommonName", HeaderCommonName))
common.PopulateFailedResponse(cc, common.Error(common.ErrRequestAccessDenied), true)
return
}
cc.SetNamespace(res[0])
cc.SetName(res[1])
}