Skip to content

Instantly share code, notes, and snippets.

@ishanjain28
Created Sep 5, 2017
Embed
What would you like to do?
package db
func Init() (*mgo.Session, error) {
db, err := mgo.Dial("localhost:27017")
if err != nil {
return nil, err
}
return db, nil
}
package main
// Router is created on every request and holds a reference to all the stuff that a middleware may be using
type RouterContext struct {
sess *mgo.Session
}
func main() {
db, err := db.Init()
if err != nil {
log.Fatalln(err.Error())
}
router := http.NewServeMux()
router.Handle("/submit", Handle(db, middleware.UpdateSiteStats(), middleware.RenderPage("submit.hbs"))
}
// Handle takes all the middlewares and then executes them one by one
func Handle(db *mgo.Session, handlers ...middleware.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cr := &RouterContext{}
if db != nil {
cr.sess = db.Clone()
defer cr.sess.Close()
}
for _, handler := range handlers {
err := handler(cr, w, r)
if err != nil {
w.Write([]byte(err.Error()))
return
}
}
})
}
package middleware
type HTTPError struct {
Message string
StatusCode int
LogLevel int
}
func (e HTTPError) Error() string {
return e.Message
}
func NewHTTPError(m string, code int) *HTTPError {
return &HTTPError{
Message: m,
StatusCode: code,
}
}
type Handler func(ctx *RouterContext, w http.ResponseWriter, r *http.Request) *HTTPError
// updateSiteStats updates the stats of website in database
func UpdateSiteStats() Handler {
return func(router *RouterContext, w http.ResponseWriter, r *http.Request) *HTTPError {
c := router.sess.DB(DB_NAME).C("sitestats")
_, err := c.Upsert(bson.M{
"type": "pagehits",
}, bson.M{
"$inc": bson.M{
"hits": 1,
},
})
if err != nil {
return NewHTTPError(err.Error(), http.StatusInternalServerError)
}
return nil
}
}
func RenderPage() Handler {
// Code redacted
return func(router *RouterContext, w http.ResponseWriter, r *http.Request) *HTTPError {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment