web

package
v1.20220411.3 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 38 Imported by: 15

Documentation

Overview

Package web implements a model view controller system for building http servers. It is meant to be composed with other packages to form everything from small api servers to fully formed web view applications.

Basics

To create a web server:

import "github.com/blend/go-sdk/graceful"
import "github.com/blend/go-sdk/logger"
import "github.com/blend/go-sdk/web"

...

app := web.MustNew(web.OptBindAddr(os.Getenv("BIND_ADDR")))
app.GET("/", func(_ *web.Ctx) web.Result {
	return web.Text.Result("hello world")
})
if err := graceful.Shutdown(app); err != nil {
	logger.FatalExit(err)
}

This will start a web server with a trivial endpoint mounted at the path "/" for the HTTP Verb "GET". This example will also start the server and listen for SIGINT and SIGTERM os signals, and close the server gracefully if they're received, letting requests finish.

There are many more examples in the github.com/blend/go-sdk/examples/web directory.

Index

Constants

View Source
const (
	// PackageName is the full name of this package.
	PackageName = "github.com/blend/go-sdk/web"
	// RouteTokenFilepath is a special route token.
	RouteTokenFilepath = "filepath"
	// RegexpAssetCacheFiles is a common regex for parsing css, js, and html file routes.
	RegexpAssetCacheFiles = `^(.*)\.([0-9]+)\.(css|js|html|htm)$`
	// FieldTagPostForm is a field tag you can use to set a struct from a post body.
	FieldTagPostForm = "postForm"
)
View Source
const (
	// DefaultBindAddr is the default bind address.
	DefaultBindAddr = ":8080"
	// DefaultHealthzBindAddr is the default healthz bind address.
	DefaultHealthzBindAddr = ":8081"
	// DefaultMockBindAddr is a bind address used for integration testing.
	DefaultMockBindAddr = "127.0.0.1:0"
	// DefaultSkipRedirectTrailingSlash is the default if we should redirect for missing trailing slashes.
	DefaultSkipRedirectTrailingSlash = false
	// DefaultHandleOptions is a default.
	DefaultHandleOptions = false
	// DefaultHandleMethodNotAllowed is a default.
	DefaultHandleMethodNotAllowed = false
	// DefaultRecoverPanics returns if we should recover panics by default.
	DefaultRecoverPanics = true
	// DefaultMaxHeaderBytes is a default that is unset.
	DefaultMaxHeaderBytes = 0
	// DefaultReadTimeout is a default.
	DefaultReadTimeout = 0
	// DefaultReadHeaderTimeout is a default.
	DefaultReadHeaderTimeout time.Duration = 0
	// DefaultWriteTimeout is a default.
	DefaultWriteTimeout time.Duration = 0
	// DefaultIdleTimeout is a default.
	DefaultIdleTimeout time.Duration = 0
	// DefaultCookieName is the default name of the field that contains the session id.
	DefaultCookieName = "SID"
	// DefaultSecureCookieName is the default name of the field that contains the secure session id.
	DefaultSecureCookieName = "SSID"
	// DefaultCookiePath is the default cookie path.
	DefaultCookiePath = "/"
	// DefaultCookieSecure returns what the default value for the `Secure` bit of issued cookies will be.
	DefaultCookieSecure = true
	// DefaultCookieHTTPOnly returns what the default value for the `HTTPOnly` bit of issued cookies will be.
	DefaultCookieHTTPOnly = true
	// DefaultCookieSameSiteMode is the default cookie same site mode (currently http.SameSiteLaxMode).
	DefaultCookieSameSiteMode = http.SameSiteLaxMode
	// DefaultSessionTimeout is the default absolute timeout for a session (24 hours as a sane default).
	DefaultSessionTimeout time.Duration = 24 * time.Hour
	// DefaultUseSessionCache is the default if we should use the auth manager session cache.
	DefaultUseSessionCache = true
	// DefaultSessionTimeoutIsAbsolute is the default if we should set absolute session expiries.
	DefaultSessionTimeoutIsAbsolute = true
	// DefaultHTTPSUpgradeTargetPort is the default upgrade target port.
	DefaultHTTPSUpgradeTargetPort = 443
	// DefaultKeepAlive is the default setting for TCP KeepAlive.
	DefaultKeepAlive = true
	// DefaultKeepAlivePeriod is the default time to keep tcp connections open.
	DefaultKeepAlivePeriod = 3 * time.Minute
	// DefaultShutdownGracePeriod is the default shutdown grace period.
	DefaultShutdownGracePeriod = 30 * time.Second
	// DefaultHealthzFailureThreshold is the default healthz failure threshold.
	DefaultHealthzFailureThreshold = 3
	// DefaultViewBufferPoolSize is the default buffer pool size.
	DefaultViewBufferPoolSize = 256
)
View Source
const (
	// LenSessionID is the byte length of a session id.
	LenSessionID = 64
	// LenSessionIDBase64 is the length of a session id base64 encoded.
	LenSessionIDBase64 = 88
)
View Source
const (
	// ErrSessionIDEmpty is thrown if a session id is empty.
	ErrSessionIDEmpty ex.Class = "auth session id is empty"
	// ErrSecureSessionIDEmpty is an error that is thrown if a given secure session id is invalid.
	ErrSecureSessionIDEmpty ex.Class = "auth secure session id is empty"
	// ErrUnsetViewTemplate is an error that is thrown if a given secure session id is invalid.
	ErrUnsetViewTemplate ex.Class = "view result template is unset"
	// ErrParameterMissing is an error on request validation.
	ErrParameterMissing ex.Class = "parameter is missing"
	// ErrParameterInvalid is an error on request validation.
	ErrParameterInvalid ex.Class = "parameter is invalid"
)
View Source
const (
	// DefaultTemplateNameBadRequest is the default template name for bad request view results.
	DefaultTemplateNameBadRequest = "bad_request"
	// DefaultTemplateNameInternalError is the default template name for internal server error view results.
	DefaultTemplateNameInternalError = "error"
	// DefaultTemplateNameNotFound is the default template name for not found error view results.
	DefaultTemplateNameNotFound = "not_found"
	// DefaultTemplateNameNotAuthorized is the default template name for not authorized error view results.
	DefaultTemplateNameNotAuthorized = "not_authorized"
	// DefaultTemplateNameStatus is the default template name for status view results.
	DefaultTemplateNameStatus = "status"

	// DefaultTemplateBadRequest is a basic view.
	DefaultTemplateBadRequest = `` /* 154-byte string literal not displayed */
	// DefaultTemplateInternalError is a basic view.
	DefaultTemplateInternalError = `` /* 151-byte string literal not displayed */
	// DefaultTemplateNotAuthorized is a basic view.
	DefaultTemplateNotAuthorized = `` /* 130-byte string literal not displayed */
	// DefaultTemplateNotFound is a basic view.
	DefaultTemplateNotFound = `<html><head><style>body { font-family: sans-serif; text-align: center; }</style></head><body><h4>Not Found</h4></body></html>`
	// DefaultTemplateStatus is a basic view.
	DefaultTemplateStatus = `` /* 179-byte string literal not displayed */
)
View Source
const (
	// ErrJWTNonstandardClaims can be returned by the jwt manager keyfunc.
	ErrJWTNonstandardClaims = ex.Class("jwt; invalid claims object; should be standard claims")
)

Variables

View Source
var (
	ErrInvalidBoolValue = fmt.Errorf("invalid boolean value")
)

Common errors

Functions

func Base64URLDecode

func Base64URLDecode(raw string) ([]byte, error)

Base64URLDecode decodes a base64 string.

func Base64URLEncode

func Base64URLEncode(raw []byte) string

Base64URLEncode base64 encodes data.

func BaseHeaders added in v1.20201204.1

func BaseHeaders() http.Header

BaseHeaders are the default headers added by go-web.

func BoolValue

func BoolValue(value string, inputErr error) (output bool, err error)

BoolValue parses a value as an bool. If the input error is set it short circuits.

func CSVValue

func CSVValue(value string, err error) ([]string, error)

CSVValue just returns the string directly from a value error pair.

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func CopySingleHeaders added in v1.20201204.1

func CopySingleHeaders(headers map[string]string) http.Header

CopySingleHeaders copies headers in single value format.

func DurationValue

func DurationValue(value string, inputErr error) (output time.Duration, err error)

DurationValue parses a value as an time.Duration. If the input error is set it short circuits.

func Float64Value

func Float64Value(value string, inputErr error) (output float64, err error)

Float64Value parses a value as an float64. If the input error is set it short circuits.

func GetRequestStarted added in v1.20201204.1

func GetRequestStarted(ctx context.Context) time.Time

GetRequestStarted gets the request started time from a context.

func Int64Value

func Int64Value(value string, inputErr error) (output int64, err error)

Int64Value parses a value as an int64. If the input error is set it short circuits.

func IntValue

func IntValue(value string, inputErr error) (output int, err error)

IntValue parses a value as an int. If the input error is set it short circuits.

func IsErrBadRequest added in v1.20201204.1

func IsErrBadRequest(err error) bool

IsErrBadRequest returns if an error is a bad request triggering error.

func IsErrParameterInvalid added in v1.20201204.1

func IsErrParameterInvalid(err error) bool

IsErrParameterInvalid returns if an error is an ErrParameterInvalid.

func IsErrParameterMissing added in v1.20201204.1

func IsErrParameterMissing(err error) bool

IsErrParameterMissing returns if an error is an ErrParameterMissing.

func IsErrSessionInvalid

func IsErrSessionInvalid(err error) bool

IsErrSessionInvalid returns if an error is a session invalid error.

func MergeHeaders added in v1.20201204.1

func MergeHeaders(headers ...http.Header) http.Header

MergeHeaders merges headers.

func MockSimulateLogin added in v1.20210215.2

func MockSimulateLogin(ctx context.Context, app *App, userID string, opts ...r2.Option) []r2.Option

MockSimulateLogin simulates a user login for a given app as mocked request params (i.e. r2 options).

This requires an auth manager to be set on the app.

func NewCookie

func NewCookie(name, value string) *http.Cookie

NewCookie returns a new name + value pair cookie.

func NewParameterInvalidError added in v1.20201204.1

func NewParameterInvalidError(paramName, message string) error

NewParameterInvalidError returns a new parameter invalid error.

func NewParameterMissingError added in v1.20201204.1

func NewParameterMissingError(paramName string) error

