Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

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

wants to merge 1 commit into from

Conversation

jnfeinstein
Copy link

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.

The .MapHandler function maps all of the output types of the given
function to the function. Whenever one of the types is requested,
the function is executed (in the context of the injector of course)
and the resulting value is used.

Technical notes:

-) I added the .MapHandler function for backwards compatiblity.
I believe it was previously possible to map a function as a type,
and I wanted to maintain that functionality.

-) The input to .MapHandler is an interface{} so that all function
signatures are supported. This also means that it might panic if
bad values are specified, which I think is desirable. Otherwise
the behavior may be quite strange.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant