kaspad/apiserver/server/middlewares.go
Ori Newman 31ccedf136 [NOD-325] Enable separate error messages for logging and client (#406)
* [NOD-325] Enable separate error messages for logging and client

* [NOD-325] Add json annotation to clientError
2019-09-16 13:26:05 +03:00

51 lines
1.4 KiB
Go

package server
import (
"fmt"
"github.com/daglabs/btcd/apiserver/utils"
"net/http"
"runtime/debug"
)
var nextRequestID uint64 = 1
func addRequestMetadataMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rCtx := utils.ToAPIServerContext(r.Context()).SetRequestID(nextRequestID)
r.WithContext(rCtx)
nextRequestID++
next.ServeHTTP(w, r)
})
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := utils.ToAPIServerContext(r.Context())
ctx.Infof("Method: %s URI: %s", r.Method, r.RequestURI)
next.ServeHTTP(w, r)
})
}
func recoveryMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := utils.ToAPIServerContext(r.Context())
defer func() {
recoveryErr := recover()
if recoveryErr != nil {
recoveryErrStr := fmt.Sprintf("%s", recoveryErr)
log.Criticalf("Fatal error: %s", recoveryErrStr)
log.Criticalf("Stack trace: %s", debug.Stack())
sendErr(ctx, w, utils.NewInternalServerHandlerError(recoveryErrStr))
}
}()
h.ServeHTTP(w, r)
})
}
func setJSONMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
h.ServeHTTP(w, r)
})
}