NewParameterMissingError returns a new parameter missing error.

func NewSessionID

func NewSessionID() string

NewSessionID returns a new session id. It is not a uuid; session ids are generated using a secure random source. SessionIDs are generally 64 bytes.

func PathRedirectHandler

func PathRedirectHandler(path string) func(*Ctx) *url.URL

PathRedirectHandler returns a handler for AuthManager.RedirectHandler based on a path.

func ReadSetCookies

func ReadSetCookies(h http.Header) []*http.Cookie

ReadSetCookies parses all "Set-Cookie" values from the header h and returns the successfully parsed Cookies.

It is a verbatim copy of the one found in `net/http` but exported so you can use it to.

func ResultOrDefault

func ResultOrDefault(result, defaultResult interface{}) interface{}

ResultOrDefault returns a result or a default.

func SessionTimeoutProvider

func SessionTimeoutProvider(isAbsolute bool, timeout time.Duration) func(*Session) time.Time

SessionTimeoutProvider returns a new session timeout provider.

func SessionTimeoutProviderAbsolute

func SessionTimeoutProviderAbsolute(timeout time.Duration) func(*Session) time.Time

SessionTimeoutProviderAbsolute returns an absolute session timeout.

func SessionTimeoutProviderRolling

func SessionTimeoutProviderRolling(timeout time.Duration) func(*Session) time.Time

SessionTimeoutProviderRolling returns a rolling session timeout.

func StringValue

func StringValue(value string, _ error) string

StringValue just returns the string directly from a value error pair.

func UUIDValue added in v1.20210216.1

func UUIDValue(param string, inputErr error) (uuid.UUID, error)

UUIDValue returns a uuid typed value.

func WithApp added in v1.20201204.1

func WithApp(ctx context.Context, app *App) context.Context

WithApp adds an app to a context.

func WithRequestStarted added in v1.20201204.1

func WithRequestStarted(ctx context.Context, requestStarted time.Time) context.Context

WithRequestStarted sets the request started time on a context.

func WithSession added in v1.20201204.1

func WithSession(ctx context.Context, session *Session) context.Context

WithSession sets a session on a context.

Types

type Action

type Action func(*Ctx) Result

Action is the function signature for controller actions.

func GZip added in v1.20201204.1

func GZip(action Action) Action

GZip is a middleware the implements gzip compression for requests that opt into it.

func JSONProviderAsDefault

func JSONProviderAsDefault(action Action) Action

JSONProviderAsDefault sets the context.DefaultResultProvider() equal to context.JSON().

func NestMiddleware

func NestMiddleware(action Action, middleware ...Middleware) Action

NestMiddleware reads the middleware variadic args and organizes the calls recursively in the order they appear. I.e. NestMiddleware(inner, third, second, first) will call "first", "second", "third", then "inner".

func SessionAware

func SessionAware(action Action) Action

SessionAware is an action that injects the session into the context.

func SessionAwareForLogout added in v1.20220411.3

func SessionAwareForLogout(action Action) Action

SessionAwareForLogout is an action that injects the session into the context, but does not extend it if there is a session lifetime handler on the auth manager.

func SessionRequired

func SessionRequired(action Action) Action

SessionRequired is an action that requires a session to be present or identified in some form on the request.

func TextProviderAsDefault

func TextProviderAsDefault(action Action) Action

TextProviderAsDefault sets the context.DefaultResultProvider() equal to context.Text().

func ViewProviderAsDefault

func ViewProviderAsDefault(action Action) Action

ViewProviderAsDefault sets the context.DefaultResultProvider() equal to context.View().

func XMLProviderAsDefault

func XMLProviderAsDefault(action Action) Action

XMLProviderAsDefault sets the context.DefaultResultProvider() equal to context.XML().

type App

type App struct {
	*async.Latch
	*RouteTree

	Config Config

	Auth        AuthManager
	BaseContext func(net.Listener) context.Context

	BaseHeaders    http.Header
	BaseMiddleware []Middleware
	BaseState      State

	Log    logger.Log
	Tracer Tracer

	TLSConfig *tls.Config
	Server    *http.Server
	Listener  net.Listener

	Statics map[string]*StaticFileServer

	DefaultProvider ResultProvider
	Views           *ViewCache

	PanicAction PanicAction
}

App is the server for the app.

func GetApp added in v1.20201204.1

func GetApp(ctx context.Context) *App

GetApp gets an app off a context.

func MustNew added in v1.20201204.1

func MustNew(options ...Option) *App

MustNew creates a new app and panics if there is an error.

func New

func New(options ...Option) (*App, error)

New returns a new web app.

func (*App) Background added in v1.20201204.1

func (a *App) Background() context.Context

Background returns a base context.

func (*App) DELETE

func (a *App) DELETE(path string, action Action, middleware ...Middleware)

DELETE registers a DELETE request route handler with the given middleware.

func (*App) GET

func (a *App) GET(path string, action Action, middleware ...Middleware)

GET registers a GET request route handler with the given middleware.

func (*App) HEAD

func (a *App) HEAD(path string, action Action, middleware ...Middleware)

HEAD registers a HEAD request route handler with the given middleware.

func (*App) Lookup

func (a *App) Lookup(method, path string) (route *Route, params RouteParameters, skipSlashRedirect bool)

Lookup finds the route data for a given method and path.

func (*App) Method added in v1.20201204.1

func (a *App) Method(method string, path string, action Action, middleware ...Middleware)

Method registers an action for a given method and path with the given middleware.

func (*App) MethodBare added in v1.20201204.1

func (a *App) MethodBare(method string, path string, action Action, middleware ...Middleware)

MethodBare registers an action for a given method and path with the given middleware that omits logging and tracing.

func (*App) OPTIONS

func (a *App) OPTIONS(path string, action Action, middleware ...Middleware)

OPTIONS registers a OPTIONS request route handler the given middleware.

func (*App) PATCH

func (a *App) PATCH(path string, action Action, middleware ...Middleware)

PATCH registers a PATCH request route handler with the given middleware.

func (*App) POST

func (a *App) POST(path string, action Action, middleware ...Middleware)

POST registers a POST request route handler with the given middleware.

func (*App) PUT

func (a *App) PUT(path string, action Action, middleware ...Middleware)

PUT registers a PUT request route handler with the given middleware.

func (*App) Register

func (a *App) Register(controllers ...Controller)

Register registers controllers with the app's router.

func (*App) RenderAction added in v1.20201204.1

func (a *App) RenderAction(action Action) Handler

RenderAction is the translation step from Action to Handler.

func (*App) RenderActionBare added in v1.20201204.1

func (a *App) RenderActionBare(action Action) Handler

RenderActionBare is the translation step from Action to Handler that omits logging.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

func (*App) ServeStatic

func (a *App) ServeStatic(route string, searchPaths []string, middleware ...Middleware)

ServeStatic serves files from the given file system root(s).. If the path does not end with "/*filepath" that suffix will be added for you internally. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served.

func (*App) ServeStaticCached

func (a *App) ServeStaticCached(route string, searchPaths []string, middleware ...Middleware)

ServeStaticCached serves files from the given file system root(s). If the path does not end with "/*filepath" that suffix will be added for you internally.

func (*App) SetStaticHeader

func (a *App) SetStaticHeader(route, key, value string) error

SetStaticHeader adds a header for the given static path. These headers are automatically added to any result that the static path fileserver sends.

func (*App) SetStaticRewriteRule

func (a *App) SetStaticRewriteRule(route, match string, action RewriteAction) error

SetStaticRewriteRule adds a rewrite rule for a specific statically served path. It mutates the path for the incoming static file request to the fileserver according to the action.

func (*App) Start

func (a *App) Start() (err error)

Start starts the server and binds to the given address.

func (*App) StartupTasks

func (a *App) StartupTasks() (err error)

StartupTasks runs common startup tasks. These tasks include anything outside setting up the underlying server itself. Right now, this is limited to initializing the view cache if relevant.

func (*App) Stop added in v0.3.1

func (a *App) Stop() error

Stop stops the server.

type AuthManager

type AuthManager struct {
	CookieDefaults http.Cookie

	// PersistHandler is called to both create and to update a session in a persistent store.
	PersistHandler AuthManagerPersistSessionHandler
	// SerializeSessionHandler if set, is called to serialize the session
	// as a session cookie value.
	SerializeHandler AuthManagerSerializeSessionHandler
	// FetchSessionHandler is called if set to restore a session from a string session identifier.
	FetchHandler AuthManagerFetchSessionHandler
	// Remove handler is called on logout to remove a session from a persistent store.
	// It is called during `Logout` to remove logged out sessions.
	RemoveHandler AuthManagerRemoveSessionHandler
	// ValidateHandler is called after a session is retored to make sure it's still valid.
	ValidateHandler AuthManagerValidateSessionHandler
	// SessionTimeoutProvider is called to create a variable session expiry.
	SessionTimeoutProvider AuthManagerSessionTimeoutProvider

	// LoginRedirectHandler redirects an unauthenticated user to the login page.
	LoginRedirectHandler AuthManagerRedirectHandler
}

AuthManager is a manager for sessions.

func MustNewAuthManager added in v1.20201204.1

func MustNewAuthManager(options ...AuthManagerOption) AuthManager

MustNewAuthManager returns a new auth manager with a given set of options but panics on error.

func NewAuthManager added in v1.20201204.1

func NewAuthManager(options ...AuthManagerOption) (manager AuthManager, err error)

NewAuthManager returns a new auth manager from a given config. For remote mode, you must provide a fetch, persist, and remove handler, and optionally a login redirect handler.

func NewLocalAuthManager

func NewLocalAuthManager(options ...AuthManagerOption) (AuthManager, error)

NewLocalAuthManager returns a new locally cached session manager. It saves sessions to a local store.

func NewLocalAuthManagerFromCache added in v1.1.0

func NewLocalAuthManagerFromCache(cache *LocalSessionCache, options ...AuthManagerOption) (manager AuthManager, err error)

NewLocalAuthManagerFromCache returns a new locally cached session manager that saves sessions to the cache provided

func (AuthManager) Login

func (am AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error)

Login logs a userID in.

func (AuthManager) LoginRedirect

func (am AuthManager) LoginRedirect(ctx *Ctx) Result

LoginRedirect returns a redirect result for when auth fails and you need to send the user to a login page.

func (AuthManager) Logout

func (am AuthManager) Logout(ctx *Ctx) error

