Skip to content

Instantly share code, notes, and snippets.

@Yigaue
Last active April 21, 2023 13:07
Show Gist options
  • Save Yigaue/3102ffe5dd1f67b8643247db6a2f289c to your computer and use it in GitHub Desktop.
Save Yigaue/3102ffe5dd1f67b8643247db6a2f289c to your computer and use it in GitHub Desktop.
Note on Handle, HandleFunc and HandlerFunc in Go or Golang

Note on Handle, HandleFunc and HandlerFunc in Go or Golang

Handle:

Handle is a method with ServeMux(struct) as receiver, and takes two argument, pattern(string) and a handler(Handler).

func (mux *ServeMux) Handle(pattern string, handler Handler) {
      // implementation here.
}

HandleFunc

The HandleFunc is a method with receiver, ServeMux that takes two arguments, pattern(string) and a function with the appropriate signature, (ResponseWriter, *Request). The HandleFunc method calls both Handle method and HandlerFunc type in it implementation. The function from it argument is passed to the HandlerFunc which sort of converts it to a Handler and then the resulting handler is passed to the Handle method.

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  if handler == nil {
    panic("http: nil handler")
  }
  mux.Handle(pattern, HandlerFunc(handler))
}

HandlerFunc

HandlerFunc defines a func type of signature (ResponseWriter, *Request). It implements a ServeHTTP method thereby implementing the Handler interface. Note all custom Handler most implement the http package Handler interface which defines only one method, ServeHTTP with signature (ResponseWriter, *Request). HandlerFunc makes it possible for normal function to be use as Handler without first implementing the ServeHTTP method define by the Handler interface.

type HandlerFunc func(ResponseWriter, *Request)

Note: Both HandleFunc method and HandlerFunc type are useful when a normal function is to be used as http Handler.

HandleFunc is a wrapper when a normal function is to be use as a handler. Handlefunc offers a one-time direct way to do this as it calls both the Handle method and the HandlerFunc type. However, without the HanleFunc the process have to be splitted. First passed the function to HandlerFunc for conversion to a handler and then the resulting handler will be passed to the Handle method, but using a HandleFunc does it directly since it calls both the Handle method and the HandlerFunc type in it implementation. Any type can serve as a Handler as far it implements the Handler interface which has just one method ServeHTTP with signature (ResponseWriter, *Request). Then this type (handler) can be passed directly to Handle method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment