Skip to content

handler functions

spaceweasel edited this page Feb 16, 2016 · 2 revisions

Handler Functions

Handler functions have a simple signature taking only a Context parameter. They can be named or anonymous:

func main() {  
  r := mango.NewRouter()

  // register a named handler function
  r.Get("/hello", hello)

  // register an anonymous handler function
  r.Get("/goodbye", func(c *mango.Context) {
    c.RespondWith("Goodbye world!")
  })

  // assign the router as the main handler
  http.ListenAndServe(":8080", router)
}

func hello(c *mango.Context) {
  c.RespondWith("Hello world!")
}

The benefit of the anonymous handler functions is that they keep the request method and pattern details adjacent to your handler code, rather than having to jump between handler and registration areas; however, a named handler function has the advantage of being capable of use by more than one route. Both approaches are fine; it is your personal choice and will depend most on the number of handler functions you need to register.