Updated middleware example to return error format that fn understands.

This commit is contained in:
Travis Reeder
2017-07-13 10:21:02 -07:00
parent 667c611fac
commit 6d2c503010
2 changed files with 5 additions and 1 deletions

View File

@@ -91,6 +91,7 @@ func (c *middlewareContextImpl) serveNext() {
logrus.WithError(err).Warnln("Middleware error")
// todo: might be a good idea to check if anything is written yet, and if not, output the error: simpleError(err)
// see: http://stackoverflow.com/questions/39415827/golang-http-check-if-responsewriter-has-been-written
c.ginContext.Error(err)
c.ginContext.Abort()
return
}
@@ -110,6 +111,7 @@ func (s *Server) middlewareWrapperFunc(ctx context.Context) gin.HandlerFunc {
if len(s.middlewares) == 0 {
return
}
// TODO: we should get rid of this, gin context and middleware context both implement context, don't need a third one here
ctx = c.MustGet("ctx").(context.Context)
fctx := &middlewareContextImpl{Context: ctx}
// add this context to gin context so we can grab it later

View File

@@ -40,8 +40,10 @@ func (h *CustomMiddleware) Serve(ctx server.MiddlewareContext, w http.ResponseWr
// check auth header
tokenHeader := strings.SplitN(r.Header.Get("Authorization"), " ", 3)
if len(tokenHeader) < 2 || tokenHeader[1] != "KlaatuBaradaNikto" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
m := map[string]string{"error": "Invalid Authorization token. Sorry!"}
m2 := map[string]string{"message": "Invalid Authorization token."}
m := map[string]map[string]string{"error": m2}
json.NewEncoder(w).Encode(m)
return errors.New("Invalid authorization token.")
}