Logout unauthenticates a session.

func (AuthManager) VerifyOrExtendSession added in v1.20220411.3

func (am AuthManager) VerifyOrExtendSession(ctx *Ctx) (session *Session, err error)

VerifyOrExtendSession reads a session value from a request and checks if it's valid. It also handles updating a rolling expiry.

func (AuthManager) VerifySession

func (am AuthManager) VerifySession(ctx *Ctx) (sessionValue string, session *Session, err error)

VerifySession pulls the session cookie off the request, and validates it represents a valid session.

type AuthManagerFetchSessionHandler added in v1.20210306.3

type AuthManagerFetchSessionHandler func(context.Context, string) (*Session, error)

AuthManagerFetchSessionHandler restores a session based on a session value.

type AuthManagerOption added in v1.20201204.1

type AuthManagerOption func(*AuthManager) error

AuthManagerOption is a variadic option for auth managers.

func OptAuthManagerCookieDefaults added in v1.20201204.1

func OptAuthManagerCookieDefaults(cookie http.Cookie) AuthManagerOption

OptAuthManagerCookieDefaults sets a field on an auth manager

func OptAuthManagerCookieDomain added in v1.20201204.1

func OptAuthManagerCookieDomain(domain string) AuthManagerOption

OptAuthManagerCookieDomain sets a field on an auth manager

func OptAuthManagerCookieHTTPOnly added in v1.20201204.1

func OptAuthManagerCookieHTTPOnly(httpOnly bool) AuthManagerOption

OptAuthManagerCookieHTTPOnly sets a field on an auth manager

func OptAuthManagerCookieName added in v1.20201204.1

func OptAuthManagerCookieName(cookieName string) AuthManagerOption

OptAuthManagerCookieName sets a field on an auth manager

func OptAuthManagerCookiePath added in v1.20201204.1

func OptAuthManagerCookiePath(cookiePath string) AuthManagerOption

OptAuthManagerCookiePath sets a field on an auth manager

func OptAuthManagerCookieSameSite added in v1.20201204.1

func OptAuthManagerCookieSameSite(sameSite http.SameSite) AuthManagerOption

OptAuthManagerCookieSameSite sets a field on an auth manager

func OptAuthManagerCookieSecure added in v1.20201204.1

func OptAuthManagerCookieSecure(secure bool) AuthManagerOption

OptAuthManagerCookieSecure sets a field on an auth manager

func OptAuthManagerFetchHandler added in v1.20201204.1

func OptAuthManagerFetchHandler(handler AuthManagerFetchSessionHandler) AuthManagerOption

OptAuthManagerFetchHandler sets a field on an auth manager

func OptAuthManagerFromConfig added in v1.20201204.1

func OptAuthManagerFromConfig(cfg Config) AuthManagerOption

OptAuthManagerFromConfig returns an auth manager from a config.

func OptAuthManagerLoginRedirectHandler added in v1.20201204.1

func OptAuthManagerLoginRedirectHandler(handler AuthManagerRedirectHandler) AuthManagerOption

OptAuthManagerLoginRedirectHandler sets a field on an auth manager

func OptAuthManagerPersistHandler added in v1.20201204.1

func OptAuthManagerPersistHandler(handler AuthManagerPersistSessionHandler) AuthManagerOption

OptAuthManagerPersistHandler sets a field on an auth manager

func OptAuthManagerRemoveHandler added in v1.20201204.1

func OptAuthManagerRemoveHandler(handler AuthManagerRemoveSessionHandler) AuthManagerOption

OptAuthManagerRemoveHandler sets a field on an auth manager

func OptAuthManagerSerializeHandler added in v1.20210306.3

func OptAuthManagerSerializeHandler(handler AuthManagerSerializeSessionHandler) AuthManagerOption

OptAuthManagerSerializeHandler sets a field on an auth manager

func OptAuthManagerSessionTimeoutProvider added in v1.20201204.1

func OptAuthManagerSessionTimeoutProvider(handler AuthManagerSessionTimeoutProvider) AuthManagerOption

OptAuthManagerSessionTimeoutProvider sets a field on an auth manager

func OptAuthManagerValidateHandler added in v1.20201204.1

func OptAuthManagerValidateHandler(handler AuthManagerValidateSessionHandler) AuthManagerOption

OptAuthManagerValidateHandler sets a field on an auth manager

type AuthManagerPersistSessionHandler added in v1.20210306.3

type AuthManagerPersistSessionHandler func(context.Context, *Session) error

AuthManagerPersistSessionHandler saves the session to a stable store.

type AuthManagerRedirectHandler

type AuthManagerRedirectHandler func(*Ctx) *url.URL

AuthManagerRedirectHandler is a redirect handler.

type AuthManagerRemoveSessionHandler added in v1.20210306.3

type AuthManagerRemoveSessionHandler func(context.Context, string) error

AuthManagerRemoveSessionHandler removes a session based on a session value.

type AuthManagerSerializeSessionHandler added in v1.20210306.3

type AuthManagerSerializeSessionHandler func(context.Context, *Session) (string, error)

AuthManagerSerializeSessionHandler serializes a session as a string.

type AuthManagerSessionTimeoutProvider

type AuthManagerSessionTimeoutProvider func(*Session) time.Time

AuthManagerSessionTimeoutProvider provides a new timeout for a session.

type AuthManagerValidateSessionHandler added in v1.20210306.3

type AuthManagerValidateSessionHandler func(context.Context, *Session) error

AuthManagerValidateSessionHandler validates a session.

type CachedStaticFile

type CachedStaticFile struct {
	Path     string
	Size     int
	ETag     string
	ModTime  time.Time
	Contents *bytes.Reader
}

CachedStaticFile is a memory mapped static file.

func NewCachedStaticFile added in v1.20210201.1

func NewCachedStaticFile(path string) (*CachedStaticFile, error)

NewCachedStaticFile returns a new cached static file for a given path.

func (CachedStaticFile) Render

func (csf CachedStaticFile) Render(ctx *Ctx) error

Render implements Result.

Note: It is safe to ingore the error returned from this method; it only has this signature to satisfy the `Result` interface.

type Config

type Config struct {
	Port                      int32         `json:"port,omitempty" yaml:"port,omitempty" env:"PORT"`
	BindAddr                  string        `json:"bindAddr,omitempty" yaml:"bindAddr,omitempty" env:"BIND_ADDR"`
	BaseURL                   string        `json:"baseURL,omitempty" yaml:"baseURL,omitempty" env:"BASE_URL"`
	SkipRedirectTrailingSlash bool          `json:"skipRedirectTrailingSlash,omitempty" yaml:"skipRedirectTrailingSlash,omitempty"`
	HandleOptions             bool          `json:"handleOptions,omitempty" yaml:"handleOptions,omitempty"`
	HandleMethodNotAllowed    bool          `json:"handleMethodNotAllowed,omitempty" yaml:"handleMethodNotAllowed,omitempty"`
	DisablePanicRecovery      bool          `json:"disablePanicRecovery,omitempty" yaml:"disablePanicRecovery,omitempty"`
	SessionTimeout            time.Duration `json:"sessionTimeout,omitempty" yaml:"sessionTimeout,omitempty" env:"SESSION_TIMEOUT"`
	SessionTimeoutIsRelative  bool          `json:"sessionTimeoutIsRelative,omitempty" yaml:"sessionTimeoutIsRelative,omitempty"`

	CookieSecure   *bool  `json:"cookieSecure,omitempty" yaml:"cookieSecure,omitempty" env:"COOKIE_SECURE"`
	CookieHTTPOnly *bool  `json:"cookieHTTPOnly,omitempty" yaml:"cookieHTTPOnly,omitempty" env:"COOKIE_HTTP_ONLY"`
	CookieSameSite string `json:"cookieSameSite,omitempty" yaml:"cookieSameSite,omitempty" env:"COOKIE_SAME_SITE"`
	CookieName     string `json:"cookieName,omitempty" yaml:"cookieName,omitempty" env:"COOKIE_NAME"`
	CookiePath     string `json:"cookiePath,omitempty" yaml:"cookiePath,omitempty" env:"COOKIE_PATH"`
	CookieDomain   string `json:"cookieDomain,omitempty" yaml:"cookieDomain,omitempty" env:"COOKIE_DOMAIN"`

	DefaultHeaders      map[string]string `json:"defaultHeaders,omitempty" yaml:"defaultHeaders,omitempty"`
	MaxHeaderBytes      int               `json:"maxHeaderBytes,omitempty" yaml:"maxHeaderBytes,omitempty" env:"MAX_HEADER_BYTES"`
	ReadTimeout         time.Duration     `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty" env:"READ_TIMEOUT"`
	ReadHeaderTimeout   time.Duration     `json:"readHeaderTimeout,omitempty" yaml:"readHeaderTimeout,omitempty" env:"READ_HEADER_TIMEOUT"`
	WriteTimeout        time.Duration     `json:"writeTimeout,omitempty" yaml:"writeTimeout,omitempty" env:"WRITE_TIMEOUT"`
	IdleTimeout         time.Duration     `json:"idleTimeout,omitempty" yaml:"idleTimeout,omitempty" env:"IDLE_TIMEOUT"`
	ShutdownGracePeriod time.Duration     `json:"shutdownGracePeriod,omitempty" yaml:"shutdownGracePeriod,omitempty" env:"SHUTDOWN_GRACE_PERIOD"`

	KeepAlive        *bool         `json:"keepAlive,omitempty" yaml:"keepAlive,omitempty" env:"KEEP_ALIVE"`
	KeepAlivePeriod  time.Duration `json:"keepAlivePeriod,omitempty" yaml:"keepAlivePeriod,omitempty" env:"KEEP_ALIVE_PERIOD"`
	UseProxyProtocol bool          `json:"useProxyProtocol,omitempty" yaml:"useProxyProtocol,omitempty"`

	Views ViewCacheConfig `json:"views,omitempty" yaml:"views,omitempty"`
}

Config is an object used to set up a web app.

func (Config) BaseURLOrDefault added in v1.20201204.1

func (c Config) BaseURLOrDefault() string

BaseURLOrDefault gets the base url for the app or a default.

func (Config) BindAddrOrDefault added in v1.20201204.1

func (c Config) BindAddrOrDefault(defaults ...string) string

BindAddrOrDefault returns the bind address or a default.

func (Config) CookieDomainOrDefault added in v1.20201204.1

