Created
January 6, 2018 10:27
-
-
Save crhntr/cbd6658f0525b0c76f6b7ef915161357 to your computer and use it in GitHub Desktop.
An idea for a tool for handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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