-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
47 lines (34 loc) · 1.15 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
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
)
type LogMiddleware struct {
http.Handler
}
func (middleware *LogMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println("Receive request")
middleware.Handler.ServeHTTP(w, r)
}
// ============================================================================================== //
// 9. HttpRoter khusus buat router saja. Kalau ingin pakai middleware buat manual, ini contoh
// buatnya
func TestMiddleware(t *testing.T) {
router := httprouter.New()
router.GET("/", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
fmt.Fprint(w, "Middleware Test")
})
middleware := LogMiddleware{router}
request := httptest.NewRequest(http.MethodGet, "http://localhost:2020/", nil)
recorder := httptest.NewRecorder()
middleware.ServeHTTP(recorder, request)
response := recorder.Result()
body, _ := io.ReadAll(response.Body)
assert.Equal(t, "Middleware Test", string(body))
}
// ============================================================================================== //