ytdl-web/pkg/serverctx/context.go

38 lines
857 B
Go

package serverctx
import (
"context"
"net/http"
)
type contextKey string
const (
isHTTPSKey contextKey = "isHTTPS"
basePathKey contextKey = "basePath"
)
func Middleware(basePath string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isHttps := r.URL.Scheme == "https" || r.Header.Get("X-Forwarded-Proto") == "https"
ctx := context.WithValue(r.Context(), isHTTPSKey, isHttps)
ctx = context.WithValue(ctx, basePathKey, basePath)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func IsHTTPS(ctx context.Context) bool {
isHttps, ok := ctx.Value(isHTTPSKey).(bool)
return ok && isHttps
}
func BasePath(ctx context.Context) string {
basePath, ok := ctx.Value(basePathKey).(string)
if !ok {
return ""
}
return basePath
}