chix

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2024 License: MIT Imports: 34 Imported by: 2

README ΒΆ

logo

πŸ”— Table of Contents

βš™ Usage

go get -u github.com/lrstanley/chix@latest

✨ Features

  • http.Server wrapper that easily allows starting, and gracefully shutting down your http server, and other background services, using errgroup.
  • RealIP middleware (supports whitelisting specific proxies, rather than allowing any source).
  • private IP middleware, restricting endpoints to be internal only.
  • Rendering helpers:
    • JSON (with ?pretty=true support).
  • Auth middleware:
    • Uses markbates/goth to support many different providers.
    • Encrypts session cookies, which removes the need for local session storage.
    • Uses Go 1.18's generics functionality to provide a custom ID and auth object resolver.
      • No longer have to type assert to your local models!
    • Optionally requiring authentication.
    • Optionally requiring specific roles.
    • Optionally adding authentication info to context for use by children handlers.
    • API key validation.
    • API version validation.
  • Struct/type binding, from get/post data, with support for go-playground/validator.
  • Structured logging using apex/log (same API as logrus).
    • Allows injecting additional metadata into logs.
    • Injects logger into context for use by children handlers.
  • Debug middleware:
    • Easily let children handlers know if global debug flags are enabled.
    • Allows masking errors, unless debugging is enabled.
  • Error handler, that automatically handles api-vs-static content responses.
    • Supports ErrorResolver's, providing the ability to override status codes for specific types of errors.
  • go:embed helpers for mounting an embedded filesystem seamlessly as an http endpoint.
    • Useful for projects that bundle their frontend assets in their binary.
    • Supports local filesystem reading, when debugging is enabled (TODO).
  • Middleware for robots.txt and security.txt responding.
  • lrstanley/clix -- go-flags wrapper, that handles parsing and decoding, with additional helpers.
  • lrstanley/go-query-parser -- similar to that of Google/Github/etc search, a query string parser that allows filters and tags to be dynamically configured by the end user.

πŸ’‘ Example Projects

Use these as a reference point for how you might use some of the functionality within this library, or how you might want to structure your applications.

πŸ™‹β™‚ Support & Assistance

  • ❀ Please review the Code of Conduct for guidelines on ensuring everyone has the best experience interacting with the community.
  • πŸ™‹β™‚ Take a look at the support document on guidelines for tips on how to ask the right questions.
  • 🐞 For all features/bugs/issues/questions/etc, head over here.

🀝 Contributing

  • ❀ Please review the Code of Conduct for guidelines on ensuring everyone has the best experience interacting with the community.
  • πŸ“‹ Please review the contributing doc for submitting issues/a guide on submitting pull requests and helping out.
  • πŸ— For anything security related, please review this repositories security policy.

βš– License

MIT License