func (c Config) CookieDomainOrDefault() string

CookieDomainOrDefault returns a property or a default.

func (Config) CookieHTTPOnlyOrDefault added in v1.20201204.1

func (c Config) CookieHTTPOnlyOrDefault() bool

CookieHTTPOnlyOrDefault returns a property or a default.

func (Config) CookieNameOrDefault added in v1.20201204.1

func (c Config) CookieNameOrDefault() string

CookieNameOrDefault returns a property or a default.

func (Config) CookiePathOrDefault added in v1.20201204.1

func (c Config) CookiePathOrDefault() string

CookiePathOrDefault returns a property or a default.

func (Config) CookieSameSiteOrDefault added in v1.20201204.1

func (c Config) CookieSameSiteOrDefault() http.SameSite

CookieSameSiteOrDefault returns a property or a default.

func (Config) CookieSecureOrDefault added in v1.20201204.1

func (c Config) CookieSecureOrDefault() bool

CookieSecureOrDefault returns a property or a default.

func (Config) IdleTimeoutOrDefault added in v1.20201204.1

func (c Config) IdleTimeoutOrDefault() time.Duration

IdleTimeoutOrDefault gets a property.

func (Config) IsZero added in v1.20210201.1

func (c Config) IsZero() bool

IsZero returns if the config is unset or not.

func (Config) KeepAliveOrDefault added in v1.20201204.1

func (c Config) KeepAliveOrDefault() bool

KeepAliveOrDefault returns if we should keep TCP connections open.

func (Config) KeepAlivePeriodOrDefault added in v1.20201204.1

func (c Config) KeepAlivePeriodOrDefault() time.Duration

KeepAlivePeriodOrDefault returns the TCP keep alive period or a default.

func (Config) MaxHeaderBytesOrDefault added in v1.20201204.1

func (c Config) MaxHeaderBytesOrDefault() int

MaxHeaderBytesOrDefault returns the maximum header size in bytes or a default.

func (Config) PortOrDefault added in v1.20201204.1

func (c Config) PortOrDefault() int32

PortOrDefault returns the int32 port for a given config. This is useful in things like kubernetes pod templates. If the config .Port is unset, it will parse the .BindAddr, or the DefaultBindAddr for the port number.

func (Config) ReadHeaderTimeoutOrDefault added in v1.20201204.1

func (c Config) ReadHeaderTimeoutOrDefault() time.Duration

ReadHeaderTimeoutOrDefault gets a property.

func (Config) ReadTimeoutOrDefault added in v1.20201204.1

func (c Config) ReadTimeoutOrDefault() time.Duration

ReadTimeoutOrDefault gets a property.

func (*Config) Resolve added in v1.20201204.1

func (c *Config) Resolve(ctx context.Context) error

Resolve resolves the config from other sources.

func (Config) ResolveCookieDomain added in v1.20210104.2

func (c Config) ResolveCookieDomain(_ context.Context) (*string, error)

ResolveCookieDomain is a resolver for the `CookieDomain` field based on the BaseURL if one is provided.

func (Config) ResolveCookieSecure added in v1.20210104.2

func (c Config) ResolveCookieSecure(_ context.Context) (*bool, error)

ResolveCookieSecure is a resolver for the `CookieSecure` field based on the BaseURL if one is provided.

func (Config) SessionTimeoutOrDefault added in v1.20201204.1

func (c Config) SessionTimeoutOrDefault() time.Duration

SessionTimeoutOrDefault returns a property or a default.

func (Config) ShutdownGracePeriodOrDefault added in v1.20201204.1

func (c Config) ShutdownGracePeriodOrDefault() time.Duration

ShutdownGracePeriodOrDefault gets the shutdown grace period.

func (Config) WriteTimeoutOrDefault added in v1.20201204.1

func (c Config) WriteTimeoutOrDefault() time.Duration

WriteTimeoutOrDefault gets a property.

type Controller

type Controller interface {
	Register(app *App)
}

Controller is an interface for controller objects.

The primary concern of a controller is to register routes that correspond to the actions the controller implements.

Routes are registered in order, and cannot collide with eachother.

Controllers should also register any views or additional resources they need at the time of registration.

type Ctx

type Ctx struct {
	// App is a reference back to the parent application.
	App *App
	// Auth is a reference to the app default auth manager, but
	// can be overwritten by middleware.
	Auth AuthManager
	// DefaultProvider is the app default result provider by default
	// but can be overwritten by middleware.
	DefaultProvider ResultProvider
	// Views is the app view cache by default but can be
	// overwritten by middleware.
	Views *ViewCache
	// Response is the response writer for the request.
	Response ResponseWriter
	// Request is the inbound request metadata.
	Request *http.Request
	// Body is a cached copy of the post body of a request.
	// It is typically set by calling `.PostBody()` on this context.
	// If you're expecting a large post body, do not use
	// the `.PostBody()` function, instead read directly from `.Request.Body` with
	// a stream reader or similar.
	Body []byte
	// Form is a cache of parsed url form values from the post body.
	Form url.Values
	// State is a mutable bag of state, it contains by default
	// state set on the application.
	State State
	// Session is the current auth session
	Session *Session
	// Route is the matching route for the request if relevant.
	Route *Route
	// RouteParams is a cache of parameters or variables
	// within the route and their values.
	RouteParams RouteParameters
	// Log is the request specific logger.
	Log logger.Log
	// Tracer is the app tracer by default if one is set.
	// It can be overwritten by middleware.
	Tracer Tracer
	// RequestStarted is the time the request was received.
	RequestStarted time.Time
}

Ctx is the struct that represents the context for an hc request.

func MockCtx added in v1.20201204.1

func MockCtx(method, path string, options ...CtxOption) *Ctx

MockCtx returns a new mock ctx. It is intended to be used in testing.

func MockCtxWithBuffer added in v1.20210201.1

func MockCtxWithBuffer(method, path string, buf io.Writer, options ...CtxOption) *Ctx

MockCtxWithBuffer returns a new mock ctx. It is intended to be used in testing.

func NewCtx

func NewCtx(w ResponseWriter, r *http.Request, options ...CtxOption) *Ctx

NewCtx returns a new ctx.

func (*Ctx) Annotations added in v1.20201204.1

func (rc *Ctx) Annotations() map[string]interface{}

Annotations returns the annotations for logging calls.

func (*Ctx) Close added in v1.20201204.1

func (rc *Ctx) Close() error

Close closes the context.

func (*Ctx) Context

func (rc *Ctx) Context() context.Context

Context returns the context.

func (*Ctx) Cookie added in v1.20201204.1

func (rc *Ctx) Cookie(name string) *http.Cookie

Cookie returns a named cookie from the request.

func (*Ctx) Elapsed

func (rc *Ctx) Elapsed() time.Duration

Elapsed is the time delta between start and end.

func (*Ctx) EnsureForm added in v1.20201204.1

func (rc *Ctx) EnsureForm() error

EnsureForm parses the post body as an application form. The parsed form will be available on the `.Form` field.

func (*Ctx) ExpireCookie

func (rc *Ctx) ExpireCookie(name string, path string)

ExpireCookie expires a cookie.

func (*Ctx) ExtendCookie

func (rc *Ctx) ExtendCookie(name string, path string, years, months, days int)

ExtendCookie extends a cookie by years, months or days.

func (*Ctx) ExtendCookieByDuration

func (rc *Ctx) ExtendCookieByDuration(name string, path string, duration time.Duration)

ExtendCookieByDuration extends a cookie by a time duration (on the order of nanoseconds to hours).

func (*Ctx) FormValue

func (rc *Ctx) FormValue(key string) (output string, err error)

FormValue returns a form value.

func (*Ctx) HeaderValue

func (rc *Ctx) HeaderValue(key string) (value string, err error)

HeaderValue returns a header value.

func (*Ctx) Labels added in v1.20201204.1

func (rc *Ctx) Labels() map[string]string

Labels returns the labels for logging calls.

func (*Ctx) Param

func (rc *Ctx) Param(name string) (value string, err error)

Param returns a parameter from the request.

It checks, in order:

  • RouteParam
  • QueryValue
  • HeaderValue
  • FormValue
  • CookieValue

It should only be used in cases where you don't necessarily know where the param value will be coming from. Where possible, use the more tightly scoped param getters.

It returns the value, and a validation error if the value is not found in any of the possible sources.

You can use one of the Value functions to also cast the resulting string into a useful type:

typed, err := web.IntValue(rc.Param("fooID"))

func (*Ctx) PostBody

func (rc *Ctx) PostBody() ([]byte, error)

PostBody reads, caches and returns the bytes on a request post body. It will store those bytes for re-use on this context object. If you're expecting a large post body, or a large post body is even possible use a stream reader on `.Request.Body` instead of this method.

func (*Ctx) PostBodyAsForm added in v1.20201204.1

func (rc *Ctx) PostBodyAsForm(response interface{}) error

PostBodyAsForm reads the incoming post body (closing it) sets a given object from the post form fields. NOTE: the request method *MUST* not be `GET` otherwise the golang internals will skip parsing the body.

func (*Ctx) PostBodyAsJSON

func (rc *Ctx) PostBodyAsJSON(response interface{}) error

PostBodyAsJSON reads the incoming post body (closing it) and marshals it to the target object as json.

func (*Ctx) PostBodyAsString

func (rc *Ctx) PostBodyAsString() (string, error)

PostBodyAsString returns the post body as a string.

func (*Ctx) PostBodyAsXML

func (rc *Ctx) PostBodyAsXML(response interface{}) error

PostBodyAsXML reads the incoming post body (closing it) and marshals it to the target object as xml.

func (*Ctx) QueryValue

func (rc *Ctx) QueryValue(key string) (value string, err error)

QueryValue returns a query value.

func (*Ctx) RouteParam

func (rc *Ctx) RouteParam(key string) (output string, err error)

RouteParam returns a string route parameter

func (*Ctx) StateValue

func (rc *Ctx) StateValue(key string) interface{}

StateValue returns an object in the state cache.

func (*Ctx) WithContext

func (rc *Ctx) WithContext(ctx context.Context) *Ctx

WithContext sets the background context for the request.

func (*Ctx) WithStateValue

func (rc *Ctx) WithStateValue(key string, value interface{}) *Ctx

WithStateValue sets the state for a key to an object.

type CtxOption added in v1.20201204.1

