httputil

package
v0.0.0-...-81dc835 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2024 License: Apache-2.0 Imports: 34 Imported by: 7

Documentation

Index

Constants

View Source
const BodyMaxSize = 1024 * 1024 * 10

Variables

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

CSPNonceCookieDef is a HTTP session cookie. The nonce has to be stable within a browsing session because Turbo uses XHR to load new pages. If nonce changes on every page load, the script in the new page cannot be run in the current page due to different nonce.

View Source
var CSPSchemeSourceHTTPS = CSPSchemeSource{Scheme: "https"}
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 FileServerIndexHTMLtemplateDataKey = FileServerIndexHTMLTemplateDataKeyType{}
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 CSPNoncePerRequest

func CSPNoncePerRequest(r *http.Request) (nonce string, rWithNonce *http.Request)

func CSPNoncePerSession

func CSPNoncePerSession(cookieManager CSPNoncePerSessionCookieManager, w http.ResponseWriter, r *http.Request) (nonce string, rWithNonce *http.Request)

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 GetCSPNonce

func GetCSPNonce(ctx context.Context) string

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 GetWithContext

func GetWithContext(ctx context.Context, c *http.Client, url string) (resp *http.Response, err error)

GetWithContext is a compat method for http.Client.Get

func HeadWithContext

func HeadWithContext(ctx context.Context, c *http.Client, url string) (resp *http.Response, err error)

HeadWithContext is a compat method for http.Client.Head

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 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 PostFormWithContext

func PostFormWithContext(ctx context.Context, c *http.Client, url string, data url.Values) (resp *http.Response, err error)

PostFormWithContext is a compat method for http.Client.PostForm

func PostWithContext

func PostWithContext(ctx context.Context, c *http.Client, url string, contentType string, body io.Reader) (resp *http.Response, err error)

PostWithContext is a compat method for http.Client.Post

func ShouldSendSameSiteNone

func ShouldSendSameSiteNone(useragent string, secure bool) bool

func UpdateCookie

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

func WithCSPNonce

func WithCSPNonce(ctx context.Context, nonce string) context.Context

func XContentTypeOptionsNosniff

func XContentTypeOptionsNosniff(next http.Handler) http.Handler

func XFrameOptionsDeny

func XFrameOptionsDeny(next http.Handler) http.Handler

func XRobotsTag

func XRobotsTag(next http.Handler) http.Handler

Types

type BodyDefaulter

type BodyDefaulter interface {
	SetDefaults()
}

type CSPDirective

type CSPDirective struct {
	Name  CSPDirectiveName
	Value CSPSources
}

func (CSPDirective) String

func (d CSPDirective) String() string

type CSPDirectiveName

type CSPDirectiveName string
const (

	// connect-src is not needed when there is no default-src.
	// CSPDirectiveNameConnectSrc CSPDirectiveName = "connect-src"
	// font-src is not needed when there is no default-src.
	// CSPDirectiveNameFontSrc    CSPDirectiveName = "font-src"
	// frame-src is not needed when there is no default-src.
	// CSPDirectiveNameFrameSrc   CSPDirectiveName = "frame-src"
	// img-src is not needed when there is no default-src.
	// CSPDirectiveNameImgSrc     CSPDirectiveName = "img-src"
	CSPDirectiveNameObjectSrc CSPDirectiveName = "object-src"
	CSPDirectiveNameScriptSrc CSPDirectiveName = "script-src"

	CSPDirectiveNameBaseURI CSPDirectiveName = "base-uri"
	// CSPDirectiveNameBlockAllMixedContent is deprecated.
	// See https://www.w3.org/TR/mixed-content/#strict-checking
	// CSPDirectiveNameBlockAllMixedContent CSPDirectiveName = "block-all-mixed-content"
	CSPDirectiveNameFrameAncestors CSPDirectiveName = "frame-ancestors"
)

type CSPDirectives

type CSPDirectives []CSPDirective

func (CSPDirectives) String

func (d CSPDirectives) String() string

type CSPHashSource

type CSPHashSource struct {
	Hash string
}

func (CSPHashSource) CSPLevel

func (s CSPHashSource) CSPLevel() int

func (CSPHashSource) String

func (s CSPHashSource) String() string

type CSPHostSource

type CSPHostSource struct {
	Scheme string
	Host   string
}

func (CSPHostSource) CSPLevel

func (s CSPHostSource) CSPLevel() int

func (CSPHostSource) String

func (s CSPHostSource) String() string

type CSPKeywordSourceLevel1

type CSPKeywordSourceLevel1 string
const (
	CSPSourceNone CSPKeywordSourceLevel1 = "'none'"
	CSPSourceSelf CSPKeywordSourceLevel1 = "'self'"
)

func (CSPKeywordSourceLevel1) CSPLevel

func (_ CSPKeywordSourceLevel1) CSPLevel() int

func (CSPKeywordSourceLevel1) String

func (s CSPKeywordSourceLevel1) String() string

type CSPKeywordSourceLevel3

type CSPKeywordSourceLevel3 string
const (
	// 'unsafe-hashes' is not needed when we no longer specify style-src.
	// If you want it to allow inline event handler, you should migrate from inline event handler instead.
	// CSPSourceUnsafeHashes  CSPKeywordSourceLevel3 = "'unsafe-hashes'"
	CSPSourceStrictDynamic CSPKeywordSourceLevel3 = "'strict-dynamic'"
)

func (CSPKeywordSourceLevel3) CSPLevel

func (_ CSPKeywordSourceLevel3) CSPLevel() int

func (CSPKeywordSourceLevel3) String

func (s CSPKeywordSourceLevel3) String() string

type CSPNoncePerSessionCookieManager

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

type CSPNonceSource

type CSPNonceSource struct {
	Nonce string
}

func (CSPNonceSource) CSPLevel

func (s CSPNonceSource) CSPLevel() int

func (CSPNonceSource) String

func (s CSPNonceSource) String() string

type CSPSchemeSource

type CSPSchemeSource struct {
	Scheme string
}

func (CSPSchemeSource) CSPLevel

func (s CSPSchemeSource) CSPLevel() int

func (CSPSchemeSource) String

func (s CSPSchemeSource) String() string

type CSPSource

type CSPSource interface {
	CSPLevel() int
	String() string
}

type CSPSources

type CSPSources []CSPSource

func (CSPSources) Len

func (s CSPSources) Len() int

func (CSPSources) Less

func (s CSPSources) Less(i, j int) bool

func (CSPSources) String

func (s CSPSources) String() string

func (CSPSources) Swap

func (s CSPSources) Swap(i, j int)

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

	// This flag is the inverse of http cookie host-only-flag (RFC6265 section5.3.6), default false
	IsNonHostOnly bool
}

CookieDef defines a cookie that is written to the response. All cookies in our server expects to be created with this definition.

func (*CookieDef) HostOnly

func (cd *CookieDef) HostOnly() bool

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
	Transport      http.RoundTripper
}

type FileServer

type FileServer struct {
	FileSystem          http.FileSystem
	AssetsDir           string
	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. When serving index.html, index.html is assumed to be a Go template. FileServer will use the context value FileServerIndexHTMLTemplateDataKey to render.

func (*FileServer) ServeHTTP

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

type FileServerIndexHTMLTemplateDataKeyType

type FileServerIndexHTMLTemplateDataKeyType struct{}

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 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