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 MyFunc is just a normal ass function, it doesn’t have a specific type
  • because MyFunc satisfies func(ResponseWrite, *Request), we can literally convert it to type HandlerFunc
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.HandlerFunc is 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, newFunc now has http.Handler interface
  • newFunc can now be used as a handler for http server

up

down

reference