| 1 |
package op |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"net/http" |
| 6 |
) |
| 7 |
|
| 8 |
type key int |
| 9 |
|
| 10 |
const ( |
| 11 |
issuerKey key = 0 |
| 12 |
) |
| 13 |
|
| 14 |
type IssuerInterceptor struct { |
| 15 |
issuerFromRequest IssuerFromRequest |
| 16 |
} |
| 17 |
|
| 18 |
// NewIssuerInterceptor will set the issuer into the context |
| 19 |
// by the provided IssuerFromRequest (e.g. returned from StaticIssuer or IssuerFromHost) |
| 20 |
func NewIssuerInterceptor(issuerFromRequest IssuerFromRequest) *IssuerInterceptor { |
| 21 |
return &IssuerInterceptor{ |
| 22 |
issuerFromRequest: issuerFromRequest, |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
func (i *IssuerInterceptor) Handler(next http.Handler) http.Handler { |
| 27 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 28 |
i.setIssuerCtx(w, r, next) |
| 29 |
}) |
| 30 |
} |
| 31 |
|
| 32 |
func (i *IssuerInterceptor) HandlerFunc(next http.HandlerFunc) http.HandlerFunc { |
| 33 |
return func(w http.ResponseWriter, r *http.Request) { |
| 34 |
i.setIssuerCtx(w, r, next) |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
// IssuerFromContext reads the issuer from the context (set by an IssuerInterceptor) |
| 39 |
// it will return an empty string if not found |
| 40 |
func IssuerFromContext(ctx context.Context) string { |
| 41 |
ctxIssuer, _ := ctx.Value(issuerKey).(string) |
| 42 |
return ctxIssuer |
| 43 |
} |
| 44 |
|
| 45 |
// ContextWithIssuer returns a new context with issuer set to it. |
| 46 |
func ContextWithIssuer(ctx context.Context, issuer string) context.Context { |
| 47 |
return context.WithValue(ctx, issuerKey, issuer) |
| 48 |
} |
| 49 |
|
| 50 |
func (i *IssuerInterceptor) setIssuerCtx(w http.ResponseWriter, r *http.Request, next http.Handler) { |
| 51 |
r = r.WithContext(ContextWithIssuer(r.Context(), i.issuerFromRequest(r))) |
| 52 |
next.ServeHTTP(w, r) |
| 53 |
} |