Bir ara katman (middleware) temelde Go'daki bir rota ile aynıdır. Aşağıda gösterildiği gibi httptest kullanarak bir rota işleyiciyi test ediyormuş gibi test edebilirsiniz.


Middleware


func Timer(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
timer := time.Now()
next.ServeHTTP(w, r)

if id, ok := r.Context().Value("some-key").(string); ok {
// Do something with the id and timer
}
}
}

Test


func TestTimer(t *testing.T) {
timerHandler := func(w http.ResponseWriter, r *http.Request) {}

req := httptest.NewRequest(http.MethodGet, "http://www.your-domain.com", nil)
req = req.WithContext(context.WithValue(req.Context(), "some-key", "123ABC"))

res := httptest.NewRecorder()

timerHandler(res, req)

tim := Timer(timerHandler)
tim.ServeHTTP(res, req)
}