type CtxOption func(*Ctx)

CtxOption is an option for a context.

func CtxRequestOption added in v1.20201204.1

func CtxRequestOption(opt func(*http.Request) error) CtxOption

CtxRequestOption is a ctx option that wraps a request option.

func OptCtxApp added in v1.20201204.1

func OptCtxApp(a *App) CtxOption

OptCtxApp sets the context app.

func OptCtxAuth added in v1.20201204.1

func OptCtxAuth(auth AuthManager) CtxOption

OptCtxAuth sets the context auth manager.

func OptCtxBodyBytes added in v1.20201204.1

func OptCtxBodyBytes(body []byte) CtxOption

OptCtxBodyBytes sets a post body on a context.

func OptCtxCookieValue added in v1.20201204.1

func OptCtxCookieValue(key, value string) CtxOption

OptCtxCookieValue sets a cookie value on a context.

func OptCtxDefaultProvider added in v1.20201204.1

func OptCtxDefaultProvider(rp ResultProvider) CtxOption

OptCtxDefaultProvider sets the context default result provider.

func OptCtxHeaderValue added in v1.20201204.1

func OptCtxHeaderValue(key, value string) CtxOption

OptCtxHeaderValue sets a header value on a context.

func OptCtxLog added in v1.20201204.1

func OptCtxLog(log logger.Log) CtxOption

OptCtxLog sets the context logger.

func OptCtxPostFormValue added in v1.20201204.1

func OptCtxPostFormValue(key, value string) CtxOption

OptCtxPostFormValue sets a form value on a context.

func OptCtxPostedFiles added in v1.20201204.1

func OptCtxPostedFiles(files ...webutil.PostedFile) CtxOption

OptCtxPostedFiles sets posted files on a context.

func OptCtxQueryValue added in v1.20201204.1

func OptCtxQueryValue(key, value string) CtxOption

OptCtxQueryValue sets a query value on a context.

func OptCtxRequestStarted added in v1.20201204.1

func OptCtxRequestStarted(ts time.Time) CtxOption

OptCtxRequestStarted sets the context request started timestamp.

func OptCtxRoute added in v1.20201204.1

func OptCtxRoute(r *Route) CtxOption

OptCtxRoute sets the context route.

func OptCtxRouteParamValue added in v1.20201204.1

func OptCtxRouteParamValue(key, value string) CtxOption

OptCtxRouteParamValue sets the context default result provider.

func OptCtxRouteParams added in v1.20201204.1

func OptCtxRouteParams(r RouteParameters) CtxOption

OptCtxRouteParams sets the context route params.

func OptCtxSession added in v1.20201204.1

func OptCtxSession(s *Session) CtxOption

OptCtxSession sets the context session.

func OptCtxState added in v1.20201204.1

func OptCtxState(s State) CtxOption

OptCtxState sets the context state.

func OptCtxTracer added in v1.20201204.1

func OptCtxTracer(tracer Tracer) CtxOption

OptCtxTracer sets the context tracer.

func OptCtxViews added in v1.20201204.1

func OptCtxViews(vc *ViewCache) CtxOption

OptCtxViews sets the context views cache.

type Handler

Handler is the most basic route handler.

func WrapHandler

func WrapHandler(handler http.Handler) Handler

WrapHandler wraps an http.Handler as a Handler.

type JSONResult

type JSONResult struct {
	StatusCode int
	Response   interface{}
}

JSONResult is a json result.

func (*JSONResult) Render

func (jr *JSONResult) Render(ctx *Ctx) error

Render renders the result

type JSONResultProvider

type JSONResultProvider struct{}

JSONResultProvider are context results for api methods.

var (
	// JSON is a static singleton json result provider.
	JSON JSONResultProvider
)

func (JSONResultProvider) BadRequest

func (jrp JSONResultProvider) BadRequest(err error) Result

BadRequest returns a service response.

func (JSONResultProvider) Forbidden added in v1.20201204.1

func (jrp JSONResultProvider) Forbidden() Result

Forbidden returns a 403 Forbidden response.

func (JSONResultProvider) InternalError

func (jrp JSONResultProvider) InternalError(err error) Result

InternalError returns a service response.

func (JSONResultProvider) NotAuthorized

func (jrp JSONResultProvider) NotAuthorized() Result

NotAuthorized returns a service response.

func (JSONResultProvider) NotFound

func (jrp JSONResultProvider) NotFound() Result

NotFound returns a service response.

func (JSONResultProvider) OK

func (jrp JSONResultProvider) OK() Result

OK returns a service response.

func (JSONResultProvider) Result

func (jrp JSONResultProvider) Result(response interface{}) Result

Result returns a json response.

func (JSONResultProvider) Status

func (jrp JSONResultProvider) Status(statusCode int, response interface{}) Result

Status returns a plaintext result.

type JWTManager

type JWTManager struct {
	KeyProvider func(*Session) ([]byte, error)
}

JWTManager is a manager for JWTs.

func NewJWTManager

func NewJWTManager(key []byte) *JWTManager

NewJWTManager returns a new jwt manager from a key.

func (JWTManager) Apply added in v1.20210103.1

func (jwtm JWTManager) Apply(am *AuthManager)

Apply applies the jwtm to the given auth manager.

func (JWTManager) Claims

func (jwtm JWTManager) Claims(session *Session) *jwt.StandardClaims

Claims returns the sesion as a JWT standard claims object.

func (JWTManager) FetchHandler added in v1.20210306.3

func (jwtm JWTManager) FetchHandler(_ context.Context, sessionValue string) (*Session, error)

FetchHandler is a shim to the auth manager.

func (JWTManager) FromClaims

func (jwtm JWTManager) FromClaims(claims *jwt.StandardClaims) *Session

FromClaims returns a session from a given claims set.

func (JWTManager) KeyFunc

func (jwtm JWTManager) KeyFunc(token *jwt.Token) (interface{}, error)

KeyFunc is a shim function to get the key for a given token.

func (JWTManager) SerializeHandler added in v1.20210306.3

func (jwtm JWTManager) SerializeHandler(_ context.Context, session *Session) (output string, err error)

SerializeHandler is a shim to the auth manager.

type LocalSessionCache

type LocalSessionCache struct {
	SessionLock *sync.Mutex
	Sessions    map[string]*Session
}

LocalSessionCache is a memory cache of sessions. It is meant to be used in tests.

func NewLocalSessionCache

func NewLocalSessionCache() *LocalSessionCache

NewLocalSessionCache returns a new session cache.

func (*LocalSessionCache) Apply added in v1.20210103.1

func (lsc *LocalSessionCache) Apply(am *AuthManager)

Apply applies the local session cache to a given auth manager.

func (*LocalSessionCache) FetchHandler

func (lsc *LocalSessionCache) FetchHandler(_ context.Context, sessionID string) (*Session, error)

FetchHandler is a shim to interface with the auth manager.

func (*LocalSessionCache) Get

func (lsc *LocalSessionCache) Get(sessionID string) *Session

Get gets a session.

func (*LocalSessionCache) PersistHandler

func (lsc *LocalSessionCache) PersistHandler(_ context.Context, session *Session) error

PersistHandler is a shim to interface with the auth manager.

func (*LocalSessionCache) Remove

func (lsc *LocalSessionCache) Remove(sessionID string)

Remove removes a session from the cache.

func (*LocalSessionCache) RemoveHandler

func (lsc *LocalSessionCache) RemoveHandler(_ context.Context, sessionID string) error

RemoveHandler is a shim to interface with the auth manager.

func (*LocalSessionCache) Upsert

func (lsc *LocalSessionCache) Upsert(session *Session)

Upsert adds or updates a session to the cache.

type LoggedErrorResult added in v1.20201204.1

type LoggedErrorResult struct {
	Result Result
	Error  error
}

LoggedErrorResult is a result that returns an error during the prerender phase.

func ResultWithLoggedError added in v1.20201204.1

func ResultWithLoggedError(result Result, err error) *LoggedErrorResult

ResultWithLoggedError logs an error before it renders the result.

func (LoggedErrorResult) PostRender added in v1.20201204.1

func (ler LoggedErrorResult) PostRender(ctx *Ctx) error

PostRender returns the underlying error.

func (LoggedErrorResult) Render added in v1.20201204.1

func (ler LoggedErrorResult) Render(ctx *Ctx) error

Render renders the result.

type Middleware

type Middleware func(Action) Action

Middleware is a func that implements middleware

func SessionMiddleware

func SessionMiddleware(notAuthorized Action) Middleware

SessionMiddleware implements a custom notAuthorized action.

func WithTimeout

func WithTimeout(d time.Duration) Middleware

WithTimeout injects the context for a given action with a timeout context.

type MockResult added in v1.20201204.1

type MockResult struct {
	*r2.Request
	App    *App
	Server *httptest.Server
}

MockResult is a result of a mocked request.

func Mock added in v1.20201204.1

func Mock(app *App, req *http.Request, options ...r2.Option) *MockResult

Mock sends a mock request to an app. It will reset the app Server, Listener, and will set the request host to the listener address for a randomized local listener.

func MockGet added in v1.20201204.1

func MockGet(app *App, path string, options ...r2.Option) *MockResult

MockGet sends a mock get request to an app.

func MockMethod added in v1.20201204.1

func MockMethod(app *App, method, path string, options ...r2.Option) *MockResult

MockMethod sends a mock request with a given method to an app. You should use request options to set the body of the request if it's a post or put etc.

func MockPost added in v1.20201204.1

func MockPost(app *App, path string, body io.ReadCloser, options ...r2.Option) *MockResult

MockPost sends a mock post request to an app.

func MockPostJSON added in v1.20210103.1

func MockPostJSON(app *App, path string, body interface{}, options ...r2.Option) *MockResult

MockPostJSON sends a mock post request with a json body to an app.

func (*MockResult) Close added in v1.20201204.1

func (mr *MockResult) Close() error

Close stops the app.

type NoContentResult

type NoContentResult struct{}

NoContentResult returns a no content response.

var (
	// NoContent is a static result.
	NoContent NoContentResult
)

func (NoContentResult) Render

func (ncr NoContentResult) Render(ctx *Ctx) error

Render renders a static result.

type Option added in v1.20201204.1

type Option func(*App) error

Option is an option for an app.

func OptAuth added in v1.20201204.1

func OptAuth(auth AuthManager, err error) Option

OptAuth sets the auth manager.

