Skip to content

organizing handlers

spaceweasel edited this page Feb 17, 2016 · 2 revisions

Organizing Handlers

If you have a great number of handler functions you may wish to split them into logical groups and keep them in separate files. Mango allows you to group associated handler functions inside a Registerer module; a module that implements the Registerer interface:

type Registerer interface {
	Register(r *Router)
}

Just register the routes like normal, but inside the Register method:

type ordersHandler struct{}

func (h ordersHandler) Register(r *mango.Router) {
  r.Get("/orders/{id}", h.getOrder)
  r.Get("/orders", h.getAllOrders)
  r.Post("/orders", h.addOrder)
  // ...  
}

func (h ordersHandler) getOrder(c *mango.Context) {
  // code omitted for clarity
}

func (h ordersHandler) getAllOrders(c *mango.Context) {
  // code omitted for clarity
}

func (h ordersHandler) addOrder(c *mango.Context) {
  // code omitted for clarity
}

// other handler functions...

Or if you prefer the anonymous function approach:

type accountsHandler struct{}

func (h accountsHandler) Register(r *mango.Router) {
  r.Get("/accounts/{id}", func(c *mango.Context) {
    // code omitted for clarity
  })
  r.Post("/accounts", func(c *mango.Context) {
    // TODO:
    // 1) extract account detail from request
    // 2) add new account to database
    // 3) add location header to response
    c.RespondWith(http.StatusCreated)
  })
  // other handler functions...
}

RegisterModules will add all the handler functions to the Router:

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

  // register the modules
  router.RegisterModules([]mango.Registerer{
    ordersHandler{},
    accountsHandler{},
    // ... other modules
  })

  http.ListenAndServe(":8080", router)
}