Open platform to collect and prioritize feedback
fix: some routes had status = 0
goenningfeba1efc4e45
diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 7e73e1202..7b559294f 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -19,11 +19,14 @@ func routes(r *web.Engine) *web.Engine {r.Use(middlewares.Instrumentation())r.NotFound(func(c *web.Context) error {- next := func(c *web.Context) error {+ mw := middlewares.Chain(+ middlewares.WebSetup(),+ middlewares.Tenant(),+ middlewares.Instrumentation(),+ )+ next := mw(func(c *web.Context) error {return c.NotFound()- }- next = middlewares.Tenant()(next)- next = middlewares.WebSetup()(next)+ })return next(c)})diff --git a/app/middlewares/chain.go b/app/middlewares/chain.gonew file mode 100644index 000000000..4cea11764--- /dev/null+++ b/app/middlewares/chain.go@@ -0,0 +1,16 @@+package middlewares++import (+ "github.com/getfider/fider/app/pkg/web"+)++// Chain combines multiple middlewares into one+func Chain(mws ...web.MiddlewareFunc) web.MiddlewareFunc {+ return func(handler web.HandlerFunc) web.HandlerFunc {+ next := handler+ for i := len(mws) - 1; i >= 0; i-- {+ next = mws[i](next)+ }+ return next+ }+}diff --git a/app/middlewares/compress.go b/app/middlewares/compress.goindex f32dee0cf..c494286b1 100644--- a/app/middlewares/compress.go+++ b/app/middlewares/compress.go@@ -1,8 +1,10 @@package middlewaresimport (+ "bufio""compress/gzip""io"+ "net""net/http""strings"@@ -12,38 +14,23 @@ import (type gzipResponseWriter struct {io.Writerhttp.ResponseWriter- http.Hijacker- http.Flusher- http.CloseNotifier}// Compress returns a middleware which compresses HTTP response using gzip compressionfunc Compress() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c *web.Context) error {- res := c.Responseif strings.Contains(c.Request.GetHeader("Accept-Encoding"), "gzip") {-+ res := c.Responseres.Header().Set("Content-Encoding", "gzip")res.Header().Del("Accept-Encoding")res.Header().Add("Vary", "Accept-Encoding")- h, hok := res.(http.Hijacker)- if !hok { /* w is not Hijacker... oh well... */- h = nil- }+ gw, _ := gzip.NewWriterLevel(res.Writer, gzip.DefaultCompression)- f, fok := res.(http.Flusher)- if !fok {- f = nil- }-- gw, _ := gzip.NewWriterLevel(res, gzip.DefaultCompression)- c.Response = &gzipResponseWriter{+ c.Response.Writer = &gzipResponseWriter{Writer: gw,- ResponseWriter: res,- Hijacker: h,- Flusher: f,+ ResponseWriter: c.Response.Writer,}err := next(c)@@ -54,6 +41,7 @@ func Compress() web.MiddlewareFunc {}}}+func (w *gzipResponseWriter) Header() http.Header {return w.ResponseWriter.Header()}@@ -74,22 +62,10 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {return w.Writer.Write(b)}-type flusher interface {- Flush() error+func (r gzipResponseWriter) Flush() {+ r.Writer.(http.Flusher).Flush()}-func (w *gzipResponseWriter) Flush() {- if f, ok := w.Writer.(flusher); ok {- f.Flush()- }- if w.Flusher != nil {- w.Flusher.Flush()- }-}--func (w *gzipResponseWriter) Close() error {- if c, ok := w.Writer.(io.Closer); ok {- return c.Close()- }- return nil+func (r gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {+ return r.Writer.(http.Hijacker).Hijack()}diff --git a/app/middlewares/instrumentation.go b/app/middlewares/instrumentation.goindex 0c2a49bfe..69edd92ed 100644--- a/app/middlewares/instrumentation.go+++ b/app/middlewares/instrumentation.go@@ -23,8 +23,13 @@ func Instrumentation() web.MiddlewareFunc {err := next(c)- operation := fmt.Sprintf("%s /%s", c.Request.Method, c.Param(httprouter.MatchedRoutePathParam))- code := strconv.Itoa(c.ResponseStatusCode)+ routeName := c.Param(httprouter.MatchedRoutePathParam)+ operation := fmt.Sprintf("%s %s", c.Request.Method, routeName)+ if routeName == "" && c.Request.URL.Path != "/" {+ operation = "No Route Matched"+ }++ code := strconv.Itoa(c.Response.StatusCode)metrics.HttpRequests.WithLabelValues(code, operation).Inc()metrics.HttpDuration.WithLabelValues(operation).Observe(time.Since(begin).Seconds())diff --git a/app/middlewares/panic.go b/app/middlewares/panic.goindex 250bcf382..251a6f7ff 100644--- a/app/middlewares/panic.go+++ b/app/middlewares/panic.go@@ -1,8 +1,6 @@package middlewaresimport (- "io"-"github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/log""github.com/getfider/fider/app/pkg/web"@@ -16,10 +14,6 @@ func CatchPanic() web.MiddlewareFunc {err := c.Failure(errors.Panicked(r))log.Error(c, err)c.Rollback()-- if f, ok := c.Response.(io.Closer); ok {- f.Close()- }}}()diff --git a/app/middlewares/setup.go b/app/middlewares/setup.goindex 3a9687a44..afa39f09a 100644--- a/app/middlewares/setup.go+++ b/app/middlewares/setup.go@@ -35,7 +35,7 @@ func WorkerSetup() worker.MiddlewareFunc {})return}-+if err != nil {log.Error(c, err)}@@ -104,7 +104,7 @@ func WebSetup() web.MiddlewareFunc {})return}-+if err != nil {log.Error(c, err)}@@ -112,7 +112,7 @@ func WebSetup() web.MiddlewareFunc {log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} finished with @{StatusCode:magenta} in @{ElapsedMs:magenta}ms (@{State})", dto.Props{"State": state,"HttpMethod": c.Request.Method,- "StatusCode": c.ResponseStatusCode,+ "StatusCode": c.Response.StatusCode,"URL": c.Request.URL.String(),"ElapsedMs": elapsedMs,})diff --git a/app/pkg/mock/server.go b/app/pkg/mock/server.goindex 465e6eb86..312a39daf 100644--- a/app/pkg/mock/server.go+++ b/app/pkg/mock/server.go@@ -13,6 +13,7 @@ import ("github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/jsonq""github.com/getfider/fider/app/pkg/web"+ "github.com/julienschmidt/httprouter")// Server is a HTTP server wrapper for testing purpose@@ -32,7 +33,10 @@ func createServer() *Server {request, _ := http.NewRequest("GET", "/", nil)recorder := httptest.NewRecorder()- context := web.NewContext(engine, request, recorder, make(web.StringMap))+ params := make(web.StringMap)+ params[httprouter.MatchedRoutePathParam] = "/"++ context := web.NewContext(engine, request, recorder, params)return &Server{engine: engine,diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 0d54b0b4e..cc341516e 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -65,18 +65,17 @@ const CookieSignUpAuthName = "__signup_auth"//Context shared between http pipelinetype Context struct {context.Context- Response http.ResponseWriter- Request Request- ResponseStatusCode int- id string- sessionID string- engine *Engine- params StringMap- tasks []worker.Task+ Response Response+ Request Request+ id string+ sessionID string+ engine *Engine+ params StringMap+ tasks []worker.Task}//NewContext creates a new web Context-func NewContext(engine *Engine, req *http.Request, res http.ResponseWriter, params StringMap) *Context {+func NewContext(engine *Engine, req *http.Request, rw http.ResponseWriter, params StringMap) *Context {contextID := rand.String(32)wrappedRequest := WrapRequest(req)@@ -93,7 +92,7 @@ func NewContext(engine *Engine, req *http.Request, res http.ResponseWriter, paraid: contextID,engine: engine,Request: wrappedRequest,- Response: res,+ Response: Response{Writer: rw},params: params,tasks: make([]worker.Task, 0),}@@ -339,13 +338,13 @@ func (c *Context) AddCookie(name, value string, expires time.Time) *http.CookieExpires: expires,Secure: c.Request.IsSecure,}- http.SetCookie(c.Response, cookie)+ http.SetCookie(&c.Response, cookie)return cookie}//RemoveCookie removes a cookiefunc (c *Context) RemoveCookie(name string) {- http.SetCookie(c.Response, &http.Cookie{+ http.SetCookie(&c.Response, &http.Cookie{Name: name,Path: "/",HttpOnly: true,@@ -392,7 +391,7 @@ func (c *Context) Param(name string) string {if c.params == nil {return ""}- return strings.TrimPrefix(c.params[name], "/")+ return c.params[name]}//ParamAsInt returns parameter as int@@ -444,7 +443,6 @@ func (c *Context) Blob(code int, contentType string, b []byte) error {}c.Response.Header().Set("Content-Type", contentType)- c.ResponseStatusCode = codec.Response.WriteHeader(code)_, err := c.Response.Write(b)return err@@ -456,7 +454,6 @@ func (c *Context) NoContent(code int) error {c.Response.Header().Set("Cache-Control", "no-cache, no-store")}- c.ResponseStatusCode = codec.Response.WriteHeader(code)return nil}@@ -465,7 +462,6 @@ func (c *Context) NoContent(code int) error {func (c *Context) Redirect(url string) error {c.Response.Header().Set("Cache-Control", "no-cache, no-store")c.Response.Header().Set("Location", url)- c.ResponseStatusCode = http.StatusTemporaryRedirectc.Response.WriteHeader(http.StatusTemporaryRedirect)return nil}@@ -474,7 +470,6 @@ func (c *Context) Redirect(url string) error {func (c *Context) PermanentRedirect(url string) error {c.Response.Header().Set("Cache-Control", "no-cache, no-store")c.Response.Header().Set("Location", url)- c.ResponseStatusCode = http.StatusMovedPermanentlyc.Response.WriteHeader(http.StatusMovedPermanently)return nil}diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex be6b0057d..2546280f9 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -324,7 +324,7 @@ func (g *Group) Static(prefix, root string) {filePath := path.Join(root, c.Param("filepath"))fi, err := os.Stat(filePath)if err == nil && !fi.IsDir() {- http.ServeFile(c.Response, c.Request.instance, filePath)+ http.ServeFile(&c.Response, c.Request.instance, filePath)return nil}c.Response.Header().Set("Cache-Control", "no-cache, no-store")@@ -332,7 +332,7 @@ func (g *Group) Static(prefix, root string) {}} else {h = func(c *Context) error {- http.ServeFile(c.Response, c.Request.instance, root)+ http.ServeFile(&c.Response, c.Request.instance, root)return nil}}diff --git a/app/pkg/web/response.go b/app/pkg/web/response.gonew file mode 100644index 000000000..40c80e057--- /dev/null+++ b/app/pkg/web/response.go@@ -0,0 +1,38 @@+package web++import (+ "bufio"+ "net"+ "net/http"+)++// Response is a wrapper of http.ResponseWriter with access to the StatusCode+type Response struct {+ Writer http.ResponseWriter+ StatusCode int+}++func (r *Response) Header() http.Header {+ return r.Writer.Header()+}++func (r *Response) WriteHeader(code int) {+ r.StatusCode = code+ r.Writer.WriteHeader(code)+}++func (r *Response) Write(b []byte) (int, error) {+ if r.StatusCode == 0 {+ r.WriteHeader(http.StatusOK)+ }++ return r.Writer.Write(b)+}++func (r Response) Flush() {+ r.Writer.(http.Flusher).Flush()+}++func (r Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {+ return r.Writer.(http.Hijacker).Hijack()+}diff --git a/app/pkg/web/util/webutil.go b/app/pkg/web/util/webutil.goindex 75189787f..08f857d67 100644--- a/app/pkg/web/util/webutil.go+++ b/app/pkg/web/util/webutil.go@@ -42,7 +42,7 @@ func AddAuthTokenCookie(ctx *web.Context, token string) {//SetSignUpAuthCookie sets a temporary domain-wide Auth Tokenfunc SetSignUpAuthCookie(ctx *web.Context, user *entity.User) {- http.SetCookie(ctx.Response, &http.Cookie{+ http.SetCookie(&ctx.Response, &http.Cookie{Name: web.CookieSignUpAuthName,Domain: env.MultiTenantDomain(),Value: encode(user),@@ -57,7 +57,7 @@ func SetSignUpAuthCookie(ctx *web.Context, user *entity.User) {func GetSignUpAuthCookie(ctx *web.Context) string {cookie, err := ctx.Request.Cookie(web.CookieSignUpAuthName)if err == nil {- http.SetCookie(ctx.Response, &http.Cookie{+ http.SetCookie(&ctx.Response, &http.Cookie{Name: web.CookieSignUpAuthName,Domain: env.MultiTenantDomain(),Path: "/",