func OptBaseContext added in v1.20210917.5

func OptBaseContext(ctx context.Context) Option

OptBaseContext sets a base context on an `App`; this is a context that is always used via the `BaseContext` function, independent of the listener.

func OptBaseContextFunc added in v1.20210917.5

func OptBaseContextFunc(bc func(net.Listener) context.Context) Option

OptBaseContextFunc sets a base context function on an `App`; this context function will propagated from the `App` to `http.Server.BaseContext`.

func OptBaseHeaders added in v1.20201204.1

func OptBaseHeaders(headers http.Header) Option

OptBaseHeaders sets base headers.

func OptBaseMiddleware added in v1.20201204.1

func OptBaseMiddleware(middleware ...Middleware) Option

OptBaseMiddleware sets default middleware.

func OptBaseStateValue added in v1.20201204.1

func OptBaseStateValue(key string, value interface{}) Option

OptBaseStateValue sets a base state value.

func OptBaseURL added in v1.20210908.5

func OptBaseURL(baseURL string) Option

OptBaseURL sets the config base url.

func OptBindAddr added in v1.20201204.1

func OptBindAddr(bindAddr string) Option

OptBindAddr sets the config bind address.

func OptConfig added in v1.20201204.1

func OptConfig(cfg Config) Option

OptConfig sets the config.

func OptConfigFromEnv added in v1.20201204.1

func OptConfigFromEnv() Option

OptConfigFromEnv sets the config from the environment.

func OptDefaultHeader added in v1.20201204.1

func OptDefaultHeader(key, value string) Option

OptDefaultHeader sets a default header.

func OptDefaultHeaders added in v1.20201204.1

func OptDefaultHeaders(headers http.Header) Option

OptDefaultHeaders sets base headers.

DEPRECATION(1.2021*): this method will be removed.

func OptDefaultMiddleware added in v1.20201204.1

func OptDefaultMiddleware(middleware ...Middleware) Option

OptDefaultMiddleware sets base middleware.

DEPRECATION(1.2021*): this method will be removed.

func OptIdleTimeout added in v1.20210215.2

func OptIdleTimeout(d time.Duration) Option

OptIdleTimeout sets the idle timeout.

Note that this will override the config setting if OptConfig comes before it and will be overwritten by the config if OptConfig comes after it.

func OptLog added in v1.20201204.1

func OptLog(log logger.Log) Option

OptLog sets the logger.

func OptMaxHeaderBytes added in v1.20210215.2

func OptMaxHeaderBytes(maxHeaderBytes int) Option

OptMaxHeaderBytes sets the max header bytes.

Note that this will override the config setting if OptConfig comes before it and will be overwritten by the config if OptConfig comes after it.

func OptMethodNotAllowedHandler added in v1.20201204.1

func OptMethodNotAllowedHandler(action Action) Option

OptMethodNotAllowedHandler sets default headers.

func OptNotFoundHandler added in v1.20201204.1

func OptNotFoundHandler(action Action) Option

OptNotFoundHandler sets default headers.

func OptPort added in v1.20201204.1

func OptPort(port int32) Option

OptPort sets the config bind address.

func OptReadHeaderTimeout added in v1.20210215.2

func OptReadHeaderTimeout(d time.Duration) Option

OptReadHeaderTimeout sets the read header timeout.

Note that this will override the config setting if OptConfig comes before it and will be overwritten by the config if OptConfig comes after it.

func OptReadTimeout added in v1.20210215.2

func OptReadTimeout(d time.Duration) Option

OptReadTimeout sets the read timeout.

Note that this will override the config setting if OptConfig comes before it and will be overwritten by the config if OptConfig comes after it.

func OptServer added in v1.20201204.1

func OptServer(server *http.Server) Option

OptServer sets the underlying server.

func OptServerOptions added in v1.20201204.1

func OptServerOptions(opts ...webutil.HTTPServerOption) Option

OptServerOptions applies options to the underlying http server.

Many of the fields on the server are overwritten by the config on `app.Start`. You should only use `OptServerOptions` for fields that are not governed by the config such as the stdlib logger.

func OptShutdownGracePeriod added in v1.20201204.1

func OptShutdownGracePeriod(d time.Duration) Option

OptShutdownGracePeriod sets the shutdown grace period.

func OptTLSConfig added in v1.20201204.1

func OptTLSConfig(cfg *tls.Config) Option

OptTLSConfig sets the tls config.

func OptTracer added in v1.20201204.1

func OptTracer(tracer Tracer) Option

OptTracer sets the tracer.

func OptUse added in v1.20201204.1

func OptUse(m Middleware) Option

OptUse adds to the default middleware.

func OptViews added in v1.20201204.1

func OptViews(views *ViewCache) Option

OptViews sets the view cache.

func OptWriteTimeout added in v1.20210215.2

func OptWriteTimeout(d time.Duration) Option

OptWriteTimeout sets the write timeout.

Note that this will override the config setting if OptConfig comes before it and will be overwritten by the config if OptConfig comes after it.

type PanicAction

type PanicAction func(*Ctx, interface{}) Result

PanicAction is a receiver for app.PanicHandler.

type PanicHandler

type PanicHandler func(http.ResponseWriter, *http.Request, interface{})

PanicHandler is a handler for panics that also takes an error.

type PostedFile

type PostedFile struct {
	Key      string
	FileName string
	Contents []byte
}

PostedFile is a file that has been posted to an hc endpoint.

type RawResult

type RawResult struct {
	StatusCode  int
	ContentType string
	Response    []byte
}

RawResult is for when you just want to dump bytes.

func Raw added in v1.20201204.1

func Raw(contents []byte) *RawResult

Raw returns a new raw result.

func RawWithContentType added in v1.20201204.1

func RawWithContentType(contentType string, body []byte) *RawResult

RawWithContentType returns a binary response with a given content type.

func (*RawResult) Render

func (rr *RawResult) Render(ctx *Ctx) error

Render renders the result.

type RedirectResult

type RedirectResult struct {
	Method      string `json:"redirect_method"`
	RedirectURI string `json:"redirect_uri"`
}

RedirectResult is a result that should cause the browser to redirect.

func Redirect added in v1.20201204.1

func Redirect(destination string) *RedirectResult

Redirect returns a redirect result to a given destination.

func RedirectWithMethod added in v1.20201204.1

func RedirectWithMethod(method, destination string) *RedirectResult

RedirectWithMethod returns a redirect result to a destination with a given method.

func RedirectWithMethodf added in v1.20201204.1

func RedirectWithMethodf(method, format string, args ...interface{}) *RedirectResult

RedirectWithMethodf returns a redirect result to a destination composed of a format and scan arguments with a given method.

func Redirectf added in v1.20201204.1

func Redirectf(format string, args ...interface{}) *RedirectResult

Redirectf returns a redirect result to a given destination specified by a given format and scan arguments.

func (*RedirectResult) Render

func (rr *RedirectResult) Render(ctx *Ctx) error

Render writes the result to the response.

type ResponseWriter

type ResponseWriter interface {
	http.Flusher
	http.ResponseWriter
	io.Closer
	StatusCode() int
	ContentLength() int
	InnerResponse() http.ResponseWriter
}

ResponseWriter is a super-type of http.ResponseWriter that includes the StatusCode and ContentLength for the request

type Result

type Result interface {
	Render(ctx *Ctx) error
}

Result is the result of a controller.

type ResultPostRender added in v1.20201204.1

type ResultPostRender interface {
	PostRender(ctx *Ctx) error
}

ResultPostRender is a result that has a PostRender step.

type ResultPreRender

type ResultPreRender interface {
	PreRender(ctx *Ctx) error
}

ResultPreRender is a result that has a PreRender step.

type ResultProvider

type ResultProvider interface {
	InternalError(err error) Result
	BadRequest(err error) Result
	NotFound() Result
	NotAuthorized() Result
	Status(int, interface{}) Result
}

ResultProvider is the provider interface for results.

type RewriteAction

type RewriteAction func(filePath string, matchedPieces ...string) string

RewriteAction is an action for a rewrite rule.

type RewriteRule

type RewriteRule struct {
	MatchExpression string

	Action RewriteAction
	// contains filtered or unexported fields
}

RewriteRule is a rule for re-writing incoming static urls.

func (RewriteRule) Apply

func (rr RewriteRule) Apply(filePath string) (bool, string)

Apply runs the filter, returning a bool if it matched, and the resulting path.

type Route

type Route struct {
	Handler
	Method string
	Path   string
	Params []string
}

Route is an entry in the route tree.

func (Route) String

func (r Route) String() string

String returns the path.

func (Route) StringWithMethod

func (r Route) StringWithMethod() string

StringWithMethod returns a string representation of the route. Namely: Method_Path

type RouteNode added in v1.20201204.1

type RouteNode struct {
	RouteNodeType

	Path       string
	IsWildcard bool
	MaxParams  uint8
	Indices    string
	Children   []*RouteNode
	Route      *Route
	Priority   uint32
}

RouteNode is a node on the route tree.

func (*RouteNode) AddRoute added in v1.20210908.5

func (n *RouteNode) AddRoute(method, path string, handler Handler)

AddRoute adds a node with the given handle to the path.

func (*RouteNode) GetPath added in v1.20210908.5

func (n *RouteNode) GetPath(path string) (route *Route, p RouteParameters, tsr bool)

GetPath returns the node for a path, parameter values, and if there is a trailing slash redirect recommendation.

type RouteNodeType added in v1.20201204.1

type RouteNodeType uint8

RouteNodeType is a type of route node.

const (
	RouteNodeTypeStatic RouteNodeType = iota // default
	RouteNodeTypeRoot
	RouteNodeTypeParam
	RouteNodeTypeCatchAll
)

RouteNodeTypes

type RouteParameters

type RouteParameters map[string]string

RouteParameters are parameters sourced from parsing the request path (route).

func (RouteParameters) Get

func (rp RouteParameters) Get(key string) string

Get gets a value for a key.

func (RouteParameters) Has

func (rp RouteParameters) Has(key string) bool

Has returns if the collection has a key or not.

func (RouteParameters) Set

func (rp RouteParameters) Set(key, value string)

Set stores a value for a key.

type RouteTree added in v1.20211025.3

