// a middleware to handle user authorization func Auth(f Handler) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { userId, err := auth.Verify(req.Header.Get("Authorization")) if err != nil { Send(res, http.StatusUnauthorized, map[string]string{"error": err.Error()}) return } else { if newToken, err := auth.Sign(userId); err != nil { Send(res, http.StatusInternalServerError, map[string]string{"error": err.Error()}) return } else { res.Header().Add("Authorization", newToken) // update JWT Token } } //everything seems fine, goto the business logic handler if statusCode, err, output := f(req, mux.Vars(req), db, userId); err == nil { Send(res, statusCode, output) } else { Send(res, statusCode, map[string]string{"error": err.Error()}) } } }
// a middleware to handle user authorization func AuthAndTx(f HandlerWithTx) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { userId, err := auth.Verify(req.Header.Get("Authorization")) if err != nil { Send(res, http.StatusUnauthorized, map[string]string{"error": err.Error()}) return } else { if newToken, err := auth.Sign(userId); err != nil { Send(res, http.StatusInternalServerError, map[string]string{"error": err.Error()}) return } else { res.Header().Add("Authorization", newToken) // update JWT Token } } //prepare a database session for the handler session := db.NewSession() if err := session.Begin(); err != nil { Send(res, http.StatusInternalServerError, map[string]string{"error": err.Error()}) return } defer session.Close() //everything seems fine, goto the business logic handler if statusCode, err, output := f(req, mux.Vars(req), session, userId); err == nil { //the business logic handler return no error, then try to commit the db session if err := session.Commit(); err != nil { Send(res, http.StatusInternalServerError, map[string]string{"error": err.Error()}) } else { Send(res, statusCode, output) } } else { session.Rollback() Send(res, statusCode, map[string]string{"error": err.Error()}) } } }