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 recieved, letting requests finish.
There are many more examples in the github.com/blend/go-sdk/examples/web directory.
Index ¶
- Constants
- Variables
- func Base64URLDecode(raw string) ([]byte, error)
- func Base64URLEncode(raw []byte) string
- func BaseHeaders() http.Header
- func BoolValue(value string, inputErr error) (output bool, err error)
- func CSVValue(value string, err error) ([]string, error)
- func CleanPath(p string) string
- func CopySingleHeaders(headers map[string]string) http.Header
- func DurationValue(value string, inputErr error) (output time.Duration, err error)
- func Float64Value(value string, inputErr error) (output float64, err error)
- func GetRequestStarted(ctx context.Context) time.Time
- func Int64Value(value string, inputErr error) (output int64, err error)
- func IntValue(value string, inputErr error) (output int, err error)
- func IsErrBadRequest(err error) bool
- func IsErrParameterInvalid(err error) bool
- func IsErrParameterMissing(err error) bool
- func IsErrSessionInvalid(err error) bool
- func MergeHeaders(headers ...http.Header) http.Header
- func MockSimulateLogin(ctx context.Context, app *App, userID string, opts ...r2.Option) []r2.Option
- func NewCookie(name, value string) *http.Cookie
- func NewParameterInvalidError(paramName, message string) error
- func NewParameterMissingError(paramName string) error
- func NewSessionID() string
- func PathRedirectHandler(path string) func(*Ctx) *url.URL
- func ReadSetCookies(h http.Header) []*http.Cookie
- func ResultOrDefault(result, defaultResult interface{}) interface{}
- func SessionTimeoutProvider(isAbsolute bool, timeout time.Duration) func(*Session) time.Time
- func SessionTimeoutProviderAbsolute(timeout time.Duration) func(*Session) time.Time
- func SessionTimeoutProviderRolling(timeout time.Duration) func(*Session) time.Time
- func StringValue(value string, _ error) string
- func UUIDValue(param string, inputErr error) (uuid.UUID, error)
- func WithApp(ctx context.Context, app *App) context.Context
- func WithRequestStarted(ctx context.Context, requestStarted time.Time) context.Context
- func WithSession(ctx context.Context, session *Session) context.Context
- type Action
- func GZip(action Action) Action
- func JSONProviderAsDefault(action Action) Action
- func NestMiddleware(action Action, middleware ...Middleware) Action
- func SessionAware(action Action) Action
- func SessionRequired(action Action) Action
- func TextProviderAsDefault(action Action) Action
- func ViewProviderAsDefault(action Action) Action
- func XMLProviderAsDefault(action Action) Action
- type App
- func (a *App) Background() context.Context
- func (a *App) DELETE(path string, action Action, middleware ...Middleware)
- func (a *App) GET(path string, action Action, middleware ...Middleware)
- func (a *App) HEAD(path string, action Action, middleware ...Middleware)
- func (a *App) Handle(method, path string, handler Handler)
- func (a *App) Lookup(method, path string) (route *Route, params RouteParameters, skipSlashRedirect bool)
- func (a *App) Method(method string, path string, action Action, middleware ...Middleware)
- func (a *App) MethodBare(method string, path string, action Action, middleware ...Middleware)
- func (a *App) OPTIONS(path string, action Action, middleware ...Middleware)
- func (a *App) PATCH(path string, action Action, middleware ...Middleware)
- func (a *App) POST(path string, action Action, middleware ...Middleware)
- func (a *App) PUT(path string, action Action, middleware ...Middleware)
- func (a *App) Register(controllers ...Controller)
- func (a *App) RenderAction(action Action) Handler
- func (a *App) RenderActionBare(action Action) Handler
- func (a *App) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (a *App) ServeStatic(route string, searchPaths []string, middleware ...Middleware)
- func (a *App) ServeStaticCached(route string, searchPaths []string, middleware ...Middleware)
- func (a *App) SetStaticHeader(route, key, value string) error
- func (a *App) SetStaticRewriteRule(route, match string, action RewriteAction) error
- func (a *App) Start() (err error)
- func (a *App) StartupTasks() (err error)
- func (a *App) Stop() error
- type AuthManager
- func MustNewAuthManager(options ...AuthManagerOption) AuthManager
- func NewAuthManager(options ...AuthManagerOption) (manager AuthManager, err error)
- func NewLocalAuthManager(options ...AuthManagerOption) (AuthManager, error)
- func NewLocalAuthManagerFromCache(cache *LocalSessionCache, options ...AuthManagerOption) (manager AuthManager, err error)
- type AuthManagerFetchSessionHandler
- type AuthManagerOption
- func OptAuthManagerCookieDefaults(cookie http.Cookie) AuthManagerOption
- func OptAuthManagerCookieDomain(domain string) AuthManagerOption
- func OptAuthManagerCookieHTTPOnly(httpOnly bool) AuthManagerOption
- func OptAuthManagerCookieName(cookieName string) AuthManagerOption
- func OptAuthManagerCookiePath(cookiePath string) AuthManagerOption
- func OptAuthManagerCookieSameSite(sameSite http.SameSite) AuthManagerOption
- func OptAuthManagerCookieSecure(secure bool) AuthManagerOption
- func OptAuthManagerFetchHandler(handler AuthManagerFetchSessionHandler) AuthManagerOption
- func OptAuthManagerFromConfig(cfg Config) AuthManagerOption
- func OptAuthManagerLoginRedirectHandler(handler AuthManagerRedirectHandler) AuthManagerOption
- func OptAuthManagerPersistHandler(handler AuthManagerPersistSessionHandler) AuthManagerOption
- func OptAuthManagerRemoveHandler(handler AuthManagerRemoveSessionHandler) AuthManagerOption
- func OptAuthManagerSerializeHandler(handler AuthManagerSerializeSessionHandler) AuthManagerOption
- func OptAuthManagerSessionTimeoutProvider(handler AuthManagerSessionTimeoutProvider) AuthManagerOption
- func OptAuthManagerValidateHandler(handler AuthManagerValidateSessionHandler) AuthManagerOption
- type AuthManagerPersistSessionHandler
- type AuthManagerRedirectHandler
- type AuthManagerRemoveSessionHandler
- type AuthManagerSerializeSessionHandler
- type AuthManagerSessionTimeoutProvider
- type AuthManagerValidateSessionHandler
- type CachedStaticFile
- type Config
- func (c Config) BaseURLOrDefault() string
- func (c Config) BindAddrOrDefault(defaults ...string) string
- func (c Config) CookieDomainOrDefault() string
- func (c Config) CookieHTTPOnlyOrDefault() bool
- func (c Config) CookieNameOrDefault() string
- func (c Config) CookiePathOrDefault() string
- func (c Config) CookieSameSiteOrDefault() http.SameSite
- func (c Config) CookieSecureOrDefault() bool
- func (c Config) IdleTimeoutOrDefault() time.Duration
- func (c Config) IsZero() bool
- func (c Config) KeepAliveOrDefault() bool
- func (c Config) KeepAlivePeriodOrDefault() time.Duration
- func (c Config) MaxHeaderBytesOrDefault() int
- func (c Config) PortOrDefault() int32
- func (c Config) ReadHeaderTimeoutOrDefault() time.Duration
- func (c Config) ReadTimeoutOrDefault() time.Duration
- func (c *Config) Resolve(ctx context.Context) error
- func (c Config) ResolveCookieDomain(_ context.Context) (*string, error)
- func (c Config) ResolveCookieSecure(_ context.Context) (*bool, error)
- func (c Config) SessionTimeoutOrDefault() time.Duration
- func (c Config) ShutdownGracePeriodOrDefault() time.Duration
- func (c Config) WriteTimeoutOrDefault() time.Duration
- type Controller
- type Ctx
- func (rc *Ctx) Annotations() map[string]interface{}
- func (rc *Ctx) Close() error
- func (rc *Ctx) Context() context.Context
- func (rc *Ctx) Cookie(name string) *http.Cookie
- func (rc *Ctx) Elapsed() time.Duration
- func (rc *Ctx) EnsureForm() error
- func (rc *Ctx) ExpireCookie(name string, path string)
- func (rc *Ctx) ExtendCookie(name string, path string, years, months, days int)
- func (rc *Ctx) ExtendCookieByDuration(name string, path string, duration time.Duration)
- func (rc *Ctx) FormValue(key string) (output string, err error)
- func (rc *Ctx) HeaderValue(key string) (value string, err error)
- func (rc *Ctx) Labels() map[string]string
- func (rc *Ctx) Param(name string) (value string, err error)
- func (rc *Ctx) PostBody() ([]byte, error)
- func (rc *Ctx) PostBodyAsForm(response interface{}) error
- func (rc *Ctx) PostBodyAsJSON(response interface{}) error
- func (rc *Ctx) PostBodyAsString() (string, error)
- func (rc *Ctx) PostBodyAsXML(response interface{}) error
- func (rc *Ctx) QueryValue(key string) (value string, err error)
- func (rc *Ctx) RouteParam(key string) (output string, err error)
- func (rc *Ctx) StateValue(key string) interface{}
- func (rc *Ctx) WithContext(ctx context.Context) *Ctx
- func (rc *Ctx) WithStateValue(key string, value interface{}) *Ctx
- type CtxOption
- func CtxRequestOption(opt func(*http.Request) error) CtxOption
- func OptCtxApp(a *App) CtxOption
- func OptCtxAuth(auth AuthManager) CtxOption
- func OptCtxBodyBytes(body []byte) CtxOption
- func OptCtxCookieValue(key, value string) CtxOption
- func OptCtxDefaultProvider(rp ResultProvider) CtxOption
- func OptCtxHeaderValue(key, value string) CtxOption
- func OptCtxLog(log logger.Log) CtxOption
- func OptCtxPostFormValue(key, value string) CtxOption
- func OptCtxPostedFiles(files ...webutil.PostedFile) CtxOption
- func OptCtxQueryValue(key, value string) CtxOption
- func OptCtxRequestStarted(ts time.Time) CtxOption
- func OptCtxRoute(r *Route) CtxOption
- func OptCtxRouteParamValue(key, value string) CtxOption
- func OptCtxRouteParams(r RouteParameters) CtxOption
- func OptCtxSession(s *Session) CtxOption
- func OptCtxState(s State) CtxOption
- func OptCtxTracer(tracer Tracer) CtxOption
- func OptCtxViews(vc *ViewCache) CtxOption
- type Handler
- type JSONResult
- type JSONResultProvider
- func (jrp JSONResultProvider) BadRequest(err error) Result
- func (jrp JSONResultProvider) Forbidden() Result
- func (jrp JSONResultProvider) InternalError(err error) Result
- func (jrp JSONResultProvider) NotAuthorized() Result
- func (jrp JSONResultProvider) NotFound() Result
- func (jrp JSONResultProvider) OK() Result
- func (jrp JSONResultProvider) Result(response interface{}) Result
- func (jrp JSONResultProvider) Status(statusCode int, response interface{}) Result
- type JWTManager
- func (jwtm JWTManager) Apply(am *AuthManager)
- func (jwtm JWTManager) Claims(session *Session) *jwt.StandardClaims
- func (jwtm JWTManager) FetchHandler(_ context.Context, sessionValue string) (*Session, error)
- func (jwtm JWTManager) FromClaims(claims *jwt.StandardClaims) *Session
- func (jwtm JWTManager) KeyFunc(token *jwt.Token) (interface{}, error)
- func (jwtm JWTManager) SerializeHandler(_ context.Context, session *Session) (output string, err error)
- type LocalSessionCache
- func (lsc *LocalSessionCache) Apply(am *AuthManager)
- func (lsc *LocalSessionCache) FetchHandler(_ context.Context, sessionID string) (*Session, error)
- func (lsc *LocalSessionCache) Get(sessionID string) *Session
- func (lsc *LocalSessionCache) PersistHandler(_ context.Context, session *Session) error
- func (lsc *LocalSessionCache) Remove(sessionID string)
- func (lsc *LocalSessionCache) RemoveHandler(_ context.Context, sessionID string) error
- func (lsc *LocalSessionCache) Upsert(session *Session)
- type LoggedErrorResult
- type Middleware
- type MockResult
- func Mock(app *App, req *http.Request, options ...r2.Option) *MockResult
- func MockGet(app *App, path string, options ...r2.Option) *MockResult
- func MockMethod(app *App, method, path string, options ...r2.Option) *MockResult
- func MockPost(app *App, path string, body io.ReadCloser, options ...r2.Option) *MockResult
- func MockPostJSON(app *App, path string, body interface{}, options ...r2.Option) *MockResult
- type NoContentResult
- type Option
- func OptAuth(auth AuthManager, err error) Option
- func OptBaseHeaders(headers http.Header) Option
- func OptBaseMiddleware(middleware ...Middleware) Option
- func OptBaseStateValue(key string, value interface{}) Option
- func OptBindAddr(bindAddr string) Option
- func OptConfig(cfg Config) Option
- func OptConfigFromEnv() Option
- func OptDefaultHeader(key, value string) Option
- func OptDefaultHeaders(headers http.Header) Option
- func OptDefaultMiddleware(middleware ...Middleware) Option
- func OptIdleTimeout(d time.Duration) Option
- func OptLog(log logger.Log) Option
- func OptMaxHeaderBytes(maxHeaderBytes int) Option
- func OptMethodNotAllowedHandler(action Action) Option
- func OptNotFoundHandler(action Action) Option
- func OptPort(port int32) Option
- func OptReadHeaderTimeout(d time.Duration) Option
- func OptReadTimeout(d time.Duration) Option
- func OptServer(server *http.Server) Option
- func OptServerOptions(opts ...webutil.HTTPServerOption) Option
- func OptShutdownGracePeriod(d time.Duration) Option
- func OptTLSConfig(cfg *tls.Config) Option
- func OptTracer(tracer Tracer) Option
- func OptUse(m Middleware) Option
- func OptViews(views *ViewCache) Option
- func OptWriteTimeout(d time.Duration) Option
- type PanicAction
- type PanicHandler
- type PostedFile
- type RawResult
- type RedirectResult
- type ResponseWriter
- type Result
- type ResultPostRender
- type ResultPreRender
- type ResultProvider
- type RewriteAction
- type RewriteRule
- type Route
- type RouteNode
- type RouteNodeType
- type RouteParameters
- type Session
- type State
- type StaticFileServer
- func (sc *StaticFileServer) Action(r *Ctx) Result
- func (sc *StaticFileServer) AddHeader(key, value string)
- func (sc *StaticFileServer) AddRewriteRule(match string, action RewriteAction) error
- func (sc *StaticFileServer) ResolveCachedFile(filepath string) (*CachedStaticFile, error)
- func (sc *StaticFileServer) ResolveFile(filePath string) (f http.File, finalPath string, err error)
- func (sc *StaticFileServer) ServeCachedFile(r *Ctx, filepath string) Result
- func (sc *StaticFileServer) ServeFile(r *Ctx, filePath string) Result
- type StaticFileserverOption
- type StaticResult
- type StatusViewModel
- type SyncState
- type TLSOption
- type TextResultProvider
- func (trp TextResultProvider) BadRequest(err error) Result
- func (trp TextResultProvider) InternalError(err error) Result
- func (trp TextResultProvider) NotAuthorized() Result
- func (trp TextResultProvider) NotFound() Result
- func (trp TextResultProvider) OK() Result
- func (trp TextResultProvider) Result(result interface{}) Result
- func (trp TextResultProvider) Status(statusCode int, response interface{}) Result
- type TraceFinisher
- type Tracer
- type ViewCache
- func (vc *ViewCache) AddLiterals(views ...string)
- func (vc *ViewCache) AddPaths(paths ...string)
- func (vc *ViewCache) BadRequest(err error) Result
- func (vc *ViewCache) Initialize() error
- func (vc *ViewCache) InternalError(err error) Result
- func (vc *ViewCache) Lookup(name string) (*template.Template, error)
- func (vc *ViewCache) NotAuthorized() Result
- func (vc *ViewCache) NotFound() Result
- func (vc *ViewCache) Parse() (views *template.Template, err error)
- func (vc *ViewCache) Status(statusCode int, response interface{}) Result
- func (vc *ViewCache) View(viewName string, viewModel interface{}) Result
- func (vc *ViewCache) ViewStatus(statusCode int, viewName string, viewModel interface{}) Result
- type ViewCacheConfig
- func (vcc ViewCacheConfig) BadRequestTemplateNameOrDefault() string
- func (vcc ViewCacheConfig) BufferPoolSizeOrDefault() int
- func (vcc ViewCacheConfig) InternalErrorTemplateNameOrDefault() string
- func (vcc ViewCacheConfig) NotAuthorizedTemplateNameOrDefault() string
- func (vcc ViewCacheConfig) NotFoundTemplateNameOrDefault() string
- func (vcc *ViewCacheConfig) Resolve(ctx context.Context) error
- func (vcc ViewCacheConfig) StatusTemplateNameOrDefault() string
- type ViewCacheOption
- func OptViewCacheBadRequestTemplateName(name string) ViewCacheOption
- func OptViewCacheConfig(cfg *ViewCacheConfig) ViewCacheOption
- func OptViewCacheFunc(name string, viewFunc interface{}) ViewCacheOption
- func OptViewCacheFuncMap(funcMap template.FuncMap) ViewCacheOption
- func OptViewCacheInternalErrorTemplateName(name string) ViewCacheOption
- func OptViewCacheLiterals(literals ...string) ViewCacheOption
- func OptViewCacheLiveReload(liveReload bool) ViewCacheOption
- func OptViewCacheNotAuthorizedTemplateName(name string) ViewCacheOption
- func OptViewCacheNotFoundTemplateName(name string) ViewCacheOption
- func OptViewCachePaths(paths ...string) ViewCacheOption
- func OptViewCacheStatusTemplateName(name string) ViewCacheOption
- type ViewModel
- type ViewResult
- type ViewStatus
- type ViewTraceFinisher
- type ViewTracer
- type XMLResult
- type XMLResultProvider
- func (xrp XMLResultProvider) BadRequest(err error) Result
- func (xrp XMLResultProvider) InternalError(err error) Result
- func (xrp XMLResultProvider) NotAuthorized() Result
- func (xrp XMLResultProvider) NotFound() Result
- func (xrp XMLResultProvider) OK() Result
- func (xrp XMLResultProvider) Result(result interface{}) Result
- func (xrp XMLResultProvider) Status(statusCode int, response interface{}) Result
Constants ¶
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" )
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 )
const ( // LenSessionID is the byte length of a session id. LenSessionID = 64 // LenSessionIDBase64 is the length of a session id base64 encoded. LenSessionIDBase64 = 88 )
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" )
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 */ )
const ( // ErrJWTNonstandardClaims can be returned by the jwt manager keyfunc. ErrJWTNonstandardClaims = ex.Class("jwt; invalid claims object; should be standard claims") )
Variables ¶
var (
ErrInvalidBoolValue = fmt.Errorf("invalid boolean value")
)
Common errors
Functions ¶
func Base64URLDecode ¶
Base64URLDecode decodes a base64 string.
func BaseHeaders ¶ added in v1.20201204.1
BaseHeaders are the default headers added by go-web.
func CleanPath ¶
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:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- 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
CopySingleHeaders copies headers in single value format.
func DurationValue ¶
DurationValue parses a value as an time.Duration. If the input error is set it short circuits.
func Float64Value ¶
Float64Value parses a value as an float64. If the input error is set it short circuits.
func GetRequestStarted ¶ added in v1.20201204.1
GetRequestStarted gets the request started time from a context.
func Int64Value ¶
Int64Value parses a value as an int64. If the input error is set it short circuits.
func IsErrBadRequest ¶ added in v1.20201204.1
IsErrBadRequest returns if an error is a bad request triggering error.
func IsErrParameterInvalid ¶ added in v1.20201204.1
IsErrParameterInvalid returns if an error is an ErrParameterInvalid.
func IsErrParameterMissing ¶ added in v1.20201204.1
IsErrParameterMissing returns if an error is an ErrParameterMissing.
func IsErrSessionInvalid ¶
IsErrSessionInvalid returns if an error is a session invalid error.
func MergeHeaders ¶ added in v1.20201204.1
MergeHeaders merges headers.
func MockSimulateLogin ¶ added in v1.20210215.2
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 NewParameterInvalidError ¶ added in v1.20201204.1
NewParameterInvalidError returns a new parameter invalid error.
func NewParameterMissingError ¶ added in v1.20201204.1
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 ¶
PathRedirectHandler returns a handler for AuthManager.RedirectHandler based on a path.
func ReadSetCookies ¶
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 ¶
SessionTimeoutProvider returns a new session timeout provider.
func SessionTimeoutProviderAbsolute ¶
SessionTimeoutProviderAbsolute returns an absolute session timeout.
func SessionTimeoutProviderRolling ¶
SessionTimeoutProviderRolling returns a rolling session timeout.
func StringValue ¶
StringValue just returns the string directly from a value error pair.
func WithRequestStarted ¶ added in v1.20201204.1
WithRequestStarted sets the request started time on a context.
Types ¶
type Action ¶
Action is the function signature for controller actions.
func GZip ¶ added in v1.20201204.1
GZip is a middleware the implements gzip compression for requests that opt into it.
func JSONProviderAsDefault ¶
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 ¶
SessionAware is an action that injects the session into the context, it acquires a read lock on session.
func SessionRequired ¶
SessionRequired is an action that requires a session to be present or identified in some form on the request, and acquires a read lock on session.
func TextProviderAsDefault ¶
TextProviderAsDefault sets the context.DefaultResultProvider() equal to context.Text().
func ViewProviderAsDefault ¶
ViewProviderAsDefault sets the context.DefaultResultProvider() equal to context.View().
func XMLProviderAsDefault ¶
XMLProviderAsDefault sets the context.DefaultResultProvider() equal to context.XML().
type App ¶
type App struct { *async.Latch 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 Routes map[string]*RouteNode DefaultProvider ResultProvider Views *ViewCache NotFoundHandler Handler MethodNotAllowedHandler Handler PanicAction PanicAction }
App is the server for the app.
func (*App) Background ¶ added in v1.20201204.1
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) Handle ¶
Handle adds a raw handler at a given method and path. It skips middleware, you must implement things like logging and tracing yourself in the handler.
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
RenderAction is the translation step from Action to Handler.
func (*App) RenderActionBare ¶ added in v1.20201204.1
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 ¶
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) StartupTasks ¶
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.
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) VerifyOrExpireSession ¶ added in v1.20201204.1
func (am AuthManager) VerifyOrExpireSession(ctx *Ctx) (session *Session, err error)
VerifyOrExpireSession reads a session value from a request and checks if it's valid. It also handles updating a rolling expiry.
type AuthManagerFetchSessionHandler ¶ added in v1.20210306.3
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
AuthManagerPersistSessionHandler saves the session to a stable store.
type AuthManagerRedirectHandler ¶
AuthManagerRedirectHandler is a redirect handler.
type AuthManagerRemoveSessionHandler ¶ added in v1.20210306.3
AuthManagerRemoveSessionHandler removes a session based on a session value.
type AuthManagerSerializeSessionHandler ¶ added in v1.20210306.3
AuthManagerSerializeSessionHandler serializes a session as a string.
type AuthManagerSessionTimeoutProvider ¶
AuthManagerSessionTimeoutProvider provides a new timeout for a session.
type AuthManagerValidateSessionHandler ¶ added in v1.20210306.3
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
BaseURLOrDefault gets the base url for the app or a default.
func (Config) BindAddrOrDefault ¶ added in v1.20201204.1
BindAddrOrDefault returns the bind address or a default.
func (Config) CookieDomainOrDefault ¶ added in v1.20201204.1
CookieDomainOrDefault returns a property or a default.
func (Config) CookieHTTPOnlyOrDefault ¶ added in v1.20201204.1
CookieHTTPOnlyOrDefault returns a property or a default.
func (Config) CookieNameOrDefault ¶ added in v1.20201204.1
CookieNameOrDefault returns a property or a default.
func (Config) CookiePathOrDefault ¶ added in v1.20201204.1
CookiePathOrDefault returns a property or a default.
func (Config) CookieSameSiteOrDefault ¶ added in v1.20201204.1
CookieSameSiteOrDefault returns a property or a default.
func (Config) CookieSecureOrDefault ¶ added in v1.20201204.1
CookieSecureOrDefault returns a property or a default.
func (Config) IdleTimeoutOrDefault ¶ added in v1.20201204.1
IdleTimeoutOrDefault gets a property.
func (Config) KeepAliveOrDefault ¶ added in v1.20201204.1
KeepAliveOrDefault returns if we should keep TCP connections open.
func (Config) KeepAlivePeriodOrDefault ¶ added in v1.20201204.1
KeepAlivePeriodOrDefault returns the TCP keep alive period or a default.
func (Config) MaxHeaderBytesOrDefault ¶ added in v1.20201204.1
MaxHeaderBytesOrDefault returns the maximum header size in bytes or a default.
func (Config) PortOrDefault ¶ added in v1.20201204.1
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
ReadHeaderTimeoutOrDefault gets a property.
func (Config) ReadTimeoutOrDefault ¶ added in v1.20201204.1
ReadTimeoutOrDefault gets a property.
func (Config) ResolveCookieDomain ¶ added in v1.20210104.2
ResolveCookieDomain is a resolver for the `CookieDomain` field based on the BaseURL if one is provided.
func (Config) ResolveCookieSecure ¶ added in v1.20210104.2
ResolveCookieSecure is a resolver for the `CookieSecure` field based on the BaseURL if one is provided.
func (Config) SessionTimeoutOrDefault ¶ added in v1.20201204.1
SessionTimeoutOrDefault returns a property or a default.
func (Config) ShutdownGracePeriodOrDefault ¶ added in v1.20201204.1
ShutdownGracePeriodOrDefault gets the shutdown grace period.
func (Config) WriteTimeoutOrDefault ¶ added in v1.20201204.1
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 maching 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
MockCtx returns a new mock ctx. It is intended to be used in testing.
func MockCtxWithBuffer ¶ added in v1.20210201.1
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
Annotations returns the annotations for logging calls.
func (*Ctx) EnsureForm ¶ added in v1.20201204.1
EnsureForm parses the post body as an application form. The parsed form will be available on the `.Form` field.
func (*Ctx) ExpireCookie ¶
ExpireCookie expires a cookie.
func (*Ctx) ExtendCookie ¶
ExtendCookie extends a cookie by years, months or days.
func (*Ctx) ExtendCookieByDuration ¶
ExtendCookieByDuration extends a cookie by a time duration (on the order of nanoseconds to hours).
func (*Ctx) HeaderValue ¶
HeaderValue returns a header value.
func (*Ctx) Param ¶
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 ¶
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
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 ¶
PostBodyAsJSON reads the incoming post body (closing it) and marshals it to the target object as json.
func (*Ctx) PostBodyAsString ¶
PostBodyAsString returns the post body as a string.
func (*Ctx) PostBodyAsXML ¶
PostBodyAsXML reads the incoming post body (closing it) and marshals it to the target object as xml.
func (*Ctx) QueryValue ¶
QueryValue returns a query value.
func (*Ctx) RouteParam ¶
RouteParam returns a string route parameter
func (*Ctx) StateValue ¶
StateValue returns an object in the state cache.
func (*Ctx) WithContext ¶
WithContext sets the background context for the request.
func (*Ctx) WithStateValue ¶
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
CtxRequestOption is a ctx option that wraps a request option.
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
OptCtxBodyBytes sets a post body on a context.
func OptCtxCookieValue ¶ added in v1.20201204.1
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
OptCtxHeaderValue sets a header value on a context.
func OptCtxPostFormValue ¶ added in v1.20201204.1
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
OptCtxQueryValue sets a query value on a context.
func OptCtxRequestStarted ¶ added in v1.20201204.1
OptCtxRequestStarted sets the context request started timestamp.
func OptCtxRoute ¶ added in v1.20201204.1
OptCtxRoute sets the context route.
func OptCtxRouteParamValue ¶ added in v1.20201204.1
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
OptCtxSession sets the context session.
func OptCtxState ¶ added in v1.20201204.1
OptCtxState sets the context state.
func OptCtxTracer ¶ added in v1.20201204.1
OptCtxTracer sets the context tracer.
func OptCtxViews ¶ added in v1.20201204.1
OptCtxViews sets the context views cache.
type Handler ¶
type Handler func(http.ResponseWriter, *http.Request, *Route, RouteParameters)
Handler is the most basic route handler.
func WrapHandler ¶
WrapHandler wraps an http.Handler as a Handler.
type JSONResult ¶
type JSONResult struct { StatusCode int Response interface{} }
JSONResult is a json 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 ¶
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
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 ¶
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 ¶
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
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 ¶
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
MockResult is a result of a mocked request.
func Mock ¶ added in v1.20201204.1
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
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 OptBaseHeaders ¶ added in v1.20201204.1
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
OptBaseStateValue sets a base state value.
func OptBindAddr ¶ added in v1.20201204.1
OptBindAddr sets the config bind address
func OptConfigFromEnv ¶ added in v1.20201204.1
func OptConfigFromEnv() Option
OptConfigFromEnv sets the config from the environment.
func OptDefaultHeader ¶ added in v1.20201204.1
OptDefaultHeader sets a default header.
func OptDefaultHeaders ¶ added in v1.20201204.1
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
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 OptMaxHeaderBytes ¶ added in v1.20210215.2
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
OptMethodNotAllowedHandler sets default headers.
func OptNotFoundHandler ¶ added in v1.20201204.1
OptNotFoundHandler sets default headers.
func OptReadHeaderTimeout ¶ added in v1.20210215.2
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
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 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
OptShutdownGracePeriod sets the shutdown grace period.
func OptTLSConfig ¶ added in v1.20201204.1
OptTLSConfig sets the tls config.
func OptUse ¶ added in v1.20201204.1
func OptUse(m Middleware) Option
OptUse adds to the default middleware.
func OptWriteTimeout ¶ added in v1.20210215.2
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 ¶
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 ¶
PostedFile is a file that has been posted to an hc endpoint.
type RawResult ¶
RawResult is for when you just want to dump bytes.
func RawWithContentType ¶ added in v1.20201204.1
RawWithContentType returns a binary response with a given content type.
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 ResultPostRender ¶ added in v1.20201204.1
ResultPostRender is a result that has a PostRender step.
type ResultPreRender ¶
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 ¶
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.
type Route ¶
Route is an entry in the route tree.
func (Route) StringWithMethod ¶
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.
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 ¶
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 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
GetSession gets a session off a context.
func NewSession ¶
NewSession returns a new session object.
func (*Session) IsZero ¶
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 ¶
WithBaseURL sets the base url.
func (*Session) WithRemoteAddr ¶
WithRemoteAddr sets the remote addr.
func (*Session) WithUserAgent ¶
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
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.
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 TLSOption ¶ added in v1.20201204.1
TLSOption is an option for TLS configs.
func OptTLSClientCertPool ¶ added in v1.20201204.1
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 ¶
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 ¶
AddLiterals adds view literal strings to the view collection.
func (*ViewCache) BadRequest ¶
BadRequest returns a view result.
func (*ViewCache) Initialize ¶
Initialize caches templates by path.
func (*ViewCache) InternalError ¶
InternalError returns a view result.
func (*ViewCache) NotAuthorized ¶
NotAuthorized returns a view result.
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
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.
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
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.
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.
Source Files ¶
- action.go
- app.go
- auth_manager.go
- base_headers.go
- cached_static_file.go
- config.go
- constants.go
- context.go
- controller.go
- ctx.go
- ctx_option.go
- default_provider_middleware.go
- doc.go
- errors.go
- gzip_middleware.go
- handler.go
- json_result.go
- json_result_provider.go
- jwt_manager.go
- local_session_cache.go
- logged_error_result.go
- middleware.go
- mock.go
- no_content_result.go
- option.go
- panic_handler.go
- posted_file.go
- raw_result.go
- read_set_cookies.go
- redirect_result.go
- response_writer.go
- result.go
- result_provider.go
- rewrite_rule.go
- route.go
- route_parameters.go
- session.go
- session_middleware.go
- session_timeout_provider.go
- state.go
- static_file_server.go
- static_result.go
- status_view_model.go
- text_result_provider.go
- timeout.go
- tls_option.go
- tracer.go
- tree.go
- util.go
- value_parsers.go
- view_cache.go
- view_cache_config.go
- view_cache_option.go
- view_model.go
- view_result.go
- view_status.go
- xml_result.go
- xml_result_provider.go