type RouteTree struct {
	// Routes is a map between canonicalized http method
	// (i.e. `GET` vs. `get`) and individual method
	// route trees.
	Routes map[string]*RouteNode
	// SkipTrailingSlashRedirects disables matching
	// routes that are off by a trailing slash, either because
	// routes are registered with the '/' suffix, or because
	// the request has a '/' suffix and the
	// registered route does not.
	SkipTrailingSlashRedirects bool
	// SkipHandlingMethodOptions disables returning
	// a result with the `ALLOWED` header for method options,
	// and will instead 404 for `OPTIONS` methods.
	SkipHandlingMethodOptions bool
	// SkipMethodNotAllowed skips specific handling
	// for methods that do not have a route tree with
	// a specific 405 response, and will instead return a 404.
	SkipMethodNotAllowed bool
	// NotFoundHandler is an optional handler to set
	// to customize not found (404) results.
	NotFoundHandler Handler
	// MethodNotAllowedHandler is an optional handler
	// to set to customize method not allowed (405) results.
	MethodNotAllowedHandler Handler
}

RouteTree implements the basic logic of creating a route tree.

It is embedded in *App and handles the path to handler matching based on route trees per method.

A very simple example:

rt := new(web.RouteTree)
rt.Handle(http.MethodGet, "/", func(w http.ResponseWriter, req *http.Request, route *web.Route, params web.Params) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, "OK!")
})
(&http.Server{Addr: "127.0.0.1:8080", Handler: rt}).ListenAndServe()

func (*RouteTree) Handle added in v1.20211025.3

func (rt *RouteTree) Handle(method, path string, handler Handler)

Handle adds a handler at a given method and path.

func (*RouteTree) Route added in v1.20211025.3

func (rt *RouteTree) Route(req *http.Request) (*Route, RouteParameters)

Route gets the route and parameters for a given request if it matches a registered handler.

It will automatically resolve if a trailing slash should be appended for the input request url path, and will return the corresponding redirected route (and parameters) if there is one.

func (*RouteTree) ServeHTTP added in v1.20211025.3

func (rt *RouteTree) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

type Session

type Session struct {
	UserID     string                 `json:"userID" yaml:"userID"`
	BaseURL    string                 `json:"baseURL" yaml:"baseURL"`
	SessionID  string                 `json:"sessionID" yaml:"sessionID"`
	CreatedUTC time.Time              `json:"createdUTC" yaml:"createdUTC"`
	ExpiresUTC time.Time              `json:"expiresUTC" yaml:"expiresUTC"`
	UserAgent  string                 `json:"userAgent" yaml:"userAgent"`
	RemoteAddr string                 `json:"remoteAddr" yaml:"remoteAddr"`
	State      map[string]interface{} `json:"state,omitempty" yaml:"state,omitempty"`
}

Session is an active session

func GetSession added in v1.20201204.1

func GetSession(ctx context.Context) *Session

GetSession gets a session off a context.

func NewSession

func NewSession(userID string, sessionID string) *Session

NewSession returns a new session object.

func (*Session) IsExpired

func (s *Session) IsExpired() bool

IsExpired returns if the session is expired.

func (*Session) IsZero

func (s *Session) IsZero() bool

IsZero returns if the object is set or not. It will return true if either the userID or the sessionID are unset.

func (*Session) WithBaseURL

func (s *Session) WithBaseURL(baseURL string) *Session

WithBaseURL sets the base url.

func (*Session) WithRemoteAddr

func (s *Session) WithRemoteAddr(remoteAddr string) *Session

WithRemoteAddr sets the remote addr.

func (*Session) WithUserAgent

func (s *Session) WithUserAgent(userAgent string) *Session

WithUserAgent sets the user agent.

type State

type State interface {
	Keys() []string
	Get(key string) interface{}
	Set(key string, value interface{})
	Remove(key string)
	Copy() State
}

State is a provider for a state bag.

type StaticFileServer

type StaticFileServer struct {
	sync.RWMutex

	SearchPaths   []http.FileSystem
	RewriteRules  []RewriteRule
	Headers       http.Header
	CacheDisabled bool
	Cache         map[string]*CachedStaticFile
}

StaticFileServer is a cache of static files. It can operate in cached mode, or with `CacheDisabled` set to `true` it will read from disk for each request. In cached mode, it automatically adds etags for files it caches.

func NewStaticFileServer

func NewStaticFileServer(options ...StaticFileserverOption) *StaticFileServer

NewStaticFileServer returns a new static file cache.

func (*StaticFileServer) Action

func (sc *StaticFileServer) Action(r *Ctx) Result

Action is the entrypoint for the static server. It adds default headers if specified, and then serves the file from disk or from a pull-through cache if enabled.

func (*StaticFileServer) AddHeader

func (sc *StaticFileServer) AddHeader(key, value string)

AddHeader adds a header to the static cache results.

func (*StaticFileServer) AddRewriteRule

func (sc *StaticFileServer) AddRewriteRule(match string, action RewriteAction) error

AddRewriteRule adds a static re-write rule. This is meant to modify the path of a file from what is requested by the browser to how a file may actually be accessed on disk. Typically re-write rules are used to enforce caching semantics.

func (*StaticFileServer) ResolveCachedFile added in v1.20201204.1

func (sc *StaticFileServer) ResolveCachedFile(filepath string) (*CachedStaticFile, error)

ResolveCachedFile returns a cached file at a given path. It returns the cached instance of a file if it exists, and adds it to the cache if there is a miss.

func (*StaticFileServer) ResolveFile added in v1.20201204.1

func (sc *StaticFileServer) ResolveFile(filePath string) (f http.File, finalPath string, err error)

ResolveFile resolves a file from rewrite rules and search paths. First the file path is modified according to the rewrite rules. Then each search path is checked for the resolved file path.

func (*StaticFileServer) ServeCachedFile added in v1.20201204.1

func (sc *StaticFileServer) ServeCachedFile(r *Ctx, filepath string) Result

ServeCachedFile writes the file to the response, potentially serving a cached instance of the file.

func (*StaticFileServer) ServeFile

func (sc *StaticFileServer) ServeFile(r *Ctx, filePath string) Result

ServeFile writes the file to the response by reading from disk for each request (i.e. skipping the cache)

type StaticFileserverOption added in v1.20201204.1

type StaticFileserverOption func(*StaticFileServer)

StaticFileserverOption are options for static fileservers.

func OptStaticFileServerCacheDisabled added in v1.20201204.1

func OptStaticFileServerCacheDisabled(cacheDisabled bool) StaticFileserverOption

OptStaticFileServerCacheDisabled sets the static fileserver should read from disk for each request.

func OptStaticFileServerHeaders added in v1.20201204.1

func OptStaticFileServerHeaders(headers http.Header) StaticFileserverOption

OptStaticFileServerHeaders sets the static fileserver default headers..

func OptStaticFileServerSearchPaths added in v1.20201204.1

func OptStaticFileServerSearchPaths(searchPaths ...http.FileSystem) StaticFileserverOption

OptStaticFileServerSearchPaths sets the static fileserver search paths.

type StaticResult

type StaticResult struct {
	FilePath     string
	FileSystem   http.FileSystem
	RewriteRules []RewriteRule
	Headers      http.Header
}

StaticResult represents a static output.

func Static added in v1.20201204.1

func Static(filePath string) *StaticResult

Static returns a static result for an individual file.

func (StaticResult) Render

func (sr StaticResult) Render(ctx *Ctx) error

Render renders a static result.

type StatusViewModel

type StatusViewModel struct {
	StatusCode int
	Response   interface{}
}

StatusViewModel returns the status view model.

type SyncState

type SyncState struct {
	sync.RWMutex
	Values map[string]interface{}
}

SyncState is the collection of state objects on a context.

func (*SyncState) Copy

func (s *SyncState) Copy() State

Copy creates a new copy of the vars.

func (*SyncState) Get

func (s *SyncState) Get(key string) interface{}

Get gets a value.

func (*SyncState) Keys

func (s *SyncState) Keys() (output []string)

Keys returns

func (*SyncState) Remove

func (s *SyncState) Remove(key string)

Remove removes a key.

func (*SyncState) Set

func (s *SyncState) Set(key string, value interface{})

Set sets a value.

type TLSOption added in v1.20201204.1

type TLSOption func(*tls.Config) error

TLSOption is an option for TLS configs.

func OptTLSClientCertPool added in v1.20201204.1

func OptTLSClientCertPool(certPEMs ...[]byte) TLSOption

OptTLSClientCertPool adds a given set of certs in binary PEM format to the system CA pool.

func OptTLSClientCertVerification added in v1.20201204.1

func OptTLSClientCertVerification(verification tls.ClientAuthType) TLSOption

OptTLSClientCertVerification sets the verification level for client certs.

type TextResultProvider

type TextResultProvider struct{}

TextResultProvider is the default response provider if none is specified.

var (
	// Text is a static singleton text result provider.
	Text TextResultProvider
)

func (TextResultProvider) BadRequest

func (trp TextResultProvider) BadRequest(err error) Result

BadRequest returns a plaintext result.

func (TextResultProvider) InternalError

func (trp TextResultProvider) InternalError(err error) Result

InternalError returns a plainttext result.

func (TextResultProvider) NotAuthorized

func (trp TextResultProvider) NotAuthorized() Result

NotAuthorized returns a plaintext result.

func (TextResultProvider) NotFound

func (trp TextResultProvider) NotFound() Result

NotFound returns a plaintext result.

func (TextResultProvider) OK

func (trp TextResultProvider) OK() Result

OK returns an plaintext result.

func (TextResultProvider) Result

func (trp TextResultProvider) Result(result interface{}) Result

Result returns a plaintext result.

func (TextResultProvider) Status

func (trp TextResultProvider) Status(statusCode int, response interface{}) Result

Status returns a plaintext result.

type TraceFinisher

type TraceFinisher interface {
	Finish(*Ctx, error)
}

TraceFinisher is a finisher for a trace.

type Tracer

type Tracer interface {
	Start(*Ctx) TraceFinisher
}

Tracer is a type that traces complete requests.

type ViewCache

type ViewCache struct {
	sync.Mutex
	LiveReload bool
	FuncMap    template.FuncMap
	Paths      []string
	Literals   []string
	Templates  *template.Template
	BufferPool *bufferutil.Pool

	BadRequestTemplateName    string
	InternalErrorTemplateName string
	NotFoundTemplateName      string
	NotAuthorizedTemplateName string
	StatusTemplateName        string
}

ViewCache is the cached views used in view results.

func MustNewViewCache added in v1.20201204.1

