-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathmiddleware_test.go
109 lines (84 loc) · 2.06 KB
/
middleware_test.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
package ginmetrics_test
import (
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/gin-gonic/gin"
"github.com/penglongli/gin-metrics/ginmetrics"
)
func init() {
gin.SetMode(gin.ReleaseMode)
}
func TestMiddlewareSamePort(t *testing.T) {
r := newRouter()
ts := httptest.NewServer(r)
defer ts.Close()
var wg sync.WaitGroup
nLoops := 1000
wg.Add(nLoops)
for i := 0; i < nLoops; i++ {
go func(t *testing.T, i int) {
res, err := http.Get(ts.URL + fmt.Sprintf("/product/%d", i))
if err != nil {
t.Errorf("Expected nil, received %s", err.Error())
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected %d, received %d", http.StatusOK, res.StatusCode)
}
wg.Done()
}(t, i)
}
wg.Wait()
}
func TestMiddlewareDifferentPort(t *testing.T) {
appRouter, metricsRouter := newRouterSeparateMetrics()
ts := httptest.NewServer(appRouter)
tms := httptest.NewServer(metricsRouter)
defer ts.Close()
defer tms.Close()
var wg sync.WaitGroup
nLoops := 1000
wg.Add(nLoops)
for i := 0; i < nLoops; i++ {
go func(t *testing.T, i int) {
res, err := http.Get(ts.URL + fmt.Sprintf("/product/%d", i))
if err != nil {
t.Errorf("Expected nil, received %s", err.Error())
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected %d, received %d", http.StatusOK, res.StatusCode)
}
wg.Done()
}(t, i)
}
wg.Wait()
}
func newRouterSeparateMetrics() (*gin.Engine, *gin.Engine) {
appRouter := gin.New()
metricRouter := gin.Default()
m := ginmetrics.GetMonitor()
m.UseWithoutExposingEndpoint(appRouter)
m.Expose(metricRouter)
appRouter.GET("/product/:id", func(ctx *gin.Context) {
ctx.JSON(200, map[string]string{
"productId": ctx.Param("id"),
})
})
return appRouter, metricRouter
}
func newRouter() *gin.Engine {
r := gin.New()
m := ginmetrics.GetMonitor()
m.SetMetricPath("/metrics")
m.SetSlowTime(10)
m.SetDuration([]float64{0.1, 0.3, 1.2, 5, 10})
m.Use(r)
r.GET("/product/:id", func(ctx *gin.Context) {
ctx.JSON(200, map[string]string{
"productId": ctx.Param("id"),
})
})
return r
}