github.com/best4tires/kit@v1.0.5/srv/middleware.go (about) 1 package srv 2 3 import ( 4 "net/http" 5 "net/http/httputil" 6 "time" 7 8 "github.com/best4tires/kit/log" 9 "github.com/gorilla/handlers" 10 ) 11 12 func GZIP() func(http.Handler) http.Handler { 13 return handlers.CompressHandler 14 } 15 16 func Logging(dumpRequest bool) func(http.Handler) http.Handler { 17 return func(next http.Handler) http.Handler { 18 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 19 sw := NewStatusWriter(w) 20 t0 := time.Now() 21 next.ServeHTTP(sw, r) 22 log.Accessf("%s host=%q path=%q query=%q => status %d (%s) in %s", 23 r.Method, r.Host, r.URL.Path, r.URL.RawQuery, sw.statusCode, http.StatusText(sw.statusCode), time.Since(t0)) 24 25 if dumpRequest { 26 bs, _ := httputil.DumpRequest(r, true) 27 log.Accessf("request:\n%s", string(bs)) 28 } 29 }) 30 } 31 } 32 33 func Cors() func(http.Handler) http.Handler { 34 return func(next http.Handler) http.Handler { 35 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 36 w.Header().Add("Access-control-allow-origin", "*") 37 w.Header().Add("Access-control-allow-methods", "*") 38 w.Header().Add("Access-control-allow-headers", "*") 39 next.ServeHTTP(w, r) 40 }) 41 } 42 } 43 44 func Recovery() func(http.Handler) http.Handler { 45 return func(next http.Handler) http.Handler { 46 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 47 defer func() { 48 if err := recover(); err != nil { 49 w.WriteHeader(http.StatusInternalServerError) 50 log.Errorf("http-request: recovered: %v", err) 51 log.DebugStack() 52 } 53 }() 54 next.ServeHTTP(w, r) 55 }) 56 } 57 }