feat: add web middleware
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
lab 2021-12-28 01:56:26 +08:00
parent 68ee747b7a
commit ab7b33e589
2 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package middleware
import "net/http"
func CORSHeaderMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Del("Content-Length")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", "application/json;charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,OPTIONS")
w.Header().Set("Access-Control-Allow-Credentials", "true")
next.ServeHTTP(w, r)
})
}

View File

@ -0,0 +1,23 @@
package middleware
import (
"net/http"
"time"
"github.com/sirupsen/logrus"
)
func LogRequestMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
at := time.Now()
defer func() {
logrus.WithFields(logrus.Fields{
"RemoteAddr": r.RemoteAddr,
"Method": r.Method,
"URI": r.RequestURI,
"Cost": time.Since(at).String(),
}).Infof("[%s] %s", r.Method, r.RequestURI)
}()
next.ServeHTTP(w, r)
})
}