Copyright (c) 2022 Liam Stanley <liam@liam.sh>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Also located here

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
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/"
)
View Source
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
)
View Source
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()
)
View Source
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")
)
View Source
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:

  1. Use AddErrorResolver() to add a custom resolver for err -> status code.
  2. Use WrapError() to wrap the error with a given status code.
  3. Use WrapCode() to make an error from a given status code (if you don't have an error that you can provide).
  4. 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 APIVersionMatch deprecated

func APIVersionMatch(version string) func(next http.Handler) http.Handler

Deprecated: APIVersionMatch is deprecated, and will be removed in a future release. Please use UseAPIVersionMatch instead.

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

func Bind(r *http.Request, v any) (err error)

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

func ErrorCode(w http.ResponseWriter, r *http.Request, statusCode int, err error) bool

ErrorCode is a helper function for Error() that includes a status code in the response. See also chix.WrapError() and chix.WrapCode().

func GetContextIP ΒΆ

func GetContextIP(ctx context.Context) net.IP

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

func IdentFromContext[Ident any](ctx context.Context) (auth *Ident)

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

func IsDebug(r *http.Request) bool

IsDebug returns true if debugging for the server is enabled (gets the context from the request).

func IsDebugCtx ΒΆ

func IsDebugCtx(ctx context.Context) bool

IsDebugCtx returns true if debugging for the server is enabled.

func JSON ΒΆ

func JSON(w http.ResponseWriter, r *http.Request, status int, v any)

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 Log ΒΆ

func Log(r *http.Request) log.Interface

Log is a helper for obtaining the structured logger from the request context.

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

func Recoverer(next http.Handler) http.Handler

Deprecated: Recoverer is deprecated, and will be removed in a future release. Please use UseRecoverer instead.

func Run ΒΆ

func Run(srv *http.Server, runners ...Runner) error

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

func RunContext(ctx context.Context, srv *http.Server, runners ...Runner) error

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

func RunCtx(ctx context.Context, srv *http.Server, runners ...Runner) error

Deprecated: Use RunContext instead.

func RunTLS ΒΆ added in v1.0.1

func RunTLS(srv *http.Server, certFile, keyFile string, runners ...Runner) error

RunTLS is the same as Run, but allows for TLS to be used.

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

func SecureRedirect(w http.ResponseWriter, r *http.Request, status int, fallback string)

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

func SkipNextURL(r *http.Request) *http.Request

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

func UnwrapError(err error) (resultErr error, statusCode int)

UnwrapError is a helper function for retrieving the underlying error and status code from an error that has been wrapped.

func UseAPIKeyRequired ΒΆ

func UseAPIKeyRequired(keys []string) func(next http.Handler) http.Handler

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

func UseAPIVersionMatch(version string) func(next http.Handler) http.Handler

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

func UseAuthRequired[Ident any](next http.Handler) http.Handler

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

func UseContextIP(next http.Handler) http.Handler

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

func UseDebug(debug bool) func(next http.Handler) http.Handler

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

func UseHeaders(headers map[string]string) func(next http.Handler) http.Handler

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

func UseIf(cond bool, handler func(http.Handler) http.Handler) func(http.Handler) http.Handler

UseIf is a conditional middleware that only uses the provided middleware if the condition is true, otherwise continues as normal.

func UseNextURL ΒΆ

func UseNextURL(next http.Handler) http.Handler

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

func UsePrivateIP(next http.Handler) http.Handler

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 UsePrometheus ΒΆ

func UsePrometheus(next http.Handler) http.Handler

func UseRealIP ΒΆ

func UseRealIP(trusted []string, flags RealIPOptions) func(next http.Handler) http.Handler

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

func UseRealIPCLIOpts(options []string) func(next http.Handler) http.Handler

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

func UseRealIPDefault(next http.Handler) http.Handler

UseRealIPDefault is a convenience function that wraps RealIP with the default options (OptTrustBogon and OptUseXForwardedFor).

func UseRecoverer ΒΆ added in v1.0.1

func UseRecoverer(next http.Handler) http.Handler

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

func UseRobotsTxt(custom string) func(next http.Handler) http.Handler

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

func UseRoleRequired[ID comparable](role string) func(http.Handler) http.Handler

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

func UseStatic(ctx context.Context, config *Static) http.Handler

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

func UseStructuredLogger(logger log.Interface) func(next http.Handler) http.Handler

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

func WrapCode(code int) error

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

func WrapError ΒΆ

func WrapError(err error, code int) error

WrapError wraps an error with an http status code, which chix.Error() can use as the response code. Example usage:

if chix.Error(w, r, chix.WrapError(err, http.StatusBadRequest)) {
    return
}

if chix.Error(w, r, chix.WrapError(err, 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

func (h *AuthHandler[Ident, ID]) RoleRequired(role string) func(http.Handler) http.Handler

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

func RolesFromContext(ctx context.Context) (roles AuthRoles)

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.

func (AuthRoles) Has ΒΆ

func (r AuthRoles) Has(role string) bool

Has returns true if the given role is present for the authenticated identity in the context.

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 AuthServiceReader[Ident any, ID comparable] interface {
	Get(context.Context, ID) (*Ident, error)
	Roles(context.Context, ID) ([]string, error)
}

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 BasicAuthService[Ident any] interface {
	BasicAuth(context.Context, string, string) (*Ident, error)
	Get(context.Context, string) (*Ident, error)
	Roles(context.Context, string) ([]string, error)
}

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

type ErrWithStatusCode struct {
	Err  error
	Code int
}

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

type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error) (ok bool)

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

type ErrorResolver func(err error) (status int)

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

type LogHandler func(r *http.Request) M

LogHandler is a function type that can be used to add any additional custom fields to a request log entry.

type M ΒΆ

type M map[string]any

M is a convenience alias for quickly building a map structure that is going out to a responder. Just a short-hand.

func (M) Fields ΒΆ

func (m M) Fields() (f log.Fields)

Fields satisfies the log.Fielder interface.

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

type Runner func(ctx context.Context) error

func RunnerInterval ΒΆ added in v1.0.1

func RunnerInterval(name string, r Runner, frequency time.Duration, runImmediately, exitOnError bool) Runner

func (Runner) Invoke ΒΆ

func (r Runner) Invoke(ctx context.Context) func() error

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.

func (*Static) ServeHTTP ΒΆ

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

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.

Jump to

Keyboard shortcuts

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