httputil

package
v0.0.0-...-122f59b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 27 Imported by: 3

Documentation

Index

Constants

View Source
const BodyMaxSize = 1024 * 1024 * 10

Variables

View Source
var DefaultPermissionsPolicy = []PermissionsPolicyPolicy{
	{PermissionsPolicyDirectiveAccelerometer, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveAmbientLightSensor, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveAutoplay, PermissionsPolicyAllowlistAll},
	{PermissionsPolicyDirectiveBattery, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveBluetooth, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveBrowsingTopics, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveCamera, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveDisplayCapture, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveDocumentDomain, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveEncryptedMedia, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveExecutionWhileNotRendered, PermissionsPolicyAllowlistAll},
	{PermissionsPolicyDirectiveExecutionWhileOutOfViewport, PermissionsPolicyAllowlistAll},
	{PermissionsPolicyDirectiveFullscreen, PermissionsPolicyAllowlistAll},
	{PermissionsPolicyDirectiveGamepad, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveGeolocation, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveGyroscope, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveHid, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveIdentityCredentialsGet, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveIdleDetection, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveLocalFonts, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveMagnetometer, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveMicrophone, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveMidi, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveOtpCredentials, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectivePayment, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectivePictureInPicture, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectivePublickeyCredentialsCreate, PermissionsPolicyAllowlistSelf},
	{PermissionsPolicyDirectivePublickeyCredentialsGet, PermissionsPolicyAllowlistSelf},
	{PermissionsPolicyDirectiveScreenWakeLock, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveSerial, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveSpeakerSelection, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveStorageAccess, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveUsb, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveWebShare, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveWindowManagement, PermissionsPolicyAllowlistNone},
	{PermissionsPolicyDirectiveXrSpatialTracking, PermissionsPolicyAllowlistNone},
}

* Enabled features: * - autoplay=* * - execution-while-not-rendered=* * - execution-while-out-of-viewport=* * - fullscreen=* * - publickey-credentials-create=(self) (for WebAuthn) * - publickey-credentials-get=(self) (for WebAuthn)

View Source
var FlashMessageTypeCookieDef = &CookieDef{
	NameSuffix: "flash_message_type",
	Path:       "/",
	SameSite:   http.SameSiteNoneMode,
}

FlashMessageTypeCookieDef is a HTTP session cookie.

View Source
var JSONTooLarge = apierrors.RequestEntityTooLarge.WithReason("JSONTooLarge")

Functions

func BindJSONBody

func BindJSONBody(r *http.Request, w http.ResponseWriter, v *validation.SchemaValidator, payload interface{}, options ...JSONOption) error

func CSPJoin

func CSPJoin(directives []string) string

func CheckContentType

func CheckContentType(raws []string) httproute.MiddlewareFunc

func CookieDomainWithoutPort

func CookieDomainWithoutPort(host string) string

CookieDomainWithoutPort derives host from r. If host has port, the port is removed. If host-1 is longer than ETLD+1, host-1 is returned. If ETLD+1 cannot be derived, an empty string is returned. The return value never have port.

func GetHost

func GetHost(r *http.Request, trustProxy bool) string

func GetIP

func GetIP(r *http.Request, trustProxy bool) (ip string)

func GetProto

func GetProto(r *http.Request, trustProxy bool) string

func GetRedirectURI

func GetRedirectURI(r *http.Request, trustProxy bool) (out string, err error)

func HealthCheckHandler

func HealthCheckHandler(w http.ResponseWriter, r *http.Request)

HealthCheckHandler is basic handler for server health check

func HostRelative

func HostRelative(u *url.URL) *url.URL

func IsJSONContentType

func IsJSONContentType(contentType string) bool

func IsNameHashed

func IsNameHashed(p string) bool

func NewExternalClient

func NewExternalClient(timeout time.Duration) *http.Client

func NewExternalClientWithOptions

func NewExternalClientWithOptions(timeout time.Duration, opts ExternalClientOptions) *http.Client

func NoCache

func NoCache(next http.Handler) http.Handler

NoCache allows caches to store a response but requires them to revalidate it before reuse.

func NoStore

func NoStore(next http.Handler) http.Handler

NoStore makes the browser not to store the requests.

func ParseJSONBody

func ParseJSONBody(r *http.Request, w http.ResponseWriter, parse func(io.Reader, interface{}) error, payload interface{}, options ...JSONOption) error

func PermissionsPolicyHeader

func PermissionsPolicyHeader(next http.Handler) http.Handler

func ShouldSendSameSiteNone

func ShouldSendSameSiteNone(useragent string, secure bool) bool

func UpdateCookie

func UpdateCookie(w http.ResponseWriter, cookie *http.Cookie)

func XContentTypeOptionsNosniff

func XContentTypeOptionsNosniff(next http.Handler) http.Handler

func XFrameOptionsDeny

func XFrameOptionsDeny(next http.Handler) http.Handler

Types

type BodyDefaulter

type BodyDefaulter interface {
	SetDefaults()
}

type CookieDef

type CookieDef struct {
	// NameSuffix means the cookie could have prefix.
	NameSuffix string
	Path       string
	// Domain is omitted because it is controlled somewhere else.
	// Domain            string
	AllowScriptAccess bool
	SameSite          http.SameSite
	MaxAge            *int
}

type CookieManager

type CookieManager struct {
	Request      *http.Request
	TrustProxy   bool
	CookiePrefix string
	CookieDomain string
}

func (*CookieManager) ClearCookie

func (f *CookieManager) ClearCookie(def *CookieDef) *http.Cookie

ClearCookie generates a cookie that when set, the cookie is clear.

func (*CookieManager) CookieName

func (f *CookieManager) CookieName(def *CookieDef) string

CookieName returns the full name, that is, CookiePrefix followed by NameSuffix.

func (*CookieManager) GetCookie

func (f *CookieManager) GetCookie(r *http.Request, def *CookieDef) (*http.Cookie, error)

GetCookie is wrapper around http.Request.Cookie, taking care of cookie name.

func (*CookieManager) ValueCookie

func (f *CookieManager) ValueCookie(def *CookieDef, value string) *http.Cookie

ValueCookie generates a cookie that when set, the cookie is set to the specified value.

type ExternalClientOptions

type ExternalClientOptions struct {
	FollowRedirect bool
}

type FileServer

type FileServer struct {
	FileSystem          http.FileSystem
	FallbackToIndexHTML bool
}

FileServer is a specialized version of http.FileServer that assumes files rooted at FileSystem are name-hashed. cache-control are written specifically for index.html and name-hashed files.

func (*FileServer) ServeHTTP

func (s *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

type FilesystemCache

type FilesystemCache struct {
	// contains filtered or unexported fields
}

FilesystemCache is a helper to write the response into the tmp directory. The response is then served with http.FileServer, with the advantage of supporting range request and cache validation. If the file is not modified, the response is a 304. For even better performance, we need to add Cache-Control header to take advantage of the fact that the filename is hashed. However, http.FileServer does not support Cache-Control. Unconditionally adding Cache-Control for non-existent file is problematic.

func NewFilesystemCache

func NewFilesystemCache() *FilesystemCache

func (*FilesystemCache) Clear

func (c *FilesystemCache) Clear() error

func (*FilesystemCache) Serve

func (c *FilesystemCache) Serve(r *http.Request, make func() ([]byte, error)) (handler http.Handler)

type FlashMessage

type FlashMessage struct {
	Cookies FlashMessageCookieManager
}

func (*FlashMessage) Flash

func (f *FlashMessage) Flash(rw http.ResponseWriter, messageType string)

func (*FlashMessage) Pop

type FlashMessageCookieManager

type FlashMessageCookieManager interface {
	GetCookie(r *http.Request, def *CookieDef) (*http.Cookie, error)
	ValueCookie(def *CookieDef, value string) *http.Cookie
	ClearCookie(def *CookieDef) *http.Cookie
}

type GzipMiddleware

type GzipMiddleware struct{}

func (GzipMiddleware) Handle

func (m GzipMiddleware) Handle(next http.Handler) http.Handler

type HTTPHost

type HTTPHost string

type HTTPOrigin

type HTTPOrigin string

func MakeHTTPOrigin

func MakeHTTPOrigin(proto HTTPProto, host HTTPHost) HTTPOrigin

type HTTPPermissionsPolicy

type HTTPPermissionsPolicy []PermissionsPolicyPolicy

func (HTTPPermissionsPolicy) String

func (p HTTPPermissionsPolicy) String() string

type HTTPProto

type HTTPProto string

type JSONOption

type JSONOption func(option *jsonOption)

func WithBodyMaxSize

func WithBodyMaxSize(size int64) JSONOption

type JSONResponseWriter

type JSONResponseWriter struct {
	Logger JSONResponseWriterLogger
}

func (*JSONResponseWriter) WriteResponse

func (w *JSONResponseWriter) WriteResponse(rw http.ResponseWriter, resp *api.Response)

type JSONResponseWriterLogger

type JSONResponseWriterLogger struct{ *log.Logger }

func NewJSONResponseWriterLogger

func NewJSONResponseWriterLogger(lf *log.Factory) JSONResponseWriterLogger

type PermissionsPolicyAllowlist

type PermissionsPolicyAllowlist string

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy#allowlist

const (
	PermissionsPolicyAllowlistAll  PermissionsPolicyAllowlist = "*"
	PermissionsPolicyAllowlistNone PermissionsPolicyAllowlist = "()"
	PermissionsPolicyAllowlistSelf PermissionsPolicyAllowlist = "(self)"
	PermissionsPolicyAllowlistSrc  PermissionsPolicyAllowlist = "(src)"
)

type PermissionsPolicyDirective

type PermissionsPolicyDirective string

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy#directives

const (
	PermissionsPolicyDirectiveAccelerometer               PermissionsPolicyDirective = "accelerometer"
	PermissionsPolicyDirectiveAmbientLightSensor          PermissionsPolicyDirective = "ambient-light-sensor"
	PermissionsPolicyDirectiveAutoplay                    PermissionsPolicyDirective = "autoplay"
	PermissionsPolicyDirectiveBattery                     PermissionsPolicyDirective = "battery"
	PermissionsPolicyDirectiveBluetooth                   PermissionsPolicyDirective = "bluetooth"
	PermissionsPolicyDirectiveBrowsingTopics              PermissionsPolicyDirective = "browsing-topics"
	PermissionsPolicyDirectiveCamera                      PermissionsPolicyDirective = "camera"
	PermissionsPolicyDirectiveDisplayCapture              PermissionsPolicyDirective = "display-capture"
	PermissionsPolicyDirectiveDocumentDomain              PermissionsPolicyDirective = "document-domain"
	PermissionsPolicyDirectiveEncryptedMedia              PermissionsPolicyDirective = "encrypted-media"
	PermissionsPolicyDirectiveExecutionWhileNotRendered   PermissionsPolicyDirective = "execution-while-not-rendered"
	PermissionsPolicyDirectiveExecutionWhileOutOfViewport PermissionsPolicyDirective = "execution-while-out-of-viewport"
	PermissionsPolicyDirectiveFullscreen                  PermissionsPolicyDirective = "fullscreen"
	PermissionsPolicyDirectiveGamepad                     PermissionsPolicyDirective = "gamepad"
	PermissionsPolicyDirectiveGeolocation                 PermissionsPolicyDirective = "geolocation"
	PermissionsPolicyDirectiveGyroscope                   PermissionsPolicyDirective = "gyroscope"
	PermissionsPolicyDirectiveHid                         PermissionsPolicyDirective = "hid"
	PermissionsPolicyDirectiveIdentityCredentialsGet      PermissionsPolicyDirective = "identity-credentials-get"
	PermissionsPolicyDirectiveIdleDetection               PermissionsPolicyDirective = "idle-detection"
	PermissionsPolicyDirectiveLocalFonts                  PermissionsPolicyDirective = "local-fonts"
	PermissionsPolicyDirectiveMagnetometer                PermissionsPolicyDirective = "magnetometer"
	PermissionsPolicyDirectiveMicrophone                  PermissionsPolicyDirective = "microphone"
	PermissionsPolicyDirectiveMidi                        PermissionsPolicyDirective = "midi"
	PermissionsPolicyDirectiveOtpCredentials              PermissionsPolicyDirective = "otp-credentials"
	PermissionsPolicyDirectivePayment                     PermissionsPolicyDirective = "payment"
	PermissionsPolicyDirectivePictureInPicture            PermissionsPolicyDirective = "picture-in-picture"
	PermissionsPolicyDirectivePublickeyCredentialsCreate  PermissionsPolicyDirective = "publickey-credentials-create"
	PermissionsPolicyDirectivePublickeyCredentialsGet     PermissionsPolicyDirective = "publickey-credentials-get"
	PermissionsPolicyDirectiveScreenWakeLock              PermissionsPolicyDirective = "screen-wake-lock"
	PermissionsPolicyDirectiveSerial                      PermissionsPolicyDirective = "serial"
	PermissionsPolicyDirectiveSpeakerSelection            PermissionsPolicyDirective = "speaker-selection"
	PermissionsPolicyDirectiveStorageAccess               PermissionsPolicyDirective = "storage-access"
	PermissionsPolicyDirectiveUsb                         PermissionsPolicyDirective = "usb"
	PermissionsPolicyDirectiveWebShare                    PermissionsPolicyDirective = "web-share"
	PermissionsPolicyDirectiveWindowManagement            PermissionsPolicyDirective = "window-management"
	PermissionsPolicyDirectiveXrSpatialTracking           PermissionsPolicyDirective = "xr-spatial-tracking"
)

type PermissionsPolicyPolicy

type PermissionsPolicyPolicy struct {
	Directive PermissionsPolicyDirective
	Allowlist PermissionsPolicyAllowlist
}

type RemoteIP

type RemoteIP string

type Result

type Result interface {
	WriteResponse(rw http.ResponseWriter, r *http.Request)
	IsInternalError() bool
}

type ResultRedirect

type ResultRedirect struct {
	Cookies []*http.Cookie
	URL     string
}

func (*ResultRedirect) IsInternalError

func (re *ResultRedirect) IsInternalError() bool

func (*ResultRedirect) WriteResponse

func (re *ResultRedirect) WriteResponse(rw http.ResponseWriter, r *http.Request)

type StaticCSPHeader

type StaticCSPHeader struct {
	CSPDirectives []string
}

func (StaticCSPHeader) Handle

func (m StaticCSPHeader) Handle(next http.Handler) http.Handler

type TutorialCookie

type TutorialCookie struct {
	Cookies FlashMessageCookieManager
}

func (*TutorialCookie) Pop

func (*TutorialCookie) SetAll

func (t *TutorialCookie) SetAll(rw http.ResponseWriter)

type TutorialCookieManager

type TutorialCookieManager interface {
	GetCookie(r *http.Request, def *CookieDef) (*http.Cookie, error)
	ValueCookie(def *CookieDef, value string) *http.Cookie
	ClearCookie(def *CookieDef) *http.Cookie
}

type TutorialCookieName

type TutorialCookieName string
const (
	SignupLoginTutorialCookieName TutorialCookieName = "signup_login_tutorial"
	SettingsTutorialCookieName    TutorialCookieName = "settings_tutorial"
)

type UserAgentString

type UserAgentString string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL