Refactor IDP code
This commit is contained in:
parent
c0e9e88dba
commit
ce1fac0e68
11 changed files with 482 additions and 341 deletions
56
common/handlers/observability.go
Normal file
56
common/handlers/observability.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
const (
|
||||
requestIdKey key = iota
|
||||
)
|
||||
|
||||
func Logging(logger *log.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
requestId, ok := r.Context().Value(requestIdKey).(string)
|
||||
if !ok {
|
||||
requestId = "unknown"
|
||||
}
|
||||
logger.Infoln(requestId, r.Method, r.URL.Path, r.RemoteAddr, r.UserAgent())
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Tracing(nextRequestId func() string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestId := r.Header.Get("X-Request-Id")
|
||||
if requestId == "" {
|
||||
requestId = nextRequestId()
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), requestIdKey, requestId)
|
||||
w.Header().Set("X-Request-Id", requestId)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var Healthy int32
|
||||
|
||||
func NewHealthHandler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if atomic.LoadInt32(&Healthy) == 1 {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
})
|
||||
}
|
16
common/handlers/security.go
Normal file
16
common/handlers/security.go
Normal file
|
@ -0,0 +1,16 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func EnableHSTS() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", int((time.Hour*24*180).Seconds())))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
Reference in a new issue