Skip to content

Instantly share code, notes, and snippets.

@crhntr
Created January 6, 2018 10:27
Show Gist options
  • Save crhntr/cbd6658f0525b0c76f6b7ef915161357 to your computer and use it in GitHub Desktop.
Save crhntr/cbd6658f0525b0c76f6b7ef915161357 to your computer and use it in GitHub Desktop.
An idea for a tool for handlers
package column
import (
"encoding/json"
"net/http"
"github.com/globalsign/mgo"
"github.com/julienschmidt/httprouter"
)
type Map map[string]interface{}
type Context struct {
request *http.Request
response http.ResponseWriter
params httprouter.Params
dbSess *mgo.Session
errors []error
status int
}
func (context *Context) JSON(data interface{}) {
if err := json.NewEncoder(context.response).Encode(data); err != nil {
context.errors = append(context.errors, err)
}
}
func (context *Context) Error(err error) {
if err != nil {
context.errors = append(context.errors, err)
}
}
type Base struct {
dbSess *mgo.Session
}
type ContextFunc func(*Context)
func (base Base) ContextMiddleware(contextFunc ContextFunc) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
dbSess := base.dbSess.Clone()
defer dbSess.Close()
contextFunc(&Context{
request: r,
response: w,
params: ps,
dbSess: dbSess,
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment