context.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package http
  2. import (
  3. "context"
  4. "net"
  5. "net/http"
  6. )
  7. type ctxKey int
  8. const (
  9. ctxKeyAuth ctxKey = iota
  10. ctxKeyPublicURL
  11. ctxKeyUnixSock
  12. ctxKeyUser
  13. )
  14. // NewBaseContext initializes the context for all requests, adding info for use in middleware and handlers
  15. func NewBaseContext(ctx context.Context, url string) func(l net.Listener) context.Context {
  16. return func(l net.Listener) context.Context {
  17. if l.Addr().Network() == "unix" {
  18. return context.WithValue(ctx, ctxKeyUnixSock, true)
  19. }
  20. return context.WithValue(ctx, ctxKeyPublicURL, url)
  21. }
  22. }
  23. // IsAuthenticated checks if this request was authenticated via a middleware
  24. func IsAuthenticated(r *http.Request) bool {
  25. if v := r.Context().Value(ctxKeyAuth); v != nil {
  26. return true
  27. }
  28. if v := r.Context().Value(ctxKeyUser); v != nil {
  29. return true
  30. }
  31. return false
  32. }
  33. // IsUnixSocket checks if the request was received on a unix socket, used to skip auth & CORS
  34. func IsUnixSocket(r *http.Request) bool {
  35. v, _ := r.Context().Value(ctxKeyUnixSock).(bool)
  36. return v
  37. }
  38. // PublicURL returns the URL defined in NewBaseContext, used for logging & CORS
  39. func PublicURL(r *http.Request) string {
  40. v, _ := r.Context().Value(ctxKeyPublicURL).(string)
  41. return v
  42. }
  43. // CtxGetAuth is a wrapper over the private Auth context key
  44. func CtxGetAuth(ctx context.Context) interface{} {
  45. return ctx.Value(ctxKeyAuth)
  46. }
  47. // CtxGetUser is a wrapper over the private User context key
  48. func CtxGetUser(ctx context.Context) (string, bool) {
  49. v, ok := ctx.Value(ctxKeyUser).(string)
  50. return v, ok
  51. }
  52. // CtxSetUser is a test helper that injects a User value into context
  53. func CtxSetUser(ctx context.Context, value string) context.Context {
  54. return context.WithValue(ctx, ctxKeyUser, value)
  55. }