inject icon indicating copy to clipboard operation
inject copied to clipboard

Add .MapHandler, which allows mapping types to a handler.

Open jnfeinstein opened this issue 11 years ago • 0 comments

This commit implements the functionality I described in this "issue". It supports mapping types to handlers, which are executed to return the desired value. To maintain backwards compatibility, the handler is not run when the type is a function.

This commit is designed to target a specific pattern in martini. Let's say I have a martini handler that maps a user, and a few web handlers that need a user:

func setupUser(c martini.Context) {
  var user User
  c.Map(&user)
}

m.Get("/user/me", setupUser, func(u *User) string {
  return u.String()
})

m.Get("/organization", setupUser, func(u *User) string {
  return u.Organization.String()
})

With this commit I can do:

func setupUser(c martini.Context) *User {
  var user User
  c.Map(&user)
  return &user
}

m.MapHandler(setupUser)

m.Get("/user/me", func(u *User) string {
  return u.String()
})

m.Get("/organization", func(u *User) string {
  return u.Organization.String()
})

I can request a user from anywhere without having to explicitly call the handler. Plus, the user is available directly, without the handler, on every subsequent call.

jnfeinstein avatar Nov 22 '14 02:11 jnfeinstein