From 6d2c503010dab0ff7adc57495ac5c67b966cbd33 Mon Sep 17 00:00:00 2001 From: Travis Reeder Date: Thu, 13 Jul 2017 10:21:02 -0700 Subject: [PATCH] Updated middleware example to return error format that fn understands. --- api/server/middleware.go | 2 ++ examples/middleware/main.go | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/api/server/middleware.go b/api/server/middleware.go index 74e63622d..8fa1e8ecb 100644 --- a/api/server/middleware.go +++ b/api/server/middleware.go @@ -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 diff --git a/examples/middleware/main.go b/examples/middleware/main.go index 6e4da706a..81174d823 100644 --- a/examples/middleware/main.go +++ b/examples/middleware/main.go @@ -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.") }