route/internal/middleware/headers.go

36 lines
703 B
Go
Raw Normal View History

2018-01-21 17:07:21 +00:00
package middleware
import (
"context"
"net/http"
)
type headerKey int
const hdrKey headerKey = iota
// GetHeaders fetches http headers from the request context.
func GetHeaders(ctx context.Context) (http.Header, bool) {
h, ok := ctx.Value(hdrKey).(http.Header)
if !ok {
return http.Header{}, false
}
return h, true
}
// SaveHeaders adds the needed values to the request context for twirp services.
func SaveHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if ctx == nil {
panic("context is nil")
}
ctx = context.WithValue(ctx, hdrKey, r.Header)
next.ServeHTTP(w, r.WithContext(ctx))
})
}