handler.ServeHTTP(w,req) and handler(w,req) difference in tests

huangapple go评论68阅读模式
英文:

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

正如@peter@mkopriva所指出的,选项完全相同,这只是个人口味的问题。

英文:

As @peter and @mkopriva pointed out, the options are exactly the same and it's a matter of taste

huangapple
  • 本文由 发表于 2022年12月27日 19:58:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/74928973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定