在Golang中测试一个中间件的实例

269 阅读1分钟

中间件基本上和Go中的路由是一样的。你可以通过使用httptest来测试它,就像你在测试一个路由处理程序一样,如下所示。

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
        }
    }
}
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)
}