英文:
handler.ServeHTTP(w,req) and handler(w,req) difference in tests
问题
handler.ServeHTTP(w, req)和handler(w, req)在Go测试中的区别是什么?我应该在什么情况下使用它们?它们完全相同吗?
文档简单地说:ServeHTTP调用f(w, r)。
在上述代码中,h.ServeHTTP(w, request)和h(w, request)的区别在于:
h.ServeHTTP(w, request)是通过调用http.Handler接口的ServeHTTP方法来处理HTTP请求。h(w, request)是直接调用http.HandlerFunc类型的函数来处理HTTP请求。
在大多数情况下,这两种方式是等效的,因为http.HandlerFunc类型实际上是一个实现了ServeHTTP方法的函数类型。因此,你可以根据个人喜好选择使用哪种方式。
然而,如果你的处理程序是一个自定义的类型,并且实现了ServeHTTP方法,那么你应该使用handler.ServeHTTP(w, req)来调用该方法。这样做可以确保正确地调用自定义类型的ServeHTTP方法。
总结起来,handler.ServeHTTP(w, req)是调用实现了ServeHTTP方法的类型的标准方式,而handler(w, req)是直接调用函数类型的方式。
英文:
I'm trying to understand the difference between handler.ServeHTTP(w,req) and handler(w,req) in Go testing. When should I use each of them? Are they exactly the same?
Docs say simply: ServeHTTP calls f(w, r).
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/status", nil)
w := httptest.NewRecorder()
h := http.HandlerFunc(handlers.StatusHandler)
h.ServeHTTP(w, request)
/// or should it be
h(w, request)
...
}
}
答案1
得分: 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论