Documentation ΒΆ
Index ΒΆ
- Variables
- func APIVersionMatch(version string) func(next http.Handler) http.Handlerdeprecated
- func AddErrorResolver(r ErrorResolver)
- func AddLogHandler(h LogHandler)
- func Bind(r *http.Request, v any) (err error)
- func ErrorCode(w http.ResponseWriter, r *http.Request, statusCode int, err error) bool
- func GetContextIP(ctx context.Context) net.IP
- func IDFromContext[ID comparable](ctx context.Context) (id ID)
- func IdentFromContext[Ident any](ctx context.Context) (auth *Ident)
- func IsDebug(r *http.Request) bool
- func IsDebugCtx(ctx context.Context) bool
- func JSON(w http.ResponseWriter, r *http.Request, status int, v any)
- func Log(r *http.Request) log.Interface
- func OverrideContextAuth[Ident any, ID comparable](parent context.Context, id ID, ident *Ident, roles []string) context.Context
- func Recoverer(next http.Handler) http.Handlerdeprecated
- func Run(srv *http.Server, runners ...Runner) error
- func RunContext(ctx context.Context, srv *http.Server, runners ...Runner) error
- func RunCtx(ctx context.Context, srv *http.Server, runners ...Runner) errordeprecated
- func RunTLS(srv *http.Server, certFile, keyFile string, runners ...Runner) error
- func RunTLSContext(ctx context.Context, srv *http.Server, certFile, keyFile string, ...) error
- func SecureRedirect(w http.ResponseWriter, r *http.Request, status int, fallback string)
- func SkipNextURL(r *http.Request) *http.Request
- func UnwrapError(err error) (resultErr error, statusCode int)
- func UseAPIKeyRequired(keys []string) func(next http.Handler) http.Handler
- func UseAPIVersionMatch(version string) func(next http.Handler) http.Handler
- func UseAuthContext[Ident any, ID comparable, Service AuthServiceReader[Ident, ID]](auth Service) func(next http.Handler) http.Handler
- func UseAuthRequired[Ident any](next http.Handler) http.Handler
- func UseContextIP(next http.Handler) http.Handler
- func UseDebug(debug bool) func(next http.Handler) http.Handler
- func UseHeaders(headers map[string]string) func(next http.Handler) http.Handler
- func UseIf(cond bool, handler func(http.Handler) http.Handler) func(http.Handler) http.Handler
- func UseNextURL(next http.Handler) http.Handler
- func UsePrivateIP(next http.Handler) http.Handler
- func UsePrometheus(next http.Handler) http.Handler
- func UseRealIP(trusted []string, flags RealIPOptions) func(next http.Handler) http.Handler
- func UseRealIPCLIOpts(options []string) func(next http.Handler) http.Handler
- func UseRealIPDefault(next http.Handler) http.Handler
- func UseRecoverer(next http.Handler) http.Handler
- func UseRobotsTxt(custom string) func(next http.Handler) http.Handler
- func UseRoleRequired[ID comparable](role string) func(http.Handler) http.Handler
- func UseSecurityTxt(config *SecurityConfig) func(next http.Handler) http.Handler
- func UseStatic(ctx context.Context, config *Static) http.Handler
- func UseStructuredLogger(logger log.Interface) func(next http.Handler) http.Handler
- func WrapCode(code int) error
- func WrapError(err error, code int) error
- type AuthHandler
- func (h *AuthHandler[Ident, ID]) AddToContext(next http.Handler) http.Handlerdeprecated
- func (h *AuthHandler[Ident, ID]) AuthRequired(next http.Handler) http.Handlerdeprecated
- func (h *AuthHandler[Ident, ID]) FromContext(ctx context.Context) (auth *Ident)deprecated
- func (h *AuthHandler[Ident, ID]) RoleRequired(role string) func(http.Handler) http.Handlerdeprecated
- func (h *AuthHandler[Ident, ID]) RolesFromContext(ctx context.Context) (roles AuthRoles)deprecated
- func (h *AuthHandler[Ident, ID]) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *AuthHandler[Ident, ID]) SetErrorHandler(handler ErrorHandler)
- type AuthRoles
- type AuthService
- type AuthServiceReader
- type BasicAuthHandler
- type BasicAuthService
- type ErrRealIPInvalidIP
- type ErrWithStatusCode
- type ErrorHandler
- type ErrorResolver
- type LogHandler
- type M
- type RealIPOptions
- type Runner
- type SecurityConfig
- type Static
- type Validatable
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( // DefaultAPIVersionHeader is the default header name for the API version. DefaultAPIVersionHeader = "X-Api-Version" // DefaultErrorHandler is the default header where we should look for the // API key. DefaultAPIKeyHeader = "X-Api-Key" //nolint:gosec // DefaultAPIPrefix is the default prefix for your API. Set to an empty // string to disable checks that change depending on if the request has // the provided prefix. DefaultAPIPrefix = "/api/" )
var ( // DefaultCookieSecure allows enabling the secure flag on the session cookie. DefaultCookieSecure = false // DefaultCookieMaxAge is the max age for the session cookie. DefaulltCookieMaxAge = 30 * 86400 )
var ( // DefaultDecoder is the default decoder used by Bind. You can either override // this, or provide your own. Make sure it is set before Bind is called. DefaultDecoder = form.NewDecoder() // DefaultDecodeMaxMemory is the maximum amount of memory in bytes that will be // used for decoding multipart/form-data requests. DefaultDecodeMaxMemory int64 = 8 << 20 // DefaultValidator is the default validator used by Bind, when the provided // struct to the Bind() call doesn't implement Validatable. Set this to nil // to disable validation using go-playground/validator. DefaultValidator = validator.New() )
var ( // DefaultMaskError is a flag that can be used to mask errors in the // default error handler. This only impacts errors from 500 onwards. // If debug is enabled via the UseDebug middleware, this flag will be // ignored. DefaultMaskError = true ErrAccessDenied = errors.New("access denied") ErrAPIKeyInvalid = errors.New("invalid api key provided") ErrAPIKeyMissing = errors.New("api key not specified") ErrNoAPIKeys = errors.New("no api keys provided in initialization") ErrAPIVersionMissing = errors.New("api version not specified") ErrAPIVersionMismatch = errors.New("server and client version mismatch") ErrRealIPNoOpts = errors.New("realip: no options specified") ErrRealIPNoSource = errors.New("realip: no real IP source specified (OptUseXForwardedFor, OptUseXRealIP, or OptUseTrueClientIP, OptUseCFConnectingIP)") ErrRealIPNoTrusted = errors.New("realip: no trusted proxies or bogon IPs specified") ErrAuthNotFound = errors.New("auth: no authentiation found") ErrAuthMissingRole = errors.New("auth: missing necessary role") )
var Error = defaultErrorHandler
Error handles the error (if any). Handler WILL respond to the request with a header and a response if there is an error. The return boolean tells the caller if the handler has responded to the request or not. If the request includes /api/ as the prefix (see DefaultAPIPrefix), the response will be JSON.
If you'd like a specific status code to be returned, there are four options:
- Use AddErrorResolver() to add a custom resolver for err -> status code.
- Use WrapError() to wrap the error with a given status code.
- Use WrapCode() to make an error from a given status code (if you don't have an error that you can provide).
- If none of the above apply, http.StatusInternalServerError will be returned.
NOTE: if you override this function, you must call chix.UnwrapError() on the error to get the original error, and the status code, if any of the above are used.
Functions ΒΆ
func AddErrorResolver ΒΆ
func AddErrorResolver(r ErrorResolver)
AddErrorResolver can be used to add additional error resolvers to the default error handler. These will not be used if a custom error handler is used.
func AddLogHandler ΒΆ
func AddLogHandler(h LogHandler)
AddLogHandler can be used to inject additional metadata/fields into the log context. Use this to add things like authentication information, or similar, to the log entry.
NOTE: the request context will only include entries that were registered in the request context prior to the structured logger being loaded.
func Bind ΒΆ
Bind decodes the request body to the given struct. Take a look at DefaultDecoder to add additional customizations to the default decoder. You can add additional customizations by using the Validatable interface, with a custom implementation of the Validate() method on v. Alternatively, chix also supports the go-playground/validator package, which allows various validation methods via struct tags.
At this time the only supported content-types are application/json, application/x-www-form-urlencoded, as well as GET parameters.
If validation fails, an error that is wrapped with the necessary status code will be returned (can just pass to chix.Error() and it will know the appropriate HTTP code to return, and if it should be a JSON body or not).
func ErrorCode ΒΆ
ErrorCode is a helper function for Error() that includes a status code in the response. See also chix.WrapError() and chix.WrapCode().
func GetContextIP ΒΆ
GetContextIP can be used to retrieve the IP from the context, that was previously set by UseContextIP. If no IP was set, nil is returned.
func IDFromContext ΒΆ
func IDFromContext[ID comparable](ctx context.Context) (id ID)
IDFromContext returns the user ID from the request context, if any. Note that this will only work if the UseAuthContext middleware has been loaded, and the user is authenticated.
Returns 0 if the user is not authenticated or the ID was not found in the context.
func IdentFromContext ΒΆ
IdentFromContext returns the ident from the request context, if any. Note that this will only work if the UseAuthContext middleware has been loaded, and the user is authenticated. Provided Ident type MUST match what is used in AuthHandler.
Returns nil if the user is not authenticated or the ident was not found in the context.
func IsDebug ΒΆ
IsDebug returns true if debugging for the server is enabled (gets the context from the request).
func IsDebugCtx ΒΆ
IsDebugCtx returns true if debugging for the server is enabled.
func JSON ΒΆ
JSON marshals 'v' to JSON, and setting the Content-Type as application/json. Note that this does NOT auto-escape HTML.
JSON also supports prettification when the origin request has "?pretty=true" or similar.
func OverrideContextAuth ΒΆ added in v1.0.3
func OverrideContextAuth[Ident any, ID comparable](parent context.Context, id ID, ident *Ident, roles []string) context.Context
OverrideContextAuth overrides the authentication information in the request, and returns a new context with the updated information. This is useful for when you want to temporarily override the authentication information in the request, such as when you want to impersonate another user, or for mocking in tests.
func Run ΒΆ
Run runs the provided http server, and listens for any termination signals (SIGINT, SIGTERM, SIGQUIT, etc). If runners are provided, those will run concurrently.
If the http server, or any runners return an error, all runners will terminate (assuming they listen to the provided context), and the first known error will be returned. The http server will be gracefully shut down, with a timeout of 10 seconds.
func RunContext ΒΆ added in v1.0.1
RunContext is the same as Run, but with the provided context that can be used to externally cancel all runners and the http server.
func RunTLSContext ΒΆ added in v1.0.1
func RunTLSContext(ctx context.Context, srv *http.Server, certFile, keyFile string, runners ...Runner) error
RunTLSContext is the same as Run, but with the provided context that can be used to externally cancel all runners and the http server, and also allows for TLS to be used.
func SecureRedirect ΒΆ
SecureRedirect supports validating that redirect requests fulfill the the following conditions:
- Target URL must match one of:
- Absolute/relative to the same host
- http or https, with a host matching the requested host (no cross-domain, no port matching).
- Target URL can be parsed by url.Parse().
Additionally, if using chix.UseNextURL middleware, and the current session has a "next" URL stored, the redirect will be to that URL. This allows a multi-step authentication flow to be completed, then redirected to the original destination.
func SkipNextURL ΒΆ
SkipNextURL is a middleware that will prevent the next URL (if any), that is loaded by chix.UseNextURL() from being used during a redirect. This is useful when you have to redirect to another source first.
func UnwrapError ΒΆ
UnwrapError is a helper function for retrieving the underlying error and status code from an error that has been wrapped.
func UseAPIKeyRequired ΒΆ
UseAPIKeyRequired is a middleware that checks if the request has the correct API keys provided in the DefaultAPIKeyHeader header. Panics if no keys are provided. Returns http.StatusUnauthorized if an invalid key is provided, and http.StatusPreconditionFailed if no key header is provided.
func UseAPIVersionMatch ΒΆ added in v1.0.1
UseAPIVersionMatch is a middleware that checks if the request has the correct API version provided in the DefaultAPIVersionHeader.
func UseAuthContext ΒΆ added in v1.0.3
func UseAuthContext[Ident any, ID comparable, Service AuthServiceReader[Ident, ID]](auth Service) func(next http.Handler) http.Handler
UseAuthContext adds the user authentication info to the request context, using the cookie session information. If used more than once in the same request middleware chain, it will be a no-op.
func UseAuthRequired ΒΆ added in v1.0.3
UseAuthRequired is a middleware that requires the user to be authenticated. Note that this requires the UseAuthContext middleware to be loaded prior to this middleware.
func UseContextIP ΒΆ
UseContextIP can be used to add the requests IP to the context. This is beneficial for passing the request context to a request-unaware function/method/service, that does not have access to the original request. Ensure that this middleware is registered after UseRealIP, otherwise the stored IP may be incorrect.
func UseDebug ΒΆ
UseDebug is a middleware that allows passing if debugging is enabled for the http server. Use IsDebug to check if debugging is enabled.
func UseHeaders ΒΆ
UseHeaders is a convenience handler to set multiple response header key/value pairs. Similar to go-chi's SetHeader, but allows for multiple headers to be set at once.
func UseIf ΒΆ
UseIf is a conditional middleware that only uses the provided middleware if the condition is true, otherwise continues as normal.
func UseNextURL ΒΆ
UseNextURL is a middleware that will store the current URL provided via the "next" query parameter, as a cookie in the response, for use with multi-step authentication flows. This allows the user to be redirected back to the original destination after authentication. Must use chix.SecureRedirect to redirect the user, which will pick up the url from the cookie.
func UsePrivateIP ΒΆ
UsePrivateIP can be used to allow only private IP's to access specific routes. Make sure to register this middleware after UseRealIP, otherwise the IP checking may be incorrect.
func UseRealIP ΒΆ
UseRealIP is a middleware that allows passing the real IP address of the client only if the request headers that include an override, come from a trusted proxy. Pass an optional list of trusted proxies to trust, as well as any additional options to control the behavior of the middleware. See the related Opt* constants for more information. Will panic if invalid IP's or ranges are specified.
NOTE: if multiple headers are configured to be trusted, the lookup order is:
- CF-Connecting-IP
- X-Real-IP
- True-Client-IP
- X-Forwarded-For
Examples:
router.Use(chix.UseRealIP([]string{"1.2.3.4", "10.0.0.0/24"}, chix.OptUseXForwardedFor)) router.Use(nil, chix.OptTrustBogon|chix.OptUseXForwardedFor))
func UseRealIPCLIOpts ΒΆ
UseRealIPCLIOpts is a convenience function that wraps RealIP, with support for configuring the middleware via CLI flags. You can pass in an array that contains a mix of different supported headers, "cloudflare", "*" (or "any", "all") to trust anything, "local" (or "localhost", "bogon", "internal") for bogon IPs, and anything else gets passed in as allowed CIDRs.
If no options are passed in, the default will use the same as chix.UseRealIPDefault (OptTrustBogon and OptUseXForwardedFor).
func UseRealIPDefault ΒΆ
UseRealIPDefault is a convenience function that wraps RealIP with the default options (OptTrustBogon and OptUseXForwardedFor).
func UseRecoverer ΒΆ added in v1.0.1
UseRecoverer is a middleware that recovers from panics, and returns a chix.Error with HTTP 500 status (Internal Server Error) if possible. If debug is enabled, through UseDebug(), a stack trace will be printed to stderr, otherwise to standard structured logging.
NOTE: This middleware should be loaded after logging/request-id/use-debug, etc middleware, but before the handlers that may panic.
func UseRobotsTxt ΒΆ
UseRobotsTxt returns a handler that serves a robots.txt file. When custom is empty, the default robots.txt is served (disallow <DefaultAPIPrefix>*, allow /).
You can also use go:embed to embed the robots.txt file into your binary. Example:
//go:embed your/robots.txt var robotsTxt string [...] chix.UseRobotsTxt(router, robotsTxt)
func UseRoleRequired ΒΆ added in v1.0.3
UseRoleRequired is a middleware that requires the user to have the given roles, provided via AuthService or BasicAuthService. Note that this requires the UseAuthContext middleware to be loaded prior to this middleware.
func UseSecurityTxt ΒΆ
func UseSecurityTxt(config *SecurityConfig) func(next http.Handler) http.Handler
UseSecurityTxt returns a handler that serves a security.txt file at the standardized path(s). Only the provided fields will be included in the response.
func UseStatic ΒΆ
UseStatic returns a handler that serves static files from the provided embedded filesystem, with support for using the direct filesystem when debugging is enabled.
Example usage:
//go:embed all:public/dist var publicDist embed.FS [...] router.Mount("/static", chix.UseStatic(&chix.Static{ FS: publicDist, Prefix: "/static", AllowLocal: true, Path: "public/dist" }))
func UseStructuredLogger ΒΆ
UseStructuredLogger wraps each request and writes a log entry with extra info. UseStructuredLogger also injects a logger into the request context that can be used by children middleware business logic.
func WrapCode ΒΆ
WrapCode is a helper function that returns an error using the status text of the given http status code. This is useful if you don't have an explicit error to respond with. Example usage:
chix.Error(w, r, chix.WrapCode(http.StatusBadRequest)) return chix.Error(w, r, chix.WrapCode(500)) return
Types ΒΆ
type AuthHandler ΒΆ
type AuthHandler[Ident any, ID comparable] struct { Auth AuthService[Ident, ID] Ident *Ident ID *ID // contains filtered or unexported fields }
AuthHandler wraps all authentication logic for oauth calls.
func NewAuthHandler ΒΆ
func NewAuthHandler[Ident any, ID comparable]( auth AuthService[Ident, ID], authKey, encryptKey string, ) *AuthHandler[Ident, ID]
NewAuthHandler creates a new AuthHandler. authKey is used to validate the session cookie. encryptKey is used to encrypt the session cookie.
It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes. Provide the keys in hexadecimal string format. The following link can be used to generate a random key:
The following endpoints are implemented:
- GET: <mount>/self - returns the current user authentication info.
- GET: <mount>/providers - returns a list of all available providers.
- GET: <mount>/providers/{provider} - initiates the provider authentication.
- GET: <mount>/providers/{provider}/callback - redirect target from the provider.
- GET: <mount>/logout - logs the user out.
func (*AuthHandler[Ident, ID]) AddToContext
deprecated
func (h *AuthHandler[Ident, ID]) AddToContext(next http.Handler) http.Handler
Deprecated: use UseAuthContext instead.
func (*AuthHandler[Ident, ID]) AuthRequired
deprecated
func (h *AuthHandler[Ident, ID]) AuthRequired(next http.Handler) http.Handler
Deprecated: use UseAuthRequired instead.
func (*AuthHandler[Ident, ID]) FromContext
deprecated
func (h *AuthHandler[Ident, ID]) FromContext(ctx context.Context) (auth *Ident)
Deprecated: use IdentFromContext instead.
func (*AuthHandler[Ident, ID]) RoleRequired
deprecated
Deprecated: use UseRoleRequired instead.
func (*AuthHandler[Ident, ID]) RolesFromContext
deprecated
func (h *AuthHandler[Ident, ID]) RolesFromContext(ctx context.Context) (roles AuthRoles)
Deprecated: use RolesFromContext instead.
func (*AuthHandler[Ident, ID]) ServeHTTP ΒΆ
func (h *AuthHandler[Ident, ID]) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*AuthHandler[Ident, ID]) SetErrorHandler ΒΆ
func (h *AuthHandler[Ident, ID]) SetErrorHandler(handler ErrorHandler)
SetErrorHandler sets the error handler for AuthHandler. This error handler will only be used for errors that occur within the callback process, NOT for middleware, in which chix.Error() will still be used.
type AuthRoles ΒΆ
type AuthRoles []string
AuthRoles provides helper methods for working with roles.
func RolesFromContext ΒΆ
RolesFromContext returns the user roles from the request context, if any. Note that this will only work if the UseAuthContext middleware has been loaded, and the user is authenticated.
type AuthService ΒΆ
type AuthService[Ident any, ID comparable] interface { Get(context.Context, ID) (*Ident, error) Set(context.Context, *goth.User) (ID, error) Roles(context.Context, ID) ([]string, error) }
AuthService is the interface for the authentication service. This will need to be implemented to utilize AuthHandler.
type AuthServiceReader ΒΆ added in v1.0.3
type BasicAuthHandler ΒΆ added in v1.0.3
type BasicAuthHandler[Ident any] struct { Auth BasicAuthService[Ident] Ident *Ident // contains filtered or unexported fields }
BasicAuthHandler wraps all authentication logic for basic auth calls.
func NewBasicAuthHandler ΒΆ added in v1.0.3
func NewBasicAuthHandler[Ident any]( auth BasicAuthService[Ident], authKey, encryptKey string, ) *BasicAuthHandler[Ident]
NewAuthHandler creates a new AuthHandler. authKey is used to validate the session cookie. encryptKey is used to encrypt the session cookie.
It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes. Provide the keys in hexadecimal string format. The following link can be used to generate a random key:
The following endpoints are implemented:
- GET: <mount>/self - returns the current user authentication info.
- GET: <mount>/login - initiates the provider authentication, using basic auth.
- GET: <mount>/logout - logs the user out.
func (*BasicAuthHandler[Ident]) ServeHTTP ΒΆ added in v1.0.3
func (h *BasicAuthHandler[Ident]) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*BasicAuthHandler[Ident]) SetErrorHandler ΒΆ added in v1.0.3
func (h *BasicAuthHandler[Ident]) SetErrorHandler(handler ErrorHandler)
SetErrorHandler sets the error handler for BasicAuthHandler. This error handler will only be used for errors that occur within the callback process, NOT for middleware, in which chix.Error() will still be used.
type BasicAuthService ΒΆ added in v1.0.3
type ErrRealIPInvalidIP ΒΆ
type ErrRealIPInvalidIP struct {
Err error
}
func (ErrRealIPInvalidIP) Error ΒΆ
func (e ErrRealIPInvalidIP) Error() string
func (ErrRealIPInvalidIP) Unwrap ΒΆ
func (e ErrRealIPInvalidIP) Unwrap() error
type ErrWithStatusCode ΒΆ
ErrWithStatusCode is an error wrapper that bundles a given status code, that can be used by chix.Error() as the response code. See chix.WrapError() and chix.WrapCode().
func (ErrWithStatusCode) Error ΒΆ
func (e ErrWithStatusCode) Error() string
func (ErrWithStatusCode) Unwrap ΒΆ
func (e ErrWithStatusCode) Unwrap() error
type ErrorHandler ΒΆ
ErrorHandler is a function that, depending on the input, will either respond to a request with a given response structured based off an error or do nothing, if there isn't actually an error.
type ErrorResolver ΒΆ
ErrorResolver is a function that converts an error to a status code. If 0 is returned, the originally provided status code will be used. Resolvers are useful in situations where you want to return a different error when the error contains a database-related error (like duplicate key already exists, returning a 400 by default), of when you can check if the error is due to user input.
type LogHandler ΒΆ
LogHandler is a function type that can be used to add any additional custom fields to a request log entry.
type M ΒΆ
M is a convenience alias for quickly building a map structure that is going out to a responder. Just a short-hand.
type RealIPOptions ΒΆ
type RealIPOptions int
RealIPOptions is a bitmask of options that can be passed to RealIP.
const ( OptTrustBogon RealIPOptions = 1 << iota // Trust bogon IP ranges (private IP ranges). OptTrustAny // Trust any proxy (DON'T USE THIS!). OptTrustCloudflare // Trust Cloudflare's origin IPs. OptUseXForwardedFor // Allow using the X-Forwarded-For header. OptUseXRealIP // Allow using the X-Real-IP header. OptUseTrueClientIP // Allow using the True-Client-IP header. OptUseCFConnectingIP // Allow using the CF-Connecting-IP header. OptDefaultTrust = OptTrustBogon | OptUseXForwardedFor // Default trust options. )
type Runner ΒΆ
func RunnerInterval ΒΆ added in v1.0.1
type SecurityConfig ΒΆ
type SecurityConfig struct { // Expires is the time when the content of the security.txt file should // be considered stale (so security researchers should then not trust it). // Make sure you update this value periodically and keep your file under // review. Expires time.Time // ExpiresIn is similar to Expires, but uses a given timeframe from when // the http server was started. ExpiresIn time.Duration // Contacts contains links or e-mail addresses for people to contact you // about security issues. Remember to include "https://" for URLs, and // "mailto:" for e-mails (this will be auto-included if it contains an @ // character). Contacts []string // KeyLinks contains links to keys which security researchers should use // to securely talk to you. Remember to include "https://". KeyLinks []string // Languages is a list of language codes that your security team speaks. Languages []string // Acknowledgements contains links to webpages where you say thank you // to security researchers who have helped you. Remember to include // "https://". Acknowledgements []string // Policies contains links to policies detailing what security researchers // should do when searching for or reporting security issues. Remember // to include "https://". Policies []string // Canonical contains the URLs for accessing your security.txt file. It // is important to include this if you are digitally signing the // security.txt file, so that the location of the security.txt file can // be digitally signed too. Canonical []string }
SecurityConfig configures the security.txt middleware.
func (*SecurityConfig) ServeHTTP ΒΆ
func (h *SecurityConfig) ServeHTTP(w http.ResponseWriter, _ *http.Request)
type Static ΒΆ
type Static struct { // fs is the filesystem to serve. FS fs.FS // Prefix is the prefix where the filesystem is mounted on your http router. Prefix string // CatchAll is a boolean that determines if chix.Static is being used as a // catch-all for not-found routes. If so, it will do extra validations for // using chix.Error when the route is related to an API endpoint (see // chix.DefaultAPIPrefix), as well as enforce specific methods. CatchAll bool // AllowLocal is a boolean that, if true, and chix.LocalPath exists, it will // bypass the provided filesystem and instead use the actual filesystem. AllowLocal bool // LocalPath is the subpath to use when AllowLocal is enabled. If empty, it // will default to Static.Path. It will check for this sub-directory in either // the current working directory, or the executable directory. LocalPath string // Path of the embedded filesystem, instead of the entire filesystem. go:embed // will include the target that gets embedded, as a prefix to the path. // // For example, given "go:embed all:public/dist", mounted at "/static", you // would normally have to access using "/static/public/dist/<etc>". Providing // path, where path is "public/dist", you can access the same files // via "/static/<etc>". Path string // SPA is a boolean that, if true, will serve a single page application, i.e. // redirecting all files not found, to the index.html file. SPA bool // Headers is a map of headers to set on the response (e.g. cache headers). // Example: // &chix.Static{ // [...] // Headers: map[string]string{ // "Vary": "Accept-Encoding", // "Cache-Control": "public, max-age=7776000", // }, // } Headers map[string]string // contains filtered or unexported fields }
Static is an http.Handler that serves static files from an embedded filesystem. See chix.UseStatic() for more information.
type Validatable ΒΆ
type Validatable interface {
Validate() error
}
Validatable is an interface that can be implemented by structs to provide custom validation logic, on top of the default go-playground/form validation.