-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo.go
147 lines (121 loc) · 3.5 KB
/
echo.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
package isuhttp
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/goccy/go-json"
"github.com/labstack/echo/v4"
isutools "github.com/mazrean/isucon-go-tools"
)
var (
enableGoJson = true
)
func init() {
strEnableGoJson, ok := os.LookupEnv("GO_JSON")
if !ok {
return
}
subEnableGoJson, err := strconv.ParseBool(strEnableGoJson)
if err != nil {
log.Printf("failed to parse GO_JSON: %s\n", err)
return
}
enableGoJson = subEnableGoJson
}
func EchoSetting(e *echo.Echo) *echo.Echo {
e.Use(EchoMetricsMiddleware)
if enableGoJson {
e.JSONSerializer = JSONSerializer{}
}
listener, ok, err := newUnixDomainSockListener()
if err != nil {
log.Printf("failed to init unix domain socket: %s\n", err)
}
if ok {
e.Listener = listener
}
return e
}
type JSONSerializer struct{}
func (JSONSerializer) Serialize(c echo.Context, i any, indent string) error {
enc := json.NewEncoder(c.Response())
return enc.Encode(i)
}
func (JSONSerializer) Deserialize(c echo.Context, i any) error {
err := json.NewDecoder(c.Request().Body).Decode(i)
switch err := err.(type) {
case *json.UnmarshalTypeError:
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", err.Type, err.Value, err.Field, err.Offset)).SetInternal(err)
case *json.SyntaxError:
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", err.Offset, err.Error())).SetInternal(err)
}
return err
}
func EchoMetricsMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !isutools.Enable {
return next(c)
}
path := c.Path()
host := c.Request().Host
method := c.Request().Method
reqSz := reqSize(c.Request())
// シナリオ解析用メトリクス
flowCookie, err := c.Cookie("isutools_flow")
if err == nil {
flowMethod, flowPath, ok := strings.Cut(flowCookie.Value, ",")
if ok {
flowCounterVec.WithLabelValues(flowMethod, flowPath, method, path).Inc()
}
} else {
flowCookie = new(http.Cookie)
flowCookie.Name = "isutools_flow"
}
flowCookie.Value = fmt.Sprintf("%s,%s", method, path)
flowCookie.Expires = time.Now().Add(1 * time.Hour)
c.SetCookie(flowCookie)
start := time.Now()
err = next(c)
reqDur := float64(time.Since(start)) / float64(time.Second)
// error handlerがDefaultHTTPErrorHandlerでない場合、正しくない可能性あり
var (
statusCode int
validResSize = true
resSize float64
)
if c.Response().Committed || err == nil {
statusCode = c.Response().Status
resSize = float64(c.Response().Size)
} else {
var httpError *echo.HTTPError
if errors.As(err, &httpError) {
statusCode = httpError.Code
} else {
statusCode = http.StatusInternalServerError
}
if method == http.MethodHead {
resSize = 0
} else {
/*
実際には*echo.HTTPErrorがjson encodeされたものになるが、
速度低下が許容量を超えるので妥協する
ErrorHandlerをいい感じにいじれば解決しそう
*/
validResSize = false
}
}
strStatusCode := strconv.Itoa(statusCode)
reqSizeHistogramVec.WithLabelValues(strStatusCode, method, path).Observe(reqSz)
reqDurHistogramVec.WithLabelValues(strStatusCode, method, path).Observe(reqDur)
reqCounterVec.WithLabelValues(strStatusCode, method, host, path).Inc()
if validResSize {
resSizeHistogramVec.WithLabelValues(strStatusCode, method, path).Observe(resSize)
}
return nil
}
}