mirror of
https://github.com/kaspanet/kaspad.git
synced 2025-06-15 10:36:39 +00:00

* [NOD-325] Enable separate error messages for logging and client * [NOD-325] Add json annotation to clientError
51 lines
1.4 KiB
Go
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)
|
|
})
|
|
}
|