func MustNewViewCache(opts ...ViewCacheOption) *ViewCache

MustNewViewCache returns a new view cache and panics on eror.

func NewViewCache

func NewViewCache(options ...ViewCacheOption) (*ViewCache, error)

NewViewCache returns a new view cache.

func (*ViewCache) AddLiterals

func (vc *ViewCache) AddLiterals(views ...string)

AddLiterals adds view literal strings to the view collection.

func (*ViewCache) AddPaths

func (vc *ViewCache) AddPaths(paths ...string)

AddPaths adds paths to the view collection.

func (*ViewCache) BadRequest

func (vc *ViewCache) BadRequest(err error) Result

BadRequest returns a view result.

func (*ViewCache) Initialize

func (vc *ViewCache) Initialize() error

Initialize caches templates by path.

func (*ViewCache) InternalError

func (vc *ViewCache) InternalError(err error) Result

InternalError returns a view result.

func (*ViewCache) Lookup

func (vc *ViewCache) Lookup(name string) (*template.Template, error)

Lookup looks up a view.

func (*ViewCache) NotAuthorized

func (vc *ViewCache) NotAuthorized() Result

NotAuthorized returns a view result.

func (*ViewCache) NotFound

func (vc *ViewCache) NotFound() Result

NotFound returns a view result.

func (*ViewCache) Parse

func (vc *ViewCache) Parse() (views *template.Template, err error)

Parse parses the view tree.

func (*ViewCache) Status

func (vc *ViewCache) Status(statusCode int, response interface{}) Result

Status returns a status view result.

func (*ViewCache) View

func (vc *ViewCache) View(viewName string, viewModel interface{}) Result

View returns a view result.

func (*ViewCache) ViewStatus added in v1.0.0

func (vc *ViewCache) ViewStatus(statusCode int, viewName string, viewModel interface{}) Result

ViewStatus returns a view result with a given status code..

type ViewCacheConfig

type ViewCacheConfig struct {
	// LiveReload indicates if we should store compiled views in memory for re-use (default), or read them from disk each load.
	LiveReload bool `json:"liveReload,omitempty" yaml:"liveReload,omitempty" env:"LIVE_RELOAD"`
	// Paths are a list of view paths to include in the templates list.
	Paths []string `json:"paths,omitempty" yaml:"paths,omitempty"`
	// BufferPoolSize is the size of the re-usable buffer pool for rendering views.
	BufferPoolSize int `json:"bufferPoolSize,omitempty" yaml:"bufferPoolSize,omitempty"`

	// InternalErrorTemplateName is the template name to use for the view result provider `InternalError` result.
	InternalErrorTemplateName string `json:"internalErrorTemplateName,omitempty" yaml:"internalErrorTemplateName,omitempty"`
	// BadRequestTemplateName is the template name to use for the view result provider `BadRequest` result.
	BadRequestTemplateName string `json:"badRequestTemplateName,omitempty" yaml:"badRequestTemplateName,omitempty"`
	// NotFoundTemplateName is the template name to use for the view result provider `NotFound` result.
	NotFoundTemplateName string `json:"notFoundTemplateName,omitempty" yaml:"notFoundTemplateName,omitempty"`
	// NotAuthorizedTemplateName is the template name to use for the view result provider `NotAuthorized` result.
	NotAuthorizedTemplateName string `json:"notAuthorizedTemplateName,omitempty" yaml:"notAuthorizedTemplateName,omitempty"`
	// StatusTemplateName is the template name to use for the view result provider status result.
	StatusTemplateName string `json:"statusTemplateName,omitempty" yaml:"statusTemplateName,omitempty"`
}

ViewCacheConfig is a config for the view cache.

func (ViewCacheConfig) BadRequestTemplateNameOrDefault added in v1.20201204.1

func (vcc ViewCacheConfig) BadRequestTemplateNameOrDefault() string

BadRequestTemplateNameOrDefault returns the bad request template name for the app.

func (ViewCacheConfig) BufferPoolSizeOrDefault added in v1.20201204.1

func (vcc ViewCacheConfig) BufferPoolSizeOrDefault() int

BufferPoolSizeOrDefault gets the buffer pool size or a default.

func (ViewCacheConfig) InternalErrorTemplateNameOrDefault added in v1.20201204.1

func (vcc ViewCacheConfig) InternalErrorTemplateNameOrDefault() string

InternalErrorTemplateNameOrDefault returns the internal error template name for the app.

func (ViewCacheConfig) NotAuthorizedTemplateNameOrDefault added in v1.20201204.1

func (vcc ViewCacheConfig) NotAuthorizedTemplateNameOrDefault() string

NotAuthorizedTemplateNameOrDefault returns the not authorized template name for the app.

func (ViewCacheConfig) NotFoundTemplateNameOrDefault added in v1.20201204.1

func (vcc ViewCacheConfig) NotFoundTemplateNameOrDefault() string

NotFoundTemplateNameOrDefault returns the not found template name for the app.

func (*ViewCacheConfig) Resolve added in v1.20201204.1

func (vcc *ViewCacheConfig) Resolve(ctx context.Context) error

Resolve adds extra resolution steps when we setup the config.

func (ViewCacheConfig) StatusTemplateNameOrDefault added in v1.20201204.1

func (vcc ViewCacheConfig) StatusTemplateNameOrDefault() string

StatusTemplateNameOrDefault returns the not authorized template name for the app.

type ViewCacheOption added in v1.20201204.1

type ViewCacheOption func(*ViewCache) error

ViewCacheOption is an option for ViewCache.

func OptViewCacheBadRequestTemplateName added in v1.20201204.1

func OptViewCacheBadRequestTemplateName(name string) ViewCacheOption

OptViewCacheBadRequestTemplateName sets the bad request template name.

func OptViewCacheConfig added in v1.20201204.1

func OptViewCacheConfig(cfg *ViewCacheConfig) ViewCacheOption

OptViewCacheConfig sets options based on a config.

func OptViewCacheFunc added in v1.20201204.1

func OptViewCacheFunc(name string, viewFunc interface{}) ViewCacheOption

OptViewCacheFunc adds a func to the view func map.

func OptViewCacheFuncMap added in v1.20201204.1

func OptViewCacheFuncMap(funcMap template.FuncMap) ViewCacheOption

OptViewCacheFuncMap sets the view cache func maps.

func OptViewCacheInternalErrorTemplateName added in v1.20201204.1

func OptViewCacheInternalErrorTemplateName(name string) ViewCacheOption

OptViewCacheInternalErrorTemplateName sets the internal error template name.

func OptViewCacheLiterals added in v1.20201204.1

func OptViewCacheLiterals(literals ...string) ViewCacheOption

OptViewCacheLiterals sets the view cache literals.

func OptViewCacheLiveReload added in v1.20201204.1

func OptViewCacheLiveReload(liveReload bool) ViewCacheOption

OptViewCacheLiveReload adds a func to the view func map.

func OptViewCacheNotAuthorizedTemplateName added in v1.20201204.1

func OptViewCacheNotAuthorizedTemplateName(name string) ViewCacheOption

OptViewCacheNotAuthorizedTemplateName sets the not authorized template name.

func OptViewCacheNotFoundTemplateName added in v1.20201204.1

func OptViewCacheNotFoundTemplateName(name string) ViewCacheOption

OptViewCacheNotFoundTemplateName sets the not found template name.

func OptViewCachePaths added in v1.20201204.1

func OptViewCachePaths(paths ...string) ViewCacheOption

OptViewCachePaths sets the view cache paths.

func OptViewCacheStatusTemplateName added in v1.20201204.1

func OptViewCacheStatusTemplateName(name string) ViewCacheOption

OptViewCacheStatusTemplateName sets the status template name.

type ViewModel

type ViewModel struct {
	Env       env.Vars
	Status    ViewStatus
	Ctx       *Ctx
	ViewModel interface{}
}

ViewModel is a wrapping viewmodel.

func (ViewModel) State added in v1.20201204.1

func (vm ViewModel) State(key string) interface{}

State returns a state value.

func (ViewModel) Wrap added in v1.20201204.1

func (vm ViewModel) Wrap(other interface{}) ViewModel

Wrap returns a ViewModel that wraps a new object.

type ViewResult

type ViewResult struct {
	ViewName   string
	StatusCode int
	ViewModel  interface{}
	Views      *ViewCache
	Template   *template.Template
}

ViewResult is a result that renders a view.

func (*ViewResult) Render

func (vr *ViewResult) Render(ctx *Ctx) (err error)

Render renders the result to the given response writer.

type ViewStatus added in v1.20201204.1

type ViewStatus struct {
	Code int
	Text string
}

ViewStatus is the result view model passed to status pages.

type ViewTraceFinisher

type ViewTraceFinisher interface {
	FinishView(*Ctx, *ViewResult, error)
}

ViewTraceFinisher is a finisher for view traces.

type ViewTracer

type ViewTracer interface {
	StartView(*Ctx, *ViewResult) ViewTraceFinisher
}

ViewTracer is a type that can listen for view rendering traces.

type XMLResult

type XMLResult struct {
	StatusCode int
	Response   interface{}
}

XMLResult is a json result.

func (*XMLResult) Render

func (ar *XMLResult) Render(ctx *Ctx) error

Render renders the result

type XMLResultProvider

type XMLResultProvider struct{}

XMLResultProvider are context results for api methods.

var (
	// XML is a static singleton xml result provider.
	XML XMLResultProvider
)

func (XMLResultProvider) BadRequest

func (xrp XMLResultProvider) BadRequest(err error) Result

BadRequest returns a service response.

func (XMLResultProvider) InternalError

func (xrp XMLResultProvider) InternalError(err error) Result

InternalError returns a service response.

func (XMLResultProvider) NotAuthorized

func (xrp XMLResultProvider) NotAuthorized() Result

NotAuthorized returns a service response.

func (XMLResultProvider) NotFound

func (xrp XMLResultProvider) NotFound() Result

NotFound returns a service response.

func (XMLResultProvider) OK

func (xrp XMLResultProvider) OK() Result

OK returns a service response.

func (XMLResultProvider) Result

func (xrp XMLResultProvider) Result(result interface{}) Result

Result returns an xml response.

func (XMLResultProvider) Status

func (xrp XMLResultProvider) Status(statusCode int, response interface{}) Result

Status returns a plaintext result.

Jump to

Keyboard shortcuts

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