-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheader.go
More file actions
49 lines (39 loc) · 968 Bytes
/
header.go
File metadata and controls
49 lines (39 loc) · 968 Bytes
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
package middleware
import (
"context"
"net/http"
"github.com/remind101/pkg/httpx"
)
type Header struct {
// handler is the wrapped httpx.Handler.
handler httpx.Handler
key string
extractor func(*http.Request) string
}
func ExtractHeader(h httpx.Handler, header string) *Header {
return &Header{
key: header,
handler: h,
extractor: HeaderExtractor([]string{header}),
}
}
func (h *Header) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
e := h.extractor
value := e(r)
ctx = httpx.WithHeader(ctx, h.key, value)
r = r.WithContext(ctx)
return h.handler.ServeHTTPContext(ctx, w, r)
}
// HeaderExtractor returns a function that can extract a value from a list
// of headers.
func HeaderExtractor(headers []string) func(*http.Request) string {
return func(r *http.Request) string {
for _, h := range headers {
v := r.Header.Get(h)
if v != "" {
return v
}
}
return ""
}
}