update middlewares chaining + 'better' logs

This commit is contained in:
Julien Neuhart
2018-03-28 20:47:52 +02:00
parent 707927c126
commit d9a09dc795
2 changed files with 13 additions and 13 deletions

View File

@@ -52,7 +52,7 @@ func main() {
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: middlewares.LoggingHandler(r),
Handler: r,
}
// runs our server in a goroutine so that it doesn't block.

View File

@@ -20,20 +20,20 @@ import (
"github.com/satori/go.uuid"
)
// LoggingHandler identifies the request.
func LoggingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
transactionID := uuid.NewV4().String()
r = r.WithContext(context.WithTransactionID(r.Context(), transactionID))
logger.InfoR(context.GetTransactionID(r.Context()), fmt.Sprintf("Handling new request from %s", r.RemoteAddr))
next.ServeHTTP(w, r)
})
}
// GetMiddlewaresChain builds and returns the chaining of handlers
// using the alice library.
func GetMiddlewaresChain() http.Handler {
return alice.New(enforceContentLengthHandler, enforceContentTypeHandler, convertHandler, serveHandler).ThenFunc(clearHandler)
return alice.New(loggingHandler, enforceContentLengthHandler, enforceContentTypeHandler, convertHandler, serveHandler).ThenFunc(clearHandler)
}
// loggingHandler identifies the request.
func loggingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
transactionID := uuid.NewV4().String()
r = r.WithContext(context.WithTransactionID(r.Context(), transactionID))
logger.InfoR(context.GetTransactionID(r.Context()), fmt.Sprintf("Hello %s", r.RemoteAddr))
next.ServeHTTP(w, r)
})
}
// enforeContentLengthHandler checks if the request has content.
@@ -137,5 +137,5 @@ func clearHandler(w http.ResponseWriter, r *http.Request) {
if err := c.Clear(); err != nil {
logger.WarnR(context.GetTransactionID(r.Context()), err.Error())
}
logger.InfoR(context.GetTransactionID(r.Context()), "Request handled")
logger.InfoR(context.GetTransactionID(r.Context()), fmt.Sprintf("Bye %s", r.RemoteAddr))
}