-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexthttp.go
More file actions
166 lines (147 loc) · 5.24 KB
/
Copy pathexthttp.go
File metadata and controls
166 lines (147 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/*
* Copyright 2023 steadybit GmbH. All rights reserved.
*/
// Package exthttp supports setup of HTTP servers to implement the *Kit contracts. To keep the resulting binary small
// the net/http server is used.
package exthttp
import (
"encoding/json"
"fmt"
"io"
"net/http"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
"github.com/rs/zerolog/log"
"github.com/steadybit/extension-kit"
"github.com/steadybit/extension-kit/extutil"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
type Handler func(w http.ResponseWriter, r *http.Request, body []byte)
// RegisterHttpHandler registers a handler for the given path. Also adds panic recovery, gzip compression and request logging around the handler.
func RegisterHttpHandler(path string, handler Handler) {
RegisterHttpHandlerWithLogLevel(path, handler, zerolog.InfoLevel)
}
// RegisterHttpHandlerWithLogLevel registers a handler for the given path. Also adds panic recovery, gzip compression and request logging with a given log level around the handler.
func RegisterHttpHandlerWithLogLevel(path string, handler Handler, defaultLevel zerolog.Level) {
chain := PanicRecovery(gzhttp.GzipHandler(RequestTimeoutHeaderAware(LogRequestWithDefaultLogLevel(handler, defaultLevel))))
http.Handle(path, otelhttp.NewHandler(chain, "",
otelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {
return r.Method + " " + path
}),
))
}
// GetterAsHandler turns a getter function into a handler function. Typically used in combination with the RegisterHttpHandler function.
func GetterAsHandler[T any](handler func() T) Handler {
return func(w http.ResponseWriter, r *http.Request, body []byte) {
WriteBody(w, handler())
}
}
func PanicRecovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Error().Msgf("Panic: %v\n %s", err, string(debug.Stack()))
response := extension_kit.ToError("Internal Server Error", nil)
response.Detail = extutil.Ptr(fmt.Sprintf("Panic: %v", err))
WriteError(w, response)
}
}()
next.ServeHTTP(w, r)
})
}
func RequestTimeoutHeaderAware(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
timeout := r.Header.Get("Request-Timeout")
if timeout == "" {
timeout = r.Header.Get("X-Request-Timeout")
}
decorated := next
if timeout != "" {
timeoutValue, err := strconv.ParseFloat(timeout, 32)
if err == nil && timeoutValue > 0.0 {
log.Trace().Msgf("Using handler timeout %.1fs", timeoutValue)
decorated = http.TimeoutHandler(next, time.Duration(timeoutValue*1000)*time.Millisecond, "Timeout")
}
}
decorated.ServeHTTP(w, r)
}
}
func LogRequestWithDefaultLogLevel(next Handler, defaultLevel zerolog.Level) http.Handler {
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
level := defaultLevel
if r.Method == "GET" {
level = zerolog.DebugLevel
}
var reqBody []byte = nil
if !strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") {
if bytes, err := io.ReadAll(r.Body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
} else {
reqBody = bytes
}
}
hlog.FromRequest(r).Debug().
Str("method", r.Method).
Stringer("url", r.URL).
Int("req_size", len(reqBody)).
Bytes("body", reqBody).
Msg("Request received")
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
hlog.FromRequest(r).WithLevel(level).
Str("method", r.Method).
Stringer("url", r.URL).
Int("res_size", size).
Int("req_size", len(reqBody)).
Dur("duration", duration).
Int("status", status).
Msg("")
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next(w, r, reqBody)
})).ServeHTTP(w, r)
})
handler = hlog.RequestIDHandler("req_id", "Request-Id")(handler)
handler = hlog.NewHandler(log.Logger)(handler)
return handler
}
// WriteError writes the error as the HTTP response body with status code 500.
func WriteError(w http.ResponseWriter, err extension_kit.ExtensionError) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
logEvent := log.Error()
if err.Detail != nil {
logEvent.Str("details", *err.Detail)
}
logEvent.Msg(err.Title)
encodeErr := json.NewEncoder(w).Encode(err)
if encodeErr != nil {
log.Err(encodeErr).Msgf("Failed to write ExtensionError as response body")
}
}
// WriteBody writes the given value as the HTTP response body as JSON with status code 200.
func WriteBody(w http.ResponseWriter, response any) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Err(err).Msgf("Failed to write response body")
w.WriteHeader(500)
return
}
w.WriteHeader(200)
}
func IfNoneMatchHandler(etagFn func() string, delegate Handler) Handler {
return func(w http.ResponseWriter, r *http.Request, body []byte) {
etag := etagFn()
if len(etag) > 0 {
if ifNoneMatch := r.Header.Get("If-None-Match"); etag == ifNoneMatch {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("ETag", etag)
}
delegate(w, r, body)
}
}