-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
64 lines (56 loc) · 1.64 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
package promware
import (
"fmt"
"github.com/appleboy/gofight/v2"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/stretchr/testify/assert"
"net/http"
"testing"
"time"
)
func TestMiddleware(t *testing.T) {
middleware := Default()
routes := []struct {
path string
handler http.Handler
}{
{
path: "/metrics",
handler: promhttp.Handler(),
},
{
path: "/",
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "hello world")
}),
},
{
path: "/other",
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "no")
}),
},
}
mux := http.NewServeMux()
for _, route := range routes {
mux.Handle(route.path, middleware(route.handler))
}
r := gofight.New()
r.GET("/").Run(mux, func(rsp gofight.HTTPResponse, req gofight.HTTPRequest) {
assert.Equal(t, "hello world", rsp.Body.String())
assert.Equal(t, http.StatusOK, rsp.Code)
})
r.GET("/metrics").Run(mux, func(rsp gofight.HTTPResponse, req gofight.HTTPRequest) {
assert.Equal(t, http.StatusOK, rsp.Code)
body := rsp.Body.String()
assert.Contains(t, body, "request_duration_seconds")
assert.Contains(t, body, "requests_total{code=\"200\",method=\"GET\",url=\"/\"} 1")
// metrics endpoints should be skipped
assert.NotContains(t, body, "requests_total{code=\"200\",method=\"GET\",url=\"/metrics\"} 1")
// other was never called, and should be skipped
assert.NotContains(t, body, "requests_total{code=\"200\",method=\"GET\",url=\"/other\"} 1")
})
}