http.HandlerFunc in Go
tags: learning go programming
content
Go’s http.HandlerFunc type:
go-function-type-method#go-handler-func-type
- to use
HandlerFunc, we could have:
MyFunc := func(w http.ResponseWriter, r *http.Request) {
// do something here
}- now
MyFuncis just a normal ass function, it doesn’t have a specific type - because
MyFuncsatisfiesfunc(ResponseWrite, *Request), we can literally convert it to typeHandlerFunc
MyHandlerFunc := http.HandlerFunc(MyFunc)- this is NOT complicated, it’s just like any other type conversion!
- literally we have:
type MyInt int
normalInt := 1
myInt := MyInt(normalInt)Note
what
http.HandlerFuncis actually doing:
- in essence, it’s a type, whose underlying value is a function, with specific signature.
- we can do type conversion via
newFunc := http.HandlerFunc(oldFunc).- by doing this type conversion,
newFuncnow hashttp.HandlerinterfacenewFunccan now be used as a handler for http server