This repository has been archived by the owner on Sep 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
commons.go
170 lines (149 loc) · 4.98 KB
/
commons.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package main
import (
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"net/http"
"runtime"
"time"
log "github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
loghook "github.com/ovh/logrus-ovh-hook"
"github.com/ovh/tat"
"github.com/spf13/viper"
userDB "github.com/ovh/tat/api/user"
)
// PreCheckUser has to be called as a middleware on Gin Route.
// Check if username exists in database, return user if ok
func PreCheckUser(ctx *gin.Context) (tat.User, error) {
var tatUser = tat.User{}
found, err := userDB.FindByUsername(&tatUser, getCtxUsername(ctx))
var e error
if !found {
e = errors.New("User unknown")
} else if err != nil {
e = errors.New("Error while fetching user")
}
if e != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": e})
ctx.AbortWithError(http.StatusInternalServerError, e)
return tatUser, e
}
return tatUser, nil
}
// GetParam returns the value of a parameter in Url.
// Example : http://host:port/:paramName
func GetParam(ctx *gin.Context, paramName string) (string, error) {
value, found := ctx.Params.Get(paramName)
if !found {
s := paramName + " in url does not exist"
ctx.JSON(http.StatusBadRequest, gin.H{"error": s})
return "", errors.New(s)
}
return value, nil
}
// AbortWithReturnError abort gin context and return JSON to user with error details
func AbortWithReturnError(ctx *gin.Context, statusHTTP int, err error) {
ctx.JSON(statusHTTP, gin.H{"error": err.Error()})
ctx.Abort()
}
// tatRecovery is a middleware that recovers from any panics and writes a 500 if there was one.
func tatRecovery(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
username, _ := c.Get(tat.TatHeaderUsername)
trace := make([]byte, 4096)
count := runtime.Stack(trace, true)
log.Panicf("[tatRecovery] err:%s method:%s path:%s query:%s username:%s stacktrace of %d bytes:%s",
err, c.Request.Method, path, query, username, count, trace)
c.AbortWithStatus(500)
}
}()
c.Next()
}
var logFieldAppID string
func initLog() {
if viper.GetBool("production") {
// Only log the warning severity or above.
log.SetLevel(log.InfoLevel)
gin.SetMode(gin.ReleaseMode)
log.SetFormatter(&log.JSONFormatter{})
} else {
log.SetLevel(log.DebugLevel)
}
logFieldAppID = viper.GetString("log_field_app_id")
if viper.GetString("graylog_host") != "" && viper.GetString("graylog_port") != "" {
graylogcfg := &loghook.Config{
Addr: fmt.Sprintf("%s:%s", viper.GetString("graylog_host"), viper.GetString("graylog_port")),
Protocol: viper.GetString("graylog_protocol"),
TLSConfig: &tls.Config{ServerName: viper.GetString("graylog_host")},
}
var extra map[string]interface{}
if viper.GetString("graylog_extra_key") != "" && viper.GetString("graylog_extra_value") != "" {
extra = map[string]interface{}{
viper.GetString("graylog_extra_key"): viper.GetString("graylog_extra_value"),
}
}
h, err := loghook.NewHook(graylogcfg, extra)
if err != nil {
log.Errorf("Error while initialize graylog hook: %s", err)
} else {
log.AddHook(h)
log.SetOutput(ioutil.Discard)
}
}
}
// ginrus returns a gin.HandlerFunc (middleware) that logs requests using logrus.
//
// Requests with errors are logged using logrus.Error().
// Requests without errors are logged using logrus.Info().
//
// It receives:
// 1. A time package format string (e.g. time.RFC3339).
// 2. A boolean stating whether to use UTC time zone or local.
func ginrus(l *log.Logger, timeFormat string, utc bool) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
// some evil middlewares modify this values
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
end := time.Now()
latency := end.Sub(start)
if utc {
end = end.UTC()
}
username, _ := c.Get(tat.TatHeaderUsername)
tatReferer, _ := c.Get(tat.TatHeaderXTatRefererLower)
sec := latency.Seconds()
ms := int64(latency / time.Millisecond)
entry := l.WithFields(log.Fields{
"appID": logFieldAppID,
"status": c.Writer.Status(),
"method": c.Request.Method,
"path": path,
"query": query,
"ip": c.ClientIP(),
"latency": latency,
"latency_nanosecond_int": latency.Nanoseconds(),
"latency_millisecond_int": ms,
"latency_second_float": sec,
"user-agent": c.Request.UserAgent(),
"time": end.Format(timeFormat),
"tatusername": username,
"tatfrom": tatReferer,
})
msg := fmt.Sprintf("%d %s %s %s %fs %dms %dns", c.Writer.Status(), c.Request.Method, path, username, sec, ms, latency)
if len(c.Errors) > 0 {
// Append error field if this is an erroneous request.
entry.Error(fmt.Sprintf("ERROR %s %s", msg, c.Errors.String()))
} else if c.Writer.Status() >= 400 {
entry.Warn(fmt.Sprintf("WARN %s", msg))
} else {
entry.Info(fmt.Sprintf("INFO %s", msg))
}
}
}