This is a creation in Article, where the information may have evolved or changed.
Since I have just touched Golang and are not familiar with language and usage, it is strange to see this writing:
type Handler interface { ServeHTTP(ResponseWriter, *Request)}type HandlerFunc func(ResponseWriter, *Request)func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r)}
Why do I feel so superfluous in my heart? Define one func
as a type and then implement the ServeHTTP
function. Why not just use that function?
Let's take a look at http. The prototype of the Listenandserve () interface is clear:
func ListenAndServe(addr string, handler Handler) error
The second parameter of the function is one, which means that the function Handler interface
needs to pass in a type that implements the ServerHTTP
function.
For complex applications that may be specifically defined struct
to implement an http.Handler
interface, the case is passed in struct
. But if a simple application does this, it's a bit out of the way, so the http
package provides a HandlerFunc
type to assist the user in quickly translating a function into a type that conforms to http.Handler
the interface. This method is called adapter function type
[1]
.
The key to this technique is to define a function that conforms to the interface as a type, and then implement the function in the interface to that type, calling itself directly when implemented. When you use it, you just need to convert the custom function (the same prototype) into a type conversion.
In fact, not just the standard library to use such skills, in many golang
beginners will see the groupcache
use of the [2]
.
Reference
[1] Https://github.com/gopherchina/conference/blob/master/2017/1.3%20Go%20coding%20in%20go%20way.pdf
[2] Https://github.com/golang/groupcache/blob/master/groupcache.go