103 lines
2.0 KiB
Go
103 lines
2.0 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
var processInstanceID = rand.Text()
|
|
|
|
func withInstanceID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Instance-Id", processInstanceID)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func withRequestID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var randomBytes [16]byte
|
|
|
|
if _, err := rand.Read(randomBytes[:]); err != nil {
|
|
panic("cannot generate request ID")
|
|
}
|
|
|
|
requestID := hex.EncodeToString(randomBytes[:])
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
type statusWriter struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (w *statusWriter) WriteHeader(status int) {
|
|
if w.status != 0 {
|
|
return
|
|
}
|
|
|
|
w.status = status
|
|
w.ResponseWriter.WriteHeader(status)
|
|
}
|
|
|
|
func (w *statusWriter) Write(body []byte) (int, error) {
|
|
if w.status == 0 {
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
return w.ResponseWriter.Write(body)
|
|
}
|
|
|
|
func (w *statusWriter) Unwrap() http.ResponseWriter {
|
|
return w.ResponseWriter
|
|
}
|
|
|
|
func withAccessLog(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
started := time.Now()
|
|
writer := &statusWriter{ResponseWriter: w}
|
|
|
|
defer func() {
|
|
if recovered := recover(); recovered != nil {
|
|
log.Printf(
|
|
"handler panic request_id=%s",
|
|
writer.Header().Get("X-Request-Id"),
|
|
)
|
|
|
|
if writer.status == 0 {
|
|
writeError(
|
|
writer,
|
|
http.StatusInternalServerError,
|
|
"internal_error",
|
|
"Internal server error",
|
|
)
|
|
} else {
|
|
panic(http.ErrAbortHandler)
|
|
}
|
|
}
|
|
|
|
status := writer.status
|
|
if status == 0 {
|
|
status = http.StatusOK
|
|
}
|
|
|
|
log.Printf(
|
|
"request_id=%s method=%s path=%q status=%d duration_ms=%d",
|
|
writer.Header().Get("X-Request-Id"),
|
|
r.Method,
|
|
r.URL.Path,
|
|
status,
|
|
time.Since(started).Milliseconds(),
|
|
)
|
|
}()
|
|
|
|
next.ServeHTTP(writer, r)
|
|
})
|
|
}
|