Package handling provides a mechanism for web applications to automatically create a struct of useful state on every request.

Such per-request state typically includes things like session data, as well as data derived from session data. For example, a session might include a user ID, and an application might include an object representing that user as part of its per-request state.

The application starts by defining a type to use for its per-request state, as well as how that state should be created. This is done by implementing the State and StateMaker interfaces.

type MyState struct {
	User *MyUser

func (s *MyState) EndRequest() {
	// Perform any cleanup that is needed after the response has been sent.

type MyStateMaker struct{}

func (m *MyStateMaker) MakeState(id string, w http.ResponseWriter, r *http.Request) (handling.State, error) {
	// Obtain a user based on information in the request.
	user := GetUserFromRequest(r)
	return MyState{user}

The application's handlers are similar to the standard http.HandlerFunc, except with an additional, first argument for the state object.

func HandleHello(s *MyState, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %s!", s.User.Name)

Finally, the application uses a HandlerFactory to obtain regular http.Handler objects to use with a multiplexer of its choice. In order to call its handler functions, the application defines a closure to convert between the State interface and its own State type:

func Adapt(fn func(*MyState, http.ResponseWriter, *http.Request)) handling.StateAwareHandlerFunc {
	return func(s handling.State, w http.ResponseWriter, r *http.Request) {
		fn(s.(*MyState), w, r)

func main() {
	hf := handling.NewHandlerFactory(MyStateMaker{})

	http.Handle("/hello", hf.Handle(Adapt(HandleHello)))

In addition to this functionality, handling includes a handful of convenience functions and http.Handler middleware that may prove useful.

It also includes the handling/forms sub-package, which provides functionality for the validation and rendering of HTML forms, and the handling/queries sub-package, which provides some useful SQL-related functionality.

Some default implementations of State objects may be found in the handling/state sub-package.

Imported by 2 package(s)


Imports 1 package(s)