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 applications.
To create a new server, simply instantiate one:
import "log" import "github.com/blend/go-sdk/web" ... app := web.New() app.GET("/", func(_ *web.Ctx) web.Result { return web.Text.Result("hello world") }) if err := web.StartWithGracefulShutdown(app); err != nil { log.Fatal(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.
There are many more examples in the `_examples` directory.
Index ¶
- Constants
- Variables
- func Base64URLDecode(raw string) ([]byte, error)
- func Base64URLEncode(raw []byte) string
- func BoolValue(value string, inputErr error) (output bool, err error)
- func CSVValue(value string, err error) ([]string, error)
- func CleanPath(p string) string
- func DurationValue(value string, inputErr error) (output time.Duration, err error)
- func Float64Value(value string, inputErr error) (output float64, err error)
- func Int64Value(value string, inputErr error) (output int64, err error)
- func IntValue(value string, inputErr error) (output int, err error)
- func IsErrSessionInvalid(err error) bool
- func NewAppEventListener(listener func(me *AppEvent)) logger.Listener
- func NewCookie(name, value string) *http.Cookie
- func NewCtxID() string
- func NewSessionID() string
- func ParseInt32(v string) int32
- func PathRedirectHandler(path string) func(*Ctx) *url.URL
- func ReadSetCookies(h http.Header) []*http.Cookie
- func ResultOrDefault(defaultResult interface{}, result ...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
- type 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 Any
- type App
- func (a *App) Auth() *AuthManager
- func (a *App) BaseURL() *url.URL
- func (a *App) BindAddr() string
- func (a *App) Config() *Config
- func (a *App) CreateServer() *http.Server
- func (a *App) DELETE(path string, action Action, middleware ...Middleware)
- func (a *App) DefaultHeaders() map[string]string
- func (a *App) DefaultMiddleware() []Middleware
- func (a *App) DefaultResultProvider() ResultProvider
- func (a *App) GET(path string, action Action, middleware ...Middleware)
- func (a *App) HEAD(path string, action Action, middleware ...Middleware)
- func (a *App) HSTS() *HSTSConfig
- func (a *App) Handle(method, path string, handler Handler)
- func (a *App) HandleMethodNotAllowed() bool
- func (a *App) HandleOptions() bool
- func (a *App) Handler() http.Handler
- func (a *App) IdleTimeout() time.Duration
- func (a *App) IsRunning() bool
- func (a *App) Latch() *async.Latch
- func (a *App) Listener() *net.TCPListener
- func (a *App) Logger() *logger.Logger
- func (a *App) Lookup(method, path string) (route *Route, params RouteParameters, slashRedirect bool)
- func (a *App) MaxHeaderBytes() int
- func (a *App) MethodNotAllowedHandler() Handler
- func (a *App) Mock() *MockRequestBuilder
- func (a *App) NotFoundHandler() Handler
- func (a *App) NotifyStarted() <-chan struct{}
- func (a *App) NotifyStopped() <-chan struct{}
- 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) PanicAction() PanicAction
- func (a *App) ReadHeaderTimeout() time.Duration
- func (a *App) ReadTimeout() time.Duration
- func (a *App) RecoverPanics() bool
- func (a *App) RedirectTrailingSlash() bool
- func (a *App) Register(c Controller)
- func (a *App) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (a *App) ServeStatic(route, filepath string)
- func (a *App) ServeStaticCached(route, filepath string)
- func (a *App) Server() *http.Server
- func (a *App) SetStaticHeader(route, key, value string) error
- func (a *App) SetStaticMiddleware(route string, middlewares ...Middleware) error
- func (a *App) SetStaticRewriteRule(route, match string, action RewriteAction) error
- func (a *App) SetTLSClientCertPool(certs ...[]byte) error
- func (a *App) Shutdown() error
- func (a *App) ShutdownGracePeriod() time.Duration
- func (a *App) Start() (err error)
- func (a *App) StartupTasks() error
- func (a *App) State() State
- func (a *App) StateValue(key string) interface{}
- func (a *App) Stop() error
- func (a *App) TLSConfig() *tls.Config
- func (a *App) Tracer() Tracer
- func (a *App) Views() *ViewCache
- func (a *App) WithAuth(am *AuthManager) *App
- func (a *App) WithBaseURL(baseURL *url.URL) *App
- func (a *App) WithBindAddr(bindAddr string) *App
- func (a *App) WithConfig(cfg *Config) *App
- func (a *App) WithControllers(controllers ...Controller) *App
- func (a *App) WithDefaultHeader(key string, value string) *App
- func (a *App) WithDefaultHeaders(headers map[string]string) *App
- func (a *App) WithDefaultMiddleware(middleware ...Middleware) *App
- func (a *App) WithDefaultMiddlewares(middleware ...Middleware) *App
- func (a *App) WithDefaultResultProvider(drp ResultProvider) *App
- func (a *App) WithHSTS(hsts *HSTSConfig) *App
- func (a *App) WithHandleMethodNotAllowed(handle bool) *App
- func (a *App) WithHandleOptions(handle bool) *App
- func (a *App) WithHandler(handler http.Handler) *App
- func (a *App) WithIdleTimeout(timeout time.Duration) *App
- func (a *App) WithLogger(log *logger.Logger) *App
- func (a *App) WithMaxHeaderBytes(byteCount int) *App
- func (a *App) WithMethodNotAllowedHandler(handler Action) *App
- func (a *App) WithNotFoundHandler(handler Action) *App
- func (a *App) WithPanicAction(action PanicAction) *App
- func (a *App) WithPort(port int32) *App
- func (a *App) WithReadHeaderTimeout(timeout time.Duration) *App
- func (a *App) WithReadTimeout(timeout time.Duration) *App
- func (a *App) WithRecoverPanics(value bool) *App
- func (a *App) WithRedirectTrailingSlash(value bool) *App
- func (a *App) WithServer(server *http.Server) *App
- func (a *App) WithShutdownGracePeriod(gracePeriod time.Duration) *App
- func (a *App) WithStateValue(key string, value interface{}) *App
- func (a *App) WithTLSClientCertVerification(verification tls.ClientAuthType) *App
- func (a *App) WithTLSConfig(config *tls.Config) *App
- func (a *App) WithTracer(tracer Tracer) *App
- func (a *App) WithViews(vc *ViewCache) *App
- func (a *App) WithWriteTimeout(timeout time.Duration) *App
- func (a *App) WriteTimeout() time.Duration
- type AppEvent
- func (ae AppEvent) App() *App
- func (ae *AppEvent) Elapsed() time.Duration
- func (ae *AppEvent) Err() error
- func (ae AppEvent) Healthz() *Healthz
- func (ae AppEvent) Upgrader() *HTTPSUpgrader
- func (ae *AppEvent) WithAnnotation(key, value string) *AppEvent
- func (ae *AppEvent) WithApp(app *App) *AppEvent
- func (ae *AppEvent) WithElapsed(elapsed time.Duration) *AppEvent
- func (ae *AppEvent) WithErr(err error) *AppEvent
- func (ae *AppEvent) WithFlag(flag logger.Flag) *AppEvent
- func (ae *AppEvent) WithHeadings(headings ...string) *AppEvent
- func (ae *AppEvent) WithHealthz(hz *Healthz) *AppEvent
- func (ae *AppEvent) WithLabel(key, value string) *AppEvent
- func (ae *AppEvent) WithTimestamp(ts time.Time) *AppEvent
- func (ae *AppEvent) WithUpgrader(upgrader *HTTPSUpgrader) *AppEvent
- func (ae *AppEvent) WriteJSON() logger.JSONObj
- func (ae *AppEvent) WriteText(tf logger.TextFormatter, buf *bytes.Buffer)
- type AuthManager
- func (am *AuthManager) CookieName() string
- func (am *AuthManager) CookiePath() string
- func (am *AuthManager) CookiesHTTPSOnly() bool
- func (am *AuthManager) FetchHandler() AuthManagerFetchHandler
- func (am *AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error)
- func (am *AuthManager) LoginRedirect(ctx *Ctx) Result
- func (am *AuthManager) LoginRedirectHandler() AuthManagerRedirectHandler
- func (am *AuthManager) Logout(ctx *Ctx) error
- func (am *AuthManager) ParseSessionValueHandler() AuthManagerParseSessionValueHandler
- func (am *AuthManager) PersistHandler() AuthManagerPersistHandler
- func (am *AuthManager) PostLoginRedirect(ctx *Ctx) Result
- func (am *AuthManager) PostLoginRedirectHandler() AuthManagerRedirectHandler
- func (am *AuthManager) RemoveHandler() AuthManagerRemoveHandler
- func (am *AuthManager) SerializeSessionValueHandler() AuthManagerSerializeSessionValueHandler
- func (am *AuthManager) SessionTimeoutProvider() func(*Session) time.Time
- func (am *AuthManager) ValidateHandler() AuthManagerValidateHandler
- func (am *AuthManager) VerifySession(ctx *Ctx) (session *Session, err error)
- func (am *AuthManager) WithCookieHTTPSOnly(isHTTPSOnly bool) *AuthManager
- func (am *AuthManager) WithCookieName(paramName string) *AuthManager
- func (am *AuthManager) WithCookiePath(path string) *AuthManager
- func (am *AuthManager) WithFetchHandler(handler AuthManagerFetchHandler) *AuthManager
- func (am *AuthManager) WithLoginRedirectHandler(handler AuthManagerRedirectHandler) *AuthManager
- func (am *AuthManager) WithParseSessionValueHandler(handler AuthManagerParseSessionValueHandler) *AuthManager
- func (am *AuthManager) WithPersistHandler(handler AuthManagerPersistHandler) *AuthManager
- func (am *AuthManager) WithPostLoginRedirectHandler(handler AuthManagerRedirectHandler) *AuthManager
- func (am *AuthManager) WithRemoveHandler(handler AuthManagerRemoveHandler) *AuthManager
- func (am *AuthManager) WithSerializeSessionValueHandler(handler AuthManagerSerializeSessionValueHandler) *AuthManager
- func (am *AuthManager) WithSessionTimeoutProvider(timeoutProvider func(*Session) time.Time) *AuthManager
- func (am *AuthManager) WithValidateHandler(handler AuthManagerValidateHandler) *AuthManager
- type AuthManagerFetchHandler
- type AuthManagerMode
- type AuthManagerParseSessionValueHandler
- type AuthManagerPersistHandler
- type AuthManagerRedirectHandler
- type AuthManagerRemoveHandler
- type AuthManagerSerializeSessionValueHandler
- type AuthManagerSessionTimeoutProvider
- type AuthManagerValidateHandler
- type BufferPool
- type CachedStaticFile
- type CachedStaticFileServer
- func (csfs *CachedStaticFileServer) Action(r *Ctx) Result
- func (csfs *CachedStaticFileServer) AddHeader(key, value string)
- func (csfs *CachedStaticFileServer) AddRewriteRule(match string, action RewriteAction) error
- func (csfs *CachedStaticFileServer) Files() map[string]*CachedStaticFile
- func (csfs *CachedStaticFileServer) GetCachedFile(filepath string) (*CachedStaticFile, error)
- func (csfs *CachedStaticFileServer) Headers() http.Header
- func (csfs *CachedStaticFileServer) Log() *logger.Logger
- func (csfs *CachedStaticFileServer) RewriteRules() []RewriteRule
- func (csfs *CachedStaticFileServer) ServeFile(r *Ctx) Result
- func (csfs *CachedStaticFileServer) SetMiddleware(middlewares ...Middleware)
- func (csfs *CachedStaticFileServer) WithLogger(log *logger.Logger) *CachedStaticFileServer
- type CompressedResponseWriter
- func (crw *CompressedResponseWriter) Close() error
- func (crw *CompressedResponseWriter) ContentLength() int
- func (crw *CompressedResponseWriter) Flush() error
- func (crw *CompressedResponseWriter) Header() http.Header
- func (crw *CompressedResponseWriter) InnerResponse() http.ResponseWriter
- func (crw *CompressedResponseWriter) StatusCode() int
- func (crw *CompressedResponseWriter) Write(b []byte) (int, error)
- func (crw *CompressedResponseWriter) WriteHeader(code int)
- type Config
- func (c Config) BaseURLIsSecureScheme() bool
- func (c Config) GetAuthManagerMode(inherited ...string) AuthManagerMode
- func (c Config) GetAuthSecret(defaults ...[]byte) []byte
- func (c Config) GetBaseURL(defaults ...string) string
- func (c Config) GetBindAddr(defaults ...string) string
- func (c Config) GetCookieHTTPSOnly(defaults ...bool) bool
- func (c Config) GetCookieName(defaults ...string) string
- func (c Config) GetCookiePath(defaults ...string) string
- func (c Config) GetDefaultHeaders(inherited ...map[string]string) map[string]string
- func (c Config) GetHandleMethodNotAllowed(defaults ...bool) bool
- func (c Config) GetHandleOptions(defaults ...bool) bool
- func (c Config) GetIdleTimeout(defaults ...time.Duration) time.Duration
- func (c Config) GetMaxHeaderBytes(defaults ...int) int
- func (c Config) GetPort(defaults ...int32) int32
- func (c Config) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
- func (c Config) GetReadTimeout(defaults ...time.Duration) time.Duration
- func (c Config) GetRecoverPanics(defaults ...bool) bool
- func (c Config) GetRedirectTrailingSlash(defaults ...bool) bool
- func (c Config) GetSessionTimeout(defaults ...time.Duration) time.Duration
- func (c Config) GetSessionTimeoutIsAbsolute(defaults ...bool) bool
- func (c Config) GetShutdownGracePeriod(defaults ...time.Duration) time.Duration
- func (c Config) GetWriteTimeout(defaults ...time.Duration) time.Duration
- func (c Config) IsSecure() bool
- func (c Config) ListenTLS() bool
- type Controller
- type Ctx
- func (rc *Ctx) App() *App
- func (rc *Ctx) Auth() *AuthManager
- func (rc *Ctx) Context() context.Context
- func (rc *Ctx) DefaultResultProvider() ResultProvider
- func (rc *Ctx) Elapsed() time.Duration
- func (rc Ctx) End() time.Time
- 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) GetCookie(name string) *http.Cookie
- func (rc *Ctx) HeaderValue(key string) (value string, err error)
- func (rc *Ctx) ID() string
- func (rc *Ctx) JSON() JSONResultProvider
- func (rc *Ctx) Logger() *logger.Logger
- func (rc *Ctx) NoContent() NoContentResult
- func (rc *Ctx) Param(name string) (string, error)
- func (rc *Ctx) PostBody() ([]byte, error)
- func (rc *Ctx) PostBodyAsJSON(response interface{}) error
- func (rc *Ctx) PostBodyAsString() (string, error)
- func (rc *Ctx) PostBodyAsXML(response interface{}) error
- func (rc *Ctx) PostedFiles() ([]PostedFile, error)
- func (rc *Ctx) QueryValue(key string) (value string, err error)
- func (rc *Ctx) Raw(body []byte) *RawResult
- func (rc *Ctx) RawWithContentType(contentType string, body []byte) *RawResult
- func (rc *Ctx) Redirect(destination string) *RedirectResult
- func (rc *Ctx) RedirectWithMethod(method, destination string) *RedirectResult
- func (rc *Ctx) RedirectWithMethodf(method, format string, args ...interface{}) *RedirectResult
- func (rc *Ctx) Redirectf(format string, args ...interface{}) *RedirectResult
- func (rc *Ctx) Request() *http.Request
- func (rc *Ctx) Response() ResponseWriter
- func (rc *Ctx) Route() *Route
- func (rc *Ctx) RouteParam(key string) (output string, err error)
- func (rc *Ctx) RouteParams() RouteParameters
- func (rc *Ctx) Session() *Session
- func (rc Ctx) Start() time.Time
- func (rc *Ctx) State() State
- func (rc *Ctx) StateValue(key string) interface{}
- func (rc *Ctx) Static(filePath string) *StaticResult
- func (rc *Ctx) Text() TextResultProvider
- func (rc *Ctx) Tracer() Tracer
- func (rc *Ctx) View() *ViewCache
- func (rc *Ctx) WithApp(app *App) *Ctx
- func (rc *Ctx) WithAuth(authManager *AuthManager) *Ctx
- func (rc *Ctx) WithContext(context context.Context) *Ctx
- func (rc *Ctx) WithDefaultResultProvider(provider ResultProvider) *Ctx
- func (rc *Ctx) WithID(id string) *Ctx
- func (rc *Ctx) WithLogger(log *logger.Logger) *Ctx
- func (rc *Ctx) WithRequest(req *http.Request) *Ctx
- func (rc *Ctx) WithResponse(res ResponseWriter) *Ctx
- func (rc *Ctx) WithRoute(route *Route) *Ctx
- func (rc *Ctx) WithRouteParams(params RouteParameters) *Ctx
- func (rc *Ctx) WithSession(session *Session) *Ctx
- func (rc *Ctx) WithState(state State) *Ctx
- func (rc *Ctx) WithStateValue(key string, value interface{}) *Ctx
- func (rc *Ctx) WithTracer(tracer Tracer) *Ctx
- func (rc *Ctx) WithViews(vc *ViewCache) *Ctx
- func (rc *Ctx) WriteCookie(cookie *http.Cookie)
- func (rc *Ctx) WriteNewCookie(name string, value string, expires time.Time, path string, secure bool)
- func (rc *Ctx) XML() XMLResultProvider
- type Fileserver
- type HSTSConfig
- type HTTPSUpgrader
- func (hu *HTTPSUpgrader) Logger() *logger.Logger
- func (hu *HTTPSUpgrader) ServeHTTP(rw http.ResponseWriter, req *http.Request)
- func (hu *HTTPSUpgrader) TargetPort() int32
- func (hu *HTTPSUpgrader) WithLogger(log *logger.Logger) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithTargetPort(targetPort int32) *HTTPSUpgrader
- type HTTPSUpgraderConfig
- type Handler
- type Healthz
- func (hz *Healthz) BindAddr() string
- func (hz *Healthz) Config() *HealthzConfig
- func (hz *Healthz) DefaultHeaders() map[string]string
- func (hz *Healthz) FailureThreshold() int
- func (hz *Healthz) GracePeriod() time.Duration
- func (hz *Healthz) Hosted() graceful.Graceful
- func (hz *Healthz) IdleTimeout() time.Duration
- func (hz *Healthz) IsRunning() bool
- func (hz *Healthz) Logger() *logger.Logger
- func (hz *Healthz) MaxHeaderBytes() int
- func (hz *Healthz) NotifyStarted() <-chan struct{}
- func (hz *Healthz) NotifyStopped() <-chan struct{}
- func (hz *Healthz) NotifyStopping() <-chan struct{}
- func (hz *Healthz) ReadHeaderTimeout() time.Duration
- func (hz *Healthz) ReadTimeout() time.Duration
- func (hz *Healthz) RecoverPanics() bool
- func (hz *Healthz) Self() *App
- func (hz *Healthz) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (hz *Healthz) Start() error
- func (hz *Healthz) Stop() error
- func (hz *Healthz) WithBindAddr(bindAddr string) *Healthz
- func (hz *Healthz) WithConfig(cfg *HealthzConfig) *Healthz
- func (hz *Healthz) WithDefaultHeader(key, value string) *Healthz
- func (hz *Healthz) WithFailureThreshold(failureThreshold int) *Healthz
- func (hz *Healthz) WithGracePeriod(gracePeriod time.Duration) *Healthz
- func (hz *Healthz) WithIdleTimeout(timeout time.Duration) *Healthz
- func (hz *Healthz) WithLogger(log *logger.Logger) *Healthz
- func (hz *Healthz) WithMaxHeaderBytes(byteCount int) *Healthz
- func (hz *Healthz) WithReadHeaderTimeout(timeout time.Duration) *Healthz
- func (hz *Healthz) WithReadTimeout(timeout time.Duration) *Healthz
- func (hz *Healthz) WithRecoverPanics(value bool) *Healthz
- func (hz *Healthz) WithWriteTimeout(timeout time.Duration) *Healthz
- func (hz *Healthz) WriteTimeout() time.Duration
- type HealthzConfig
- func (hzc HealthzConfig) GetBindAddr(defaults ...string) string
- func (hzc HealthzConfig) GetFailureThreshold(defaults ...int) int
- func (hzc HealthzConfig) GetGracePeriod(defaults ...time.Duration) time.Duration
- func (hzc HealthzConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration
- func (hzc HealthzConfig) GetMaxHeaderBytes(defaults ...int) int
- func (hzc HealthzConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
- func (hzc HealthzConfig) GetReadTimeout(defaults ...time.Duration) time.Duration
- func (hzc HealthzConfig) GetRecoverPanics(defaults ...bool) bool
- func (hzc HealthzConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration
- type HealthzHostable
- type JSONResult
- type JSONResultProvider
- func (jrp JSONResultProvider) BadRequest(err error) 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) Claims(session *Session) *jwt.StandardClaims
- func (jwtm JWTManager) FromClaims(claims *jwt.StandardClaims) *Session
- func (jwtm JWTManager) KeyFunc(token *jwt.Token) (interface{}, error)
- func (jwtm JWTManager) ParseSessionValueHandler(_ context.Context, sessionValue string, _ State) (*Session, error)
- func (jwtm JWTManager) SerializeSessionValueHandler(_ context.Context, session *Session, _ State) (output string, err error)
- type LocalSessionCache
- func (lsc *LocalSessionCache) FetchHandler(_ context.Context, sessionID string, _ State) (*Session, error)
- func (lsc *LocalSessionCache) Get(sessionID string) *Session
- func (lsc *LocalSessionCache) PersistHandler(_ context.Context, session *Session, _ State) error
- func (lsc *LocalSessionCache) Remove(sessionID string)
- func (lsc *LocalSessionCache) RemoveHandler(_ context.Context, sessionID string, _ State) error
- func (lsc *LocalSessionCache) Upsert(session *Session)
- type Middleware
- type MockRequestBuilder
- func (mrb *MockRequestBuilder) Bytes() ([]byte, error)
- func (mrb *MockRequestBuilder) BytesWithMeta() ([]byte, *ResponseMeta, error)
- func (mrb *MockRequestBuilder) CreateCtx(p RouteParameters) (*Ctx, error)
- func (mrb *MockRequestBuilder) Delete(pathFormat string, args ...interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) Err() error
- func (mrb *MockRequestBuilder) Execute() error
- func (mrb *MockRequestBuilder) ExecuteWithMeta() (*ResponseMeta, error)
- func (mrb *MockRequestBuilder) Get(pathFormat string, args ...interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) GetStateValue(key string) interface{}
- func (mrb *MockRequestBuilder) JSON(object interface{}) error
- func (mrb *MockRequestBuilder) JSONWithMeta(object interface{}) (*ResponseMeta, error)
- func (mrb *MockRequestBuilder) LookupRoute() (route *Route, params RouteParameters)
- func (mrb *MockRequestBuilder) Patch(pathFormat string, args ...interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) Post(pathFormat string, args ...interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) Put(pathFormat string, args ...interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) Request() (*http.Request, error)
- func (mrb *MockRequestBuilder) Response() (res *http.Response, err error)
- func (mrb *MockRequestBuilder) State() State
- func (mrb *MockRequestBuilder) WithBasicAuth(username, password string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithCookie(cookie *http.Cookie) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithCookieValue(name, value string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithErr(err error) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithFormValue(key, value string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithHeader(key, value string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithPathf(pathFormat string, args ...interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithPostBody(postBody []byte) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithPostBodyAsJSON(object interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithPostedFile(postedFile PostedFile) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithQueryString(key, value string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithStateValue(key string, value interface{}) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithVerb(verb string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) XML(object interface{}) error
- func (mrb *MockRequestBuilder) XMLWithMeta(object interface{}) (*ResponseMeta, error)
- type NoContentResult
- type PanicAction
- type PanicHandler
- type PostedFile
- type RawResponseWriter
- func (rw *RawResponseWriter) Close() error
- func (rw *RawResponseWriter) ContentLength() int
- func (rw *RawResponseWriter) Header() http.Header
- func (rw *RawResponseWriter) InnerResponse() http.ResponseWriter
- func (rw *RawResponseWriter) StatusCode() int
- func (rw *RawResponseWriter) Write(b []byte) (int, error)
- func (rw *RawResponseWriter) WriteHeader(code int)
- type RawResult
- type RedirectResult
- type RequestMeta
- type ResponseMeta
- type ResponseWriter
- type Result
- type ResultPreRender
- type ResultProvider
- type ResultRenderComplete
- type RewriteAction
- type RewriteRule
- type Route
- type RouteParameters
- type Session
- type SessionLockPolicy
- 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) Headers() http.Header
- func (sc *StaticFileServer) Log() *logger.Logger
- func (sc *StaticFileServer) RewriteRules() []RewriteRule
- func (sc *StaticFileServer) ServeFile(r *Ctx) Result
- func (sc *StaticFileServer) SetMiddleware(middlewares ...Middleware)
- func (sc *StaticFileServer) WithLogger(log *logger.Logger) *StaticFileServer
- type StaticResult
- type StatusViewModel
- type SyncState
- type TCPKeepAliveListener
- type TLSConfig
- func (tc TLSConfig) GetCAPaths(defaults ...[]string) []string
- func (tc TLSConfig) GetCert(defaults ...[]byte) []byte
- func (tc TLSConfig) GetCertPath(defaults ...string) string
- func (tc TLSConfig) GetConfig() (*tls.Config, error)
- func (tc TLSConfig) GetKey(defaults ...[]byte) []byte
- func (tc TLSConfig) GetKeyPath(defaults ...string) string
- func (tc TLSConfig) HasKeyPair() bool
- 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 Values
- type ViewCache
- func (vc *ViewCache) AddLiterals(views ...string)
- func (vc *ViewCache) AddPaths(paths ...string)
- func (vc *ViewCache) BadRequest(err error) Result
- func (vc *ViewCache) BadRequestTemplateName() string
- func (vc *ViewCache) Cached() bool
- func (vc *ViewCache) FuncMap() template.FuncMap
- func (vc *ViewCache) Initialize() error
- func (vc *ViewCache) Initialized() bool
- func (vc *ViewCache) InternalError(err error) Result
- func (vc *ViewCache) InternalErrorTemplateName() string
- func (vc *ViewCache) Literals() []string
- func (vc *ViewCache) Lookup(name string) (*template.Template, error)
- func (vc *ViewCache) NotAuthorized() Result
- func (vc *ViewCache) NotAuthorizedTemplateName() string
- func (vc *ViewCache) NotFound() Result
- func (vc *ViewCache) NotFoundTemplateName() string
- func (vc *ViewCache) Parse() (views *template.Template, err error)
- func (vc *ViewCache) Paths() []string
- func (vc *ViewCache) SetLiterals(viewLiterals ...string)
- func (vc *ViewCache) SetPaths(paths ...string)
- func (vc *ViewCache) SetTemplates(viewCache *template.Template)
- func (vc *ViewCache) Status(statusCode int, response ...interface{}) Result
- func (vc *ViewCache) StatusTemplateName() string
- func (vc *ViewCache) Templates() (*template.Template, error)
- func (vc *ViewCache) View(viewName string, viewModel interface{}) Result
- func (vc *ViewCache) WithBadRequestTemplateName(templateName string) *ViewCache
- func (vc *ViewCache) WithCached(cached bool) *ViewCache
- func (vc *ViewCache) WithInternalErrorTemplateName(templateName string) *ViewCache
- func (vc *ViewCache) WithNotAuthorizedTemplateName(templateName string) *ViewCache
- func (vc *ViewCache) WithNotFoundTemplateName(templateName string) *ViewCache
- func (vc *ViewCache) WithStatusTemplateName(templateName string) *ViewCache
- type ViewCacheConfig
- func (vcc ViewCacheConfig) GetBadRequestTemplateName(defaults ...string) string
- func (vcc ViewCacheConfig) GetBufferPoolSize(defaults ...int) int
- func (vcc ViewCacheConfig) GetCached(defaults ...bool) bool
- func (vcc ViewCacheConfig) GetInternalErrorTemplateName(defaults ...string) string
- func (vcc ViewCacheConfig) GetNotAuthorizedTemplateName(defaults ...string) string
- func (vcc ViewCacheConfig) GetNotFoundTemplateName(defaults ...string) string
- func (vcc ViewCacheConfig) GetPaths(defaults ...[]string) []string
- func (vcc ViewCacheConfig) GetStatusTemplateName(defaults ...string) string
- type ViewModel
- type ViewResult
- 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 ( // AppStart fires when the app is starting. AppStart logger.Flag = "web.app.start" // AppStartComplete fires after the app has started. AppStartComplete logger.Flag = "web.app.start.complete" // AppExit fires when an app exits. AppExit logger.Flag = "web.app.exit" )
const ( // HealthzStart is a logger event. HealthzStart logger.Flag = "web.healthz.start" // HealthzStartComplete is a logger event. HealthzStartComplete logger.Flag = "web.healthz.start.complete" // HealthzExit is a logger event. HealthzExit logger.Flag = "web.healthz.exit" )
const ( // HTTPSUpgraderStart is a logger event. HTTPSUpgraderStart logger.Flag = "web.upgrader.start" // HTTPSUpgraderStartComplete is a logger event. HTTPSUpgraderStartComplete logger.Flag = "web.upgrader.start.complete" // HTTPSUpgraderExit is a logger event. HTTPSUpgraderExit logger.Flag = "web.upgrader.exit" )
const ( // PackageName is the full name of this package. PackageName = "github.com/blend/go-sdk/web" // HeaderAllow is a common header. HeaderAllow = "Allow" // 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)$` // HeaderAcceptEncoding is the "Accept-Encoding" header. // It indicates what types of encodings the request will accept responses as. // It typically enables or disables compressed (gzipped) responses. HeaderAcceptEncoding = "Accept-Encoding" // HeaderSetCookie is the header that sets cookies in a response. HeaderSetCookie = "Set-Cookie" // HeaderCookie is the request cookie header. HeaderCookie = "Cookie" // HeaderDate is the "Date" header. // It provides a timestamp the response was generated at. // It is typically used by client cache control to invalidate expired items. HeaderDate = "Date" // HeaderCacheControl is the "Cache-Control" header. // It indicates if and how clients should cache responses. // Typical values for this include "no-cache", "max-age", "min-fresh", and "max-stale" variants. HeaderCacheControl = "Cache-Control" // HeaderConnection is the "Connection" header. // It is used to indicate if the connection should remain open by the server // after the final response bytes are sent. // This allows the connection to be re-used, helping mitigate connection negotiation // penalites in making requests. HeaderConnection = "Connection" // HeaderContentEncoding is the "Content-Encoding" header. // It is used to indicate what the response encoding is. // Typical values are "gzip", "deflate", "compress", "br", and "identity" indicating no compression. HeaderContentEncoding = "Content-Encoding" // HeaderContentLength is the "Content-Length" header. // If provided, it specifies the size of the request or response. HeaderContentLength = "Content-Length" // HeaderContentType is the "Content-Type" header. // It specifies the MIME-type of the request or response. HeaderContentType = "Content-Type" // HeaderServer is the "Server" header. // It is an informational header to tell the client what server software was used. HeaderServer = "Server" // HeaderUserAgent is the user agent header. HeaderUserAgent = "User-Agent" // HeaderVary is the "Vary" header. // It is used to indicate what fields should be used by the client as cache keys. HeaderVary = "Vary" // HeaderXServedBy is the "X-Served-By" header. // It is an informational header that indicates what software was used to generate the response. HeaderXServedBy = "X-Served-By" // HeaderXFrameOptions is the "X-Frame-Options" header. // It indicates if a browser is allowed to render the response in a <frame> element or not. HeaderXFrameOptions = "X-Frame-Options" // HeaderXXSSProtection is the "X-Xss-Protection" header. // It is a feature of internet explorer, and indicates if the browser should allow // requests across domain boundaries. HeaderXXSSProtection = "X-Xss-Protection" // HeaderXContentTypeOptions is the "X-Content-Type-Options" header. HeaderXContentTypeOptions = "X-Content-Type-Options" // HeaderStrictTransportSecurity is the hsts header. HeaderStrictTransportSecurity = "Strict-Transport-Security" // ContentTypeApplicationJSON is a content type for JSON responses. // We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding. ContentTypeApplicationJSON = "application/json; charset=UTF-8" // ContentTypeHTML is a content type for html responses. // We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding. ContentTypeHTML = "text/html; charset=utf-8" //ContentTypeXML is a content type for XML responses. // We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding. ContentTypeXML = "text/xml; charset=utf-8" // ContentTypeText is a content type for text responses. // We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding. ContentTypeText = "text/plain; charset=utf-8" // ConnectionKeepAlive is a value for the "Connection" header and // indicates the server should keep the tcp connection open // after the last byte of the response is sent. ConnectionKeepAlive = "keep-alive" // ContentEncodingIdentity is the identity (uncompressed) content encoding. ContentEncodingIdentity = "identity" // ContentEncodingGZIP is the gzip (compressed) content encoding. ContentEncodingGZIP = "gzip" )
const ( // SchemeHTTP is a protocol scheme. SchemeHTTP = "http" // SchemeHTTPS is a protocol scheme. SchemeHTTPS = "https" // SchemeSPDY is a protocol scheme. SchemeSPDY = "spdy" )
const ( // MethodGet is an http verb. MethodGet = "GET" // MethodPost is an http verb. MethodPost = "POST" // MethodPut is an http verb. MethodPut = "PUT" // MethodDelete is an http verb. MethodDelete = "DELETE" // MethodConnect is an http verb. MethodConnect = "CONNECT" // MethodOptions is an http verb. MethodOptions = "OPTIONS" )
const ( // HSTSMaxAgeFormat is the format string for a max age token. HSTSMaxAgeFormat = "max-age=%d" // HSTSIncludeSubDomains is a header value token. HSTSIncludeSubDomains = "includeSubDomains" // HSTSPreload is a header value token. HSTSPreload = "preload" )
const ( // EnvironmentVariableBindAddr is an env var that determines (if set) what the bind address should be. EnvironmentVariableBindAddr = "BIND_ADDR" // EnvironmentVariableHealthzBindAddr is an env var that determines (if set) what the healthz sidecar bind address should be. EnvironmentVariableHealthzBindAddr = "HEALTHZ_BIND_ADDR" // EnvironmentVariableUpgraderBindAddr is an env var that determines (if set) what the bind address should be. EnvironmentVariableUpgraderBindAddr = "UPGRADER_BIND_ADDR" // EnvironmentVariablePort is an env var that determines what the default bind address port segment returns. EnvironmentVariablePort = "PORT" // EnvironmentVariableHealthzPort is an env var that determines what the default healthz bind address port segment returns. EnvironmentVariableHealthzPort = "HEALTHZ_PORT" // EnvironmentVariableUpgraderPort is an env var that determines what the default bind address port segment returns. EnvironmentVariableUpgraderPort = "UPGRADER_PORT" // EnvironmentVariableTLSCert is an env var that contains the TLS cert. EnvironmentVariableTLSCert = "TLS_CERT" // EnvironmentVariableTLSKey is an env var that contains the TLS key. EnvironmentVariableTLSKey = "TLS_KEY" // EnvironmentVariableTLSCertFile is an env var that contains the file path to the TLS cert. EnvironmentVariableTLSCertFile = "TLS_CERT_FILE" // EnvironmentVariableTLSKeyFile is an env var that contains the file path to the TLS key. EnvironmentVariableTLSKeyFile = "TLS_KEY_FILE" )
Environment Variables
const ( // DefaultBindAddr is the default bind address. DefaultBindAddr = ":8080" // DefaultHealthzBindAddr is the default healthz bind address. DefaultHealthzBindAddr = ":8081" // DefaultIntegrationBindAddr is a bind address used for integration testing. DefaultIntegrationBindAddr = "127.0.0.1:0" // DefaultRedirectTrailingSlash is the default if we should redirect for missing trailing slashes. DefaultRedirectTrailingSlash = true // DefaultHandleOptions is a default. DefaultHandleOptions = false // DefaultHandleMethodNotAllowed is a default. DefaultHandleMethodNotAllowed = false // DefaultRecoverPanics returns if we should recover panics by default. DefaultRecoverPanics = true // DefaultHSTS is the default for if hsts is enabled. DefaultHSTS = true // DefaultHSTSMaxAgeSeconds is the default hsts max age seconds. DefaultHSTSMaxAgeSeconds = 31536000 // DefaultHSTSIncludeSubDomains is a default. DefaultHSTSIncludeSubDomains = true // DefaultHSTSPreload is a default. DefaultHSTSPreload = true // DefaultMaxHeaderBytes is a default that is unset. DefaultMaxHeaderBytes = 0 // DefaultReadTimeout is a default. DefaultReadTimeout = 5 * time.Second // 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 = "/" // 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 // DefaultShutdownGracePeriod is the default shutdown grace period. DefaultShutdownGracePeriod = 30 * time.Second // DefaultHealthzFailureThreshold is the default healthz failure threshold. DefaultHealthzFailureThreshold = 3 // DefaultBufferPoolSize is the default buffer pool size. DefaultViewBufferPoolSize = 256 )
Defaults
const ( // PostBodySize is the maximum post body size we will typically consume. PostBodySize = int64(1 << 26) //64mb // PostBodySizeMax is the absolute maximum file size the server can handle. PostBodySizeMax = int64(1 << 32) //enormous. )
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 ( TestTLSCert = `` /* 1094-byte string literal not displayed */ TestTLSKey = `` /* 1674-byte string literal not displayed */ )
test keys
const ( // ErrSessionIDEmpty is thrown if a session id is empty. ErrSessionIDEmpty exception.Class = "auth session id is empty" // ErrSecureSessionIDEmpty is an error that is thrown if a given secure session id is invalid. ErrSecureSessionIDEmpty exception.Class = "auth secure session id is empty" // ErrUnsetViewTemplate is an error that is thrown if a given secure session id is invalid. ErrUnsetViewTemplate exception.Class = "view result template is unset" // ErrParameterMissing is an error on request validation. ErrParameterMissing exception.Class = "parameter is missing" )
const ( // ListenerHealthz is the uid of the healthz logger listeners. ListenerHealthz = "healthz" // ErrHealthzAppUnset is a common error. ErrHealthzAppUnset exception.Class = "healthz app unset" )
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 ( // DefaultTCPKeepAliveListenerPeriod is the default keep alive period for the tcp listener. DefaultTCPKeepAliveListenerPeriod = 3 * time.Minute )
const ( // ErrJWTNonstandardClaims can be returned by the jwt manager keyfunc. ErrJWTNonstandardClaims = exception.Class("jwt; invalid claims object; should be standard claims") )
Variables ¶
var DefaultHeaders = map[string]string{ HeaderServer: PackageName, HeaderXServedBy: PackageName, }
DefaultHeaders are the default headers added by go-web.
var GracefulShutdown = graceful.Shutdown
GracefulShutdown shuts an app down gracefull. It is an alias to graceful.Shutdown
var StartWithGracefulShutdown = graceful.Shutdown
StartWithGracefulShutdown shuts an app down gracefull. It is an alias to graceful.Shutdown
Functions ¶
func Base64URLDecode ¶
Base64URLDecode decodes a base64 string.
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 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 Int64Value ¶
Int64Value parses a value as an int64. If the input error is set it short circuits.
func IsErrSessionInvalid ¶
IsErrSessionInvalid returns if an error is a session invalid error.
func NewAppEventListener ¶
NewAppEventListener returns a new app start event listener.
func NewCtxID ¶ added in v0.3.2
func NewCtxID() string
NewCtxID returns a pseudo-unique key for a context.
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(defaultResult interface{}, result ...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.
Types ¶
type Action ¶
Action is the function signature for controller actions.
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.
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 {
// contains filtered or unexported fields
}
App is the server for the app.
func MustNewFromEnv ¶
func MustNewFromEnv() *App
MustNewFromEnv returns a new app with a config set from environment variabales, and it will panic if there is an error.
func NewFromConfig ¶
NewFromConfig returns a new app from a given config.
func NewFromEnv ¶
NewFromEnv returns a new app from the environment.
func (*App) CreateServer ¶
CreateServer returns the basic http.Server for the app.
func (*App) DELETE ¶
func (a *App) DELETE(path string, action Action, middleware ...Middleware)
DELETE registers a DELETE request handler.
func (*App) DefaultHeaders ¶
DefaultHeaders returns the default headers.
func (*App) DefaultMiddleware ¶
func (a *App) DefaultMiddleware() []Middleware
DefaultMiddleware returns the default middleware.
func (*App) DefaultResultProvider ¶
func (a *App) DefaultResultProvider() ResultProvider
DefaultResultProvider returns the app wide default result provider.
func (*App) GET ¶
func (a *App) GET(path string, action Action, middleware ...Middleware)
GET registers a GET request handler.
Routes should be registered in the form:
app.GET("/myroute", myAction, myMiddleware...)
It is important to note that routes are registered in order and cannot have any wildcards inside the routes.
func (*App) HEAD ¶
func (a *App) HEAD(path string, action Action, middleware ...Middleware)
HEAD registers a HEAD request handler.
func (*App) HandleMethodNotAllowed ¶
HandleMethodNotAllowed returns if we should handle unhandled verbs.
func (*App) HandleOptions ¶
HandleOptions returns if we should handle OPTIONS requests.
func (*App) IdleTimeout ¶
IdleTimeout is the time before we close a connection.
func (*App) Listener ¶
func (a *App) Listener() *net.TCPListener
Listener returns the underlying listener.
func (*App) Lookup ¶
func (a *App) Lookup(method, path string) (route *Route, params RouteParameters, slashRedirect bool)
Lookup finds the route data for a given method and path.
func (*App) MaxHeaderBytes ¶
MaxHeaderBytes returns the app max header bytes.
func (*App) MethodNotAllowedHandler ¶
MethodNotAllowedHandler returns the method not allowed handler.
func (*App) Mock ¶
func (a *App) Mock() *MockRequestBuilder
Mock returns a request bulider to facilitate mocking requests against the app without having to start it and bind it to a port.
An example mock request that hits an already registered "GET" route at "/foo":
assert.Nil(app.Mock().Get("/").Execute())
This will assert that the request completes successfully, but does not return the response.
func (*App) NotFoundHandler ¶
NotFoundHandler returns the not found handler.
func (*App) NotifyStarted ¶
func (a *App) NotifyStarted() <-chan struct{}
NotifyStarted returns the notify started chan.
func (*App) NotifyStopped ¶ added in v0.3.1
func (a *App) NotifyStopped() <-chan struct{}
NotifyStopped returns the notify stopped chan.
func (*App) OPTIONS ¶
func (a *App) OPTIONS(path string, action Action, middleware ...Middleware)
OPTIONS registers a OPTIONS request handler.
func (*App) PATCH ¶
func (a *App) PATCH(path string, action Action, middleware ...Middleware)
PATCH registers a PATCH request handler.
func (*App) POST ¶
func (a *App) POST(path string, action Action, middleware ...Middleware)
POST registers a POST request actions.
func (*App) PUT ¶
func (a *App) PUT(path string, action Action, middleware ...Middleware)
PUT registers a PUT request handler.
func (*App) PanicAction ¶
func (a *App) PanicAction() PanicAction
PanicAction returns the panic action.
func (*App) ReadHeaderTimeout ¶
ReadHeaderTimeout returns the read header timeout for the server.
func (*App) ReadTimeout ¶
ReadTimeout returns the read timeout for the server.
func (*App) RecoverPanics ¶
RecoverPanics returns if the app recovers panics.
func (*App) RedirectTrailingSlash ¶
RedirectTrailingSlash returns if we should redirect missing trailing slashes to the correct route.
func (*App) Register ¶
func (a *App) Register(c Controller)
Register registers a controller with the app's router.
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 ¶
ServeStatic serves files from the given file system root. 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 ¶
ServeStaticCached serves files from the given file system root. 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) SetStaticMiddleware ¶
func (a *App) SetStaticMiddleware(route string, middlewares ...Middleware) error
SetStaticMiddleware adds static middleware for a given route.
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) SetTLSClientCertPool ¶
SetTLSClientCertPool set the client cert pool from a given set of pems.
func (*App) ShutdownGracePeriod ¶
ShutdownGracePeriod is the grace period on shutdown.
func (*App) StartupTasks ¶
StartupTasks runs common startup tasks.
func (*App) StateValue ¶
StateValue gets app state element by key.
func (*App) WithBaseURL ¶
WithBaseURL sets the `BaseURL` field and returns a reference to the app for building apps with a fluent api.
func (*App) WithBindAddr ¶
WithBindAddr sets the address the app listens on, and returns a reference to the app.
func (*App) WithConfig ¶
WithConfig sets the config and applies the config's setting.
func (*App) WithControllers ¶
func (a *App) WithControllers(controllers ...Controller) *App
WithControllers registers given controllers and returns a reference to the app.
func (*App) WithDefaultHeader ¶
WithDefaultHeader adds a default header.
func (*App) WithDefaultHeaders ¶
WithDefaultHeaders sets the default headers
func (*App) WithDefaultMiddleware ¶
func (a *App) WithDefaultMiddleware(middleware ...Middleware) *App
WithDefaultMiddleware sets the application wide default middleware.
func (*App) WithDefaultMiddlewares ¶
func (a *App) WithDefaultMiddlewares(middleware ...Middleware) *App
WithDefaultMiddlewares sets the application wide default middleware.
func (*App) WithDefaultResultProvider ¶
func (a *App) WithDefaultResultProvider(drp ResultProvider) *App
WithDefaultResultProvider sets the default result provider.
func (*App) WithHSTS ¶
func (a *App) WithHSTS(hsts *HSTSConfig) *App
WithHSTS enables or disables issuing the strict transport security header.
func (*App) WithHandleMethodNotAllowed ¶
WithHandleMethodNotAllowed sets if we should handlem ethod not allowed.
func (*App) WithHandleOptions ¶
WithHandleOptions returns if we should handle OPTIONS requests.
func (*App) WithHandler ¶
WithHandler sets the handler.
func (*App) WithIdleTimeout ¶
WithIdleTimeout sets the idle timeout.
func (*App) WithLogger ¶
WithLogger sets the app logger agent and returns a reference to the app. It also sets underlying loggers in any child resources like providers and the auth manager.
func (*App) WithMaxHeaderBytes ¶
WithMaxHeaderBytes sets the max header bytes value and returns a reference.
func (*App) WithMethodNotAllowedHandler ¶
WithMethodNotAllowedHandler sets the not allowed handler.
func (*App) WithNotFoundHandler ¶
WithNotFoundHandler sets the not found handler.
func (*App) WithPanicAction ¶
func (a *App) WithPanicAction(action PanicAction) *App
WithPanicAction sets the panic action.
func (*App) WithPort ¶
WithPort sets the port for the bind address of the app, and returns a reference to the app.
func (*App) WithReadHeaderTimeout ¶
WithReadHeaderTimeout returns the read header timeout for the server.
func (*App) WithReadTimeout ¶
WithReadTimeout sets the read timeout for the server and returns a reference to the app for building apps with a fluent api.
func (*App) WithRecoverPanics ¶
WithRecoverPanics sets if the app should recover panics.
func (*App) WithRedirectTrailingSlash ¶
WithRedirectTrailingSlash sets if we should redirect missing trailing slashes.
func (*App) WithServer ¶
WithServer sets the server.
func (*App) WithShutdownGracePeriod ¶
WithShutdownGracePeriod sets the shutdown grace period.
func (*App) WithStateValue ¶
WithStateValue sets app state and returns a reference to the app for building apps with a fluent api.
func (*App) WithTLSClientCertVerification ¶
func (a *App) WithTLSClientCertVerification(verification tls.ClientAuthType) *App
WithTLSClientCertVerification sets the verification level for client certs.
func (*App) WithTLSConfig ¶
WithTLSConfig sets the tls config for the app.
func (*App) WithWriteTimeout ¶
WithWriteTimeout sets the write timeout for the server and returns a reference to the app for building apps with a fluent api.
func (*App) WriteTimeout ¶
WriteTimeout returns the write timeout for the server.
type AppEvent ¶
AppEvent is an event.
func NewAppEvent ¶
NewAppEvent creates a new app start event.
func (AppEvent) Upgrader ¶
func (ae AppEvent) Upgrader() *HTTPSUpgrader
Upgrader returns the https upgrader reference.
func (*AppEvent) WithAnnotation ¶
WithAnnotation adds an annotation to the event.
func (*AppEvent) WithElapsed ¶
WithElapsed sets the elapsed time on the event.
func (*AppEvent) WithHeadings ¶
WithHeadings sets the headings.
func (*AppEvent) WithHealthz ¶
WithHealthz sets the event hz reference.
func (*AppEvent) WithTimestamp ¶
WithTimestamp sets the timestamp.
func (*AppEvent) WithUpgrader ¶
func (ae *AppEvent) WithUpgrader(upgrader *HTTPSUpgrader) *AppEvent
WithUpgrader sets the event hz reference.
type AuthManager ¶
type AuthManager struct {
// contains filtered or unexported fields
}
AuthManager is a manager for sessions.
func NewAuthManagerFromConfig ¶
func NewAuthManagerFromConfig(cfg *Config) (manager *AuthManager)
NewAuthManagerFromConfig returns a new auth manager from a given config.
func NewJWTAuthManager ¶
func NewJWTAuthManager(key []byte) *AuthManager
NewJWTAuthManager returns a new jwt session manager. It issues JWT tokens to identify users.
func NewLocalAuthManager ¶
func NewLocalAuthManager() *AuthManager
NewLocalAuthManager returns a new locally cached session manager. It saves sessions to a local store.
func NewServerAuthManager ¶
func NewServerAuthManager() *AuthManager
NewServerAuthManager returns a new server auth manager. You should set the `FetchHandler`, the `PersistHandler` and the `RemoveHandler`.
func (*AuthManager) CookieName ¶
func (am *AuthManager) CookieName() string
CookieName returns the session param name.
func (*AuthManager) CookiePath ¶
func (am *AuthManager) CookiePath() string
CookiePath returns the session param path.
func (*AuthManager) CookiesHTTPSOnly ¶
func (am *AuthManager) CookiesHTTPSOnly() bool
CookiesHTTPSOnly returns if the cookie is for only https connections.
func (*AuthManager) FetchHandler ¶
func (am *AuthManager) FetchHandler() AuthManagerFetchHandler
FetchHandler returns the fetch handler. It is used in `VerifySession` to satisfy session cache misses.
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) LoginRedirectHandler ¶
func (am *AuthManager) LoginRedirectHandler() AuthManagerRedirectHandler
LoginRedirectHandler returns the login redirect handler.
func (*AuthManager) Logout ¶
func (am *AuthManager) Logout(ctx *Ctx) error
Logout unauthenticates a session.
func (*AuthManager) ParseSessionValueHandler ¶
func (am *AuthManager) ParseSessionValueHandler() AuthManagerParseSessionValueHandler
ParseSessionValueHandler returns the parse session value handler.
func (*AuthManager) PersistHandler ¶
func (am *AuthManager) PersistHandler() AuthManagerPersistHandler
PersistHandler returns the persist handler.
func (*AuthManager) PostLoginRedirect ¶
func (am *AuthManager) PostLoginRedirect(ctx *Ctx) Result
PostLoginRedirect returns a redirect result for when auth fails and you need to send the user to a login page.
func (*AuthManager) PostLoginRedirectHandler ¶
func (am *AuthManager) PostLoginRedirectHandler() AuthManagerRedirectHandler
PostLoginRedirectHandler returns the redirect handler for login complete.
func (*AuthManager) RemoveHandler ¶
func (am *AuthManager) RemoveHandler() AuthManagerRemoveHandler
RemoveHandler returns the remove handler. It is used in validate session if the session is found to be invalid.
func (*AuthManager) SerializeSessionValueHandler ¶
func (am *AuthManager) SerializeSessionValueHandler() AuthManagerSerializeSessionValueHandler
SerializeSessionValueHandler returns the serialize session value handler.
func (*AuthManager) SessionTimeoutProvider ¶
func (am *AuthManager) SessionTimeoutProvider() func(*Session) time.Time
SessionTimeoutProvider returns the session timeout provider.
func (*AuthManager) ValidateHandler ¶
func (am *AuthManager) ValidateHandler() AuthManagerValidateHandler
ValidateHandler returns the validate handler.
func (*AuthManager) VerifySession ¶
func (am *AuthManager) VerifySession(ctx *Ctx) (session *Session, err error)
VerifySession checks a sessionID to see if it's valid. It also handles updating a rolling expiry.
func (*AuthManager) WithCookieHTTPSOnly ¶
func (am *AuthManager) WithCookieHTTPSOnly(isHTTPSOnly bool) *AuthManager
WithCookieHTTPSOnly sets if we should issue cookies with the HTTPS flag on.
func (*AuthManager) WithCookieName ¶
func (am *AuthManager) WithCookieName(paramName string) *AuthManager
WithCookieName sets the cookie name.
func (*AuthManager) WithCookiePath ¶
func (am *AuthManager) WithCookiePath(path string) *AuthManager
WithCookiePath sets the cookie path.
func (*AuthManager) WithFetchHandler ¶
func (am *AuthManager) WithFetchHandler(handler AuthManagerFetchHandler) *AuthManager
WithFetchHandler sets the fetch handler.
func (*AuthManager) WithLoginRedirectHandler ¶
func (am *AuthManager) WithLoginRedirectHandler(handler AuthManagerRedirectHandler) *AuthManager
WithLoginRedirectHandler sets the login redirect handler.
func (*AuthManager) WithParseSessionValueHandler ¶
func (am *AuthManager) WithParseSessionValueHandler(handler AuthManagerParseSessionValueHandler) *AuthManager
WithParseSessionValueHandler sets the parse session value handler.
func (*AuthManager) WithPersistHandler ¶
func (am *AuthManager) WithPersistHandler(handler AuthManagerPersistHandler) *AuthManager
WithPersistHandler sets the persist handler.
func (*AuthManager) WithPostLoginRedirectHandler ¶
func (am *AuthManager) WithPostLoginRedirectHandler(handler AuthManagerRedirectHandler) *AuthManager
WithPostLoginRedirectHandler sets the post login redirect handler.
func (*AuthManager) WithRemoveHandler ¶
func (am *AuthManager) WithRemoveHandler(handler AuthManagerRemoveHandler) *AuthManager
WithRemoveHandler sets the remove handler.
func (*AuthManager) WithSerializeSessionValueHandler ¶
func (am *AuthManager) WithSerializeSessionValueHandler(handler AuthManagerSerializeSessionValueHandler) *AuthManager
WithSerializeSessionValueHandler sets the serialize session value handler.
func (*AuthManager) WithSessionTimeoutProvider ¶
func (am *AuthManager) WithSessionTimeoutProvider(timeoutProvider func(*Session) time.Time) *AuthManager
WithSessionTimeoutProvider sets the session timeout provider.
func (*AuthManager) WithValidateHandler ¶
func (am *AuthManager) WithValidateHandler(handler AuthManagerValidateHandler) *AuthManager
WithValidateHandler sets the validate handler.
type AuthManagerFetchHandler ¶
AuthManagerFetchHandler fetches a session based on a session value.
type AuthManagerMode ¶
type AuthManagerMode string
AuthManagerMode is an auth manager mode.
const ( // AuthManagerModeJWT is the jwt auth mode. AuthManagerModeJWT AuthManagerMode = "jwt" // AuthManagerModeServer is the server managed auth mode. AuthManagerModeServer AuthManagerMode = "server" // AuthManagerModeLocal is the local cache auth mode. AuthManagerModeLocal AuthManagerMode = "cached" )
type AuthManagerParseSessionValueHandler ¶
AuthManagerParseSessionValueHandler deserializes a session from a string.
type AuthManagerPersistHandler ¶
AuthManagerPersistHandler saves the session to a stable store.
type AuthManagerRedirectHandler ¶
AuthManagerRedirectHandler is a redirect handler.
type AuthManagerRemoveHandler ¶
AuthManagerRemoveHandler removes a session based on a session value.
type AuthManagerSerializeSessionValueHandler ¶
AuthManagerSerializeSessionValueHandler serializes a session as a string.
type AuthManagerSessionTimeoutProvider ¶
AuthManagerSessionTimeoutProvider provides a new timeout for a session.
type AuthManagerValidateHandler ¶
AuthManagerValidateHandler validates a session.
type BufferPool ¶
BufferPool is a sync.Pool of bytes.Buffer.
func NewBufferPool ¶
func NewBufferPool(bufferSize int) *BufferPool
NewBufferPool returns a new BufferPool.
func (*BufferPool) Get ¶
func (bp *BufferPool) Get() *bytes.Buffer
Get returns a pooled bytes.Buffer instance.
func (*BufferPool) Put ¶
func (bp *BufferPool) Put(b *bytes.Buffer)
Put returns the pooled instance.
type CachedStaticFile ¶
CachedStaticFile is a memory mapped static file.
func (CachedStaticFile) Render ¶
func (csf CachedStaticFile) Render(ctx *Ctx) error
Render implements Result.
type CachedStaticFileServer ¶
type CachedStaticFileServer struct {
// contains filtered or unexported fields
}
CachedStaticFileServer is a cache of static files.
func NewCachedStaticFileServer ¶
func NewCachedStaticFileServer(fs http.FileSystem) *CachedStaticFileServer
NewCachedStaticFileServer returns a new static file cache.
func (*CachedStaticFileServer) Action ¶
func (csfs *CachedStaticFileServer) Action(r *Ctx) Result
Action is the entrypoint for the static server.
func (*CachedStaticFileServer) AddHeader ¶
func (csfs *CachedStaticFileServer) AddHeader(key, value string)
AddHeader adds a header to the static cache results.
func (*CachedStaticFileServer) AddRewriteRule ¶
func (csfs *CachedStaticFileServer) AddRewriteRule(match string, action RewriteAction) error
AddRewriteRule adds a static re-write rule.
func (*CachedStaticFileServer) Files ¶
func (csfs *CachedStaticFileServer) Files() map[string]*CachedStaticFile
Files returns the underlying file cache. Pragma; this should only be used in debugging, as during runtime locks are required to interact with this cache.
func (*CachedStaticFileServer) GetCachedFile ¶
func (csfs *CachedStaticFileServer) GetCachedFile(filepath string) (*CachedStaticFile, error)
GetCachedFile returns a file from the filesystem at a given path.
func (*CachedStaticFileServer) Headers ¶
func (csfs *CachedStaticFileServer) Headers() http.Header
Headers returns the headers for the static server.
func (*CachedStaticFileServer) Log ¶
func (csfs *CachedStaticFileServer) Log() *logger.Logger
Log returns a logger reference.
func (*CachedStaticFileServer) RewriteRules ¶
func (csfs *CachedStaticFileServer) RewriteRules() []RewriteRule
RewriteRules returns the rewrite rules
func (*CachedStaticFileServer) ServeFile ¶
func (csfs *CachedStaticFileServer) ServeFile(r *Ctx) Result
ServeFile writes the file to the response.
func (*CachedStaticFileServer) SetMiddleware ¶
func (csfs *CachedStaticFileServer) SetMiddleware(middlewares ...Middleware)
SetMiddleware sets the middlewares.
func (*CachedStaticFileServer) WithLogger ¶
func (csfs *CachedStaticFileServer) WithLogger(log *logger.Logger) *CachedStaticFileServer
WithLogger sets the logger reference for the static file cache.
type CompressedResponseWriter ¶
type CompressedResponseWriter struct {
// contains filtered or unexported fields
}
CompressedResponseWriter is a response writer that compresses output.
func NewCompressedResponseWriter ¶
func NewCompressedResponseWriter(w http.ResponseWriter) *CompressedResponseWriter
NewCompressedResponseWriter returns a new gzipped response writer.
func (*CompressedResponseWriter) Close ¶
func (crw *CompressedResponseWriter) Close() error
Close closes any underlying resources.
func (*CompressedResponseWriter) ContentLength ¶
func (crw *CompressedResponseWriter) ContentLength() int
ContentLength returns the content length for the request.
func (*CompressedResponseWriter) Flush ¶
func (crw *CompressedResponseWriter) Flush() error
Flush pushes any buffered data out to the response.
func (*CompressedResponseWriter) Header ¶
func (crw *CompressedResponseWriter) Header() http.Header
Header returns the headers for the response.
func (*CompressedResponseWriter) InnerResponse ¶
func (crw *CompressedResponseWriter) InnerResponse() http.ResponseWriter
InnerResponse returns the backing http response.
func (*CompressedResponseWriter) StatusCode ¶
func (crw *CompressedResponseWriter) StatusCode() int
StatusCode returns the status code for the request.
func (*CompressedResponseWriter) Write ¶
func (crw *CompressedResponseWriter) Write(b []byte) (int, error)
Write writes the byes to the stream.
func (*CompressedResponseWriter) WriteHeader ¶
func (crw *CompressedResponseWriter) WriteHeader(code int)
WriteHeader writes a status code.
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"` RedirectTrailingSlash *bool `json:"redirectTrailingSlash,omitempty" yaml:"redirectTrailingSlash,omitempty"` HandleOptions *bool `json:"handleOptions,omitempty" yaml:"handleOptions,omitempty"` HandleMethodNotAllowed *bool `json:"handleMethodNotAllowed,omitempty" yaml:"handleMethodNotAllowed,omitempty"` RecoverPanics *bool `json:"recoverPanics,omitempty" yaml:"recoverPanics,omitempty"` // AuthManagerMode is a mode designation for the auth manager. AuthManagerMode string `json:"authManagerMode" yaml:"authManagerMode"` // AuthSecret is a secret key to use with auth management. AuthSecret string `json:"authSecret" yaml:"authSecret" env:"AUTH_SECRET"` // SessionTimeout is a fixed duration to use when calculating hard or rolling deadlines. SessionTimeout time.Duration `json:"sessionTimeout,omitempty" yaml:"sessionTimeout,omitempty" env:"SESSION_TIMEOUT"` // SessionTimeoutIsAbsolute determines if the session timeout is a hard deadline or if it gets pushed forward with usage. // The default is to use a hard deadline. SessionTimeoutIsAbsolute *bool `json:"sessionTimeoutIsAbsolute,omitempty" yaml:"sessionTimeoutIsAbsolute,omitempty" env:"SESSION_TIMEOUT_ABSOLUTE"` // CookieHTTPS determines if we should flip the `https only` flag on issued cookies. CookieHTTPSOnly *bool `json:"cookieHTTPSOnly,omitempty" yaml:"cookieHTTPSOnly,omitempty" env:"COOKIE_HTTPS_ONLY"` // CookieName is the name of the cookie to issue with sessions. CookieName string `json:"cookieName,omitempty" yaml:"cookieName,omitempty" env:"COOKIE_NAME"` // CookiePath is the path on the cookie to issue with sessions. CookiePath string `json:"cookiePath,omitempty" yaml:"cookiePath,omitempty" env:"COOKIE_PATH"` // DefaultHeaders are included on any responses. The app ships with a set of default headers, which you can augment with this property. 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_HEADER_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" yaml:"shutdownGracePeriod" env:"SHUTDOWN_GRACE_PERIOD"` HSTS HSTSConfig `json:"hsts,omitempty" yaml:"hsts,omitempty"` TLS TLSConfig `json:"tls,omitempty" yaml:"tls,omitempty"` Views ViewCacheConfig `json:"views,omitempty" yaml:"views,omitempty"` Healthz HealthzConfig `json:"healthz,omitempty" yaml:"healthz,omitempty"` }
Config is an object used to set up a web app.
func MustNewConfigFromEnv ¶
func MustNewConfigFromEnv() *Config
MustNewConfigFromEnv returns a new config from environment variables, and will panic on error.
func NewConfigFromEnv ¶
NewConfigFromEnv returns a new config from the environment.
func (Config) BaseURLIsSecureScheme ¶
BaseURLIsSecureScheme returns if the base url starts with a secure scheme.
func (Config) GetAuthManagerMode ¶
func (c Config) GetAuthManagerMode(inherited ...string) AuthManagerMode
GetAuthManagerMode returns the auth manager mode.
func (Config) GetAuthSecret ¶
GetAuthSecret returns a property or a default.
func (Config) GetBaseURL ¶
GetBaseURL gets a property.
func (Config) GetBindAddr ¶
GetBindAddr util.Coalesces the bind addr, the port, or the default.
func (Config) GetCookieHTTPSOnly ¶
GetCookieHTTPSOnly returns a property or a default.
func (Config) GetCookieName ¶
GetCookieName returns a property or a default.
func (Config) GetCookiePath ¶
GetCookiePath returns a property or a default.
func (Config) GetDefaultHeaders ¶
GetDefaultHeaders returns the default headers from the config.
func (Config) GetHandleMethodNotAllowed ¶
GetHandleMethodNotAllowed returns if we should handle method not allowed results.
func (Config) GetHandleOptions ¶
GetHandleOptions returns if we should handle OPTIONS verb requests.
func (Config) GetIdleTimeout ¶
GetIdleTimeout gets a property.
func (Config) GetMaxHeaderBytes ¶
GetMaxHeaderBytes returns the maximum header size in bytes or a default.
func (Config) GetPort ¶
GetPort 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) GetReadHeaderTimeout ¶
GetReadHeaderTimeout gets a property.
func (Config) GetReadTimeout ¶
GetReadTimeout gets a property.
func (Config) GetRecoverPanics ¶
GetRecoverPanics returns if we should recover panics or not.
func (Config) GetRedirectTrailingSlash ¶
GetRedirectTrailingSlash returns if we automatically redirect for a missing trailing slash.
func (Config) GetSessionTimeout ¶
GetSessionTimeout returns a property or a default.
func (Config) GetSessionTimeoutIsAbsolute ¶
GetSessionTimeoutIsAbsolute returns a property or a default.
func (Config) GetShutdownGracePeriod ¶
GetShutdownGracePeriod gets the shutdown grace period.
func (Config) GetWriteTimeout ¶
GetWriteTimeout 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 {
// contains filtered or unexported fields
}
Ctx is the struct that represents the context for an hc request.
func NewMockCtx ¶
NewMockCtx returns a new mock ctx. It is intended to be used in testing.
func (*Ctx) DefaultResultProvider ¶
func (rc *Ctx) DefaultResultProvider() ResultProvider
DefaultResultProvider returns the current result provider for the context. This is set by calling SetDefaultResultProvider or using one of the pre-built middleware steps that set it for you.
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) JSON ¶
func (rc *Ctx) JSON() JSONResultProvider
JSON returns the JSON result provider.
It can be eschewed for:
return web.JSON.Result(foo)
But is left in place for legacy reasons.
func (*Ctx) NoContent ¶
func (rc *Ctx) NoContent() NoContentResult
NoContent returns a service response.
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) 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) PostedFiles ¶
func (rc *Ctx) PostedFiles() ([]PostedFile, error)
PostedFiles returns any files posted
func (*Ctx) QueryValue ¶
QueryValue returns a query value.
func (*Ctx) RawWithContentType ¶
RawWithContentType returns a binary response with a given content type.
func (*Ctx) Redirect ¶
func (rc *Ctx) Redirect(destination string) *RedirectResult
Redirect returns a redirect result to a given destination.
func (*Ctx) RedirectWithMethod ¶
func (rc *Ctx) RedirectWithMethod(method, destination string) *RedirectResult
RedirectWithMethod returns a redirect result to a destination with a given method.
func (*Ctx) RedirectWithMethodf ¶
func (rc *Ctx) 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 (*Ctx) Redirectf ¶
func (rc *Ctx) Redirectf(format string, args ...interface{}) *RedirectResult
Redirectf returns a redirect result to a given destination specified by a given format and scan arguments.
func (*Ctx) Response ¶
func (rc *Ctx) Response() ResponseWriter
Response returns the underyling response.
func (*Ctx) RouteParam ¶
RouteParam returns a string route parameter
func (*Ctx) RouteParams ¶
func (rc *Ctx) RouteParams() RouteParameters
RouteParams returns the route parameters for the request.
func (*Ctx) StateValue ¶
StateValue returns an object in the state cache.
func (*Ctx) Static ¶
func (rc *Ctx) Static(filePath string) *StaticResult
Static returns a static result.
func (*Ctx) Text ¶
func (rc *Ctx) Text() TextResultProvider
Text returns the text result provider.
It can be eschewed for:
return web.Text.Result(foo)
But is left in place for legacy reasons.
func (*Ctx) View ¶
View returns the view cache as a result provider.
It returns a reference to the view cache where views can either be read from disk for every request (uncached) or read from an in-memory cache.
To return a web result for a view with the name "index" simply return:
return r.View().View("index", myViewmodel)
It is important to not you'll want to have loaded the "index" view at some point in the application bootstrap (typically when you register your controller).
func (*Ctx) WithAuth ¶
func (rc *Ctx) WithAuth(authManager *AuthManager) *Ctx
WithAuth sets the request context auth.
func (*Ctx) WithContext ¶
WithContext sets the background context for the request.
func (*Ctx) WithDefaultResultProvider ¶
func (rc *Ctx) WithDefaultResultProvider(provider ResultProvider) *Ctx
WithDefaultResultProvider sets the default result provider.
func (*Ctx) WithLogger ¶
WithLogger sets the logger.
func (*Ctx) WithRequest ¶
WithRequest sets the underlying request.
func (*Ctx) WithResponse ¶
func (rc *Ctx) WithResponse(res ResponseWriter) *Ctx
WithResponse sets the underlying response.
func (*Ctx) WithRouteParams ¶
func (rc *Ctx) WithRouteParams(params RouteParameters) *Ctx
WithRouteParams sets the route parameters.
func (*Ctx) WithSession ¶
WithSession sets the session for the request.
func (*Ctx) WithStateValue ¶
WithStateValue sets the state for a key to an object.
func (*Ctx) WriteCookie ¶
WriteCookie writes the cookie to the response.
func (*Ctx) WriteNewCookie ¶
func (rc *Ctx) WriteNewCookie(name string, value string, expires time.Time, path string, secure bool)
WriteNewCookie is a helper method for WriteCookie.
func (*Ctx) XML ¶
func (rc *Ctx) XML() XMLResultProvider
XML returns the xml result provider.
It can be eschewed for:
return web.XML.Result(foo)
But is left in place for legacy reasons.
type Fileserver ¶
type Fileserver interface { AddHeader(key, value string) AddRewriteRule(match string, rewriteAction RewriteAction) error SetMiddleware(middleware ...Middleware) Headers() http.Header RewriteRules() []RewriteRule Action(*Ctx) Result }
Fileserver is a type that implements the basics of a fileserver.
type HSTSConfig ¶
type HSTSConfig struct { Enabled *bool `json:"enabled" yaml:"enabled"` MaxAgeSeconds int `json:"maxAgeSeconds" yaml:"maxAgeSeconds"` IncludeSubDomains *bool `json:"includeSubDomains" yaml:"includeSubDomains"` Preload *bool `json:"preload" yaml:"preload"` }
HSTSConfig are hsts options.
func (HSTSConfig) GetEnabled ¶
func (h HSTSConfig) GetEnabled(defaults ...bool) bool
GetEnabled returns if hsts should be enabled.
func (HSTSConfig) GetIncludeSubDomains ¶
func (h HSTSConfig) GetIncludeSubDomains(defaults ...bool) bool
GetIncludeSubDomains returns if hsts should include sub-domains.
func (HSTSConfig) GetMaxAgeSeconds ¶
func (h HSTSConfig) GetMaxAgeSeconds(defaults ...int) int
GetMaxAgeSeconds returns the max age seconds.
func (HSTSConfig) GetPreload ¶
func (h HSTSConfig) GetPreload(defaults ...bool) bool
GetPreload returns if hsts should apply before requests.
type HTTPSUpgrader ¶
type HTTPSUpgrader struct {
// contains filtered or unexported fields
}
HTTPSUpgrader redirects HTTP to HTTPS
func NewHTTPSUpgrader ¶
func NewHTTPSUpgrader() *HTTPSUpgrader
NewHTTPSUpgrader returns a new HTTPSUpgrader which redirects HTTP to HTTPS
func NewHTTPSUpgraderFromConfig ¶
func NewHTTPSUpgraderFromConfig(cfg *HTTPSUpgraderConfig) *HTTPSUpgrader
NewHTTPSUpgraderFromConfig creates a new https upgrader from a config.
func NewHTTPSUpgraderFromEnv ¶
func NewHTTPSUpgraderFromEnv() *HTTPSUpgrader
NewHTTPSUpgraderFromEnv returns a new https upgrader from enviroment variables.
func (*HTTPSUpgrader) Logger ¶
func (hu *HTTPSUpgrader) Logger() *logger.Logger
Logger returns the logger.
func (*HTTPSUpgrader) ServeHTTP ¶
func (hu *HTTPSUpgrader) ServeHTTP(rw http.ResponseWriter, req *http.Request)
ServeHTTP redirects HTTP to HTTPS
func (*HTTPSUpgrader) TargetPort ¶
func (hu *HTTPSUpgrader) TargetPort() int32
TargetPort returns the target port.
func (*HTTPSUpgrader) WithLogger ¶
func (hu *HTTPSUpgrader) WithLogger(log *logger.Logger) *HTTPSUpgrader
WithLogger sets the logger.
func (*HTTPSUpgrader) WithTargetPort ¶
func (hu *HTTPSUpgrader) WithTargetPort(targetPort int32) *HTTPSUpgrader
WithTargetPort sets the target port.
type HTTPSUpgraderConfig ¶
type HTTPSUpgraderConfig struct {
TargetPort int32 `json:"targetPort" yaml:"targetPort" env:"UPGRADE_TARGET_PORT"`
}
HTTPSUpgraderConfig is the config for the https upgrader server.
func NewHTTPSUpgraderConfigFromEnv ¶
func NewHTTPSUpgraderConfigFromEnv() *HTTPSUpgraderConfig
NewHTTPSUpgraderConfigFromEnv returns an https upgrader config populated from the environment.
func (HTTPSUpgraderConfig) GetTargetPort ¶
func (c HTTPSUpgraderConfig) GetTargetPort(defaults ...int32) int32
GetTargetPort gets the target port. It defaults to unset, i.e. use the https default of 443.
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 Healthz ¶
type Healthz struct {
// contains filtered or unexported fields
}
Healthz is a sentinel / healthcheck sidecar that can run on a different port to the main app.
It typically implements the following routes:
/healthz - overall health endpoint, 200 on healthy, 5xx on not. should be used as a kubernetes readiness probe. /debug/vars - `pkg/expvar` output.
func NewHealthz ¶
func NewHealthz(hosted HealthzHostable) *Healthz
NewHealthz returns a new healthz.
func (*Healthz) Config ¶
func (hz *Healthz) Config() *HealthzConfig
Config returns the healthz config.
func (*Healthz) DefaultHeaders ¶
DefaultHeaders returns the default headers.
func (*Healthz) FailureThreshold ¶
FailureThreshold returns the failure threshold.
func (*Healthz) GracePeriod ¶
GracePeriod returns the grace period in seconds
func (*Healthz) IdleTimeout ¶
IdleTimeout is the time before we close a connection.
func (*Healthz) MaxHeaderBytes ¶
MaxHeaderBytes returns the app max header bytes.
func (*Healthz) NotifyStarted ¶
func (hz *Healthz) NotifyStarted() <-chan struct{}
NotifyStarted returns the notify started signal.
func (*Healthz) NotifyStopped ¶ added in v0.3.1
func (hz *Healthz) NotifyStopped() <-chan struct{}
NotifyStopped returns the notify shutdown signal.
func (*Healthz) NotifyStopping ¶ added in v0.3.1
func (hz *Healthz) NotifyStopping() <-chan struct{}
NotifyStopping returns the notify shutdown signal.
func (*Healthz) ReadHeaderTimeout ¶
ReadHeaderTimeout returns the read header timeout for the server.
func (*Healthz) ReadTimeout ¶
ReadTimeout returns the read timeout for the server.
func (*Healthz) RecoverPanics ¶
RecoverPanics returns if the app recovers panics.
func (*Healthz) ServeHTTP ¶
func (hz *Healthz) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP makes the router implement the http.Handler interface.
func (*Healthz) WithBindAddr ¶
WithBindAddr sets the bind address.
func (*Healthz) WithConfig ¶
func (hz *Healthz) WithConfig(cfg *HealthzConfig) *Healthz
WithConfig sets the healthz config and relevant properties.
func (*Healthz) WithDefaultHeader ¶
WithDefaultHeader adds a default header.
func (*Healthz) WithFailureThreshold ¶
WithFailureThreshold sets the failure threshold.
func (*Healthz) WithGracePeriod ¶
WithGracePeriod sets the grace period seconds
func (*Healthz) WithIdleTimeout ¶
WithIdleTimeout sets the idle timeout.
func (*Healthz) WithLogger ¶
WithLogger sets the app logger agent and returns a reference to the app. It also sets underlying loggers in any child resources like providers and the auth manager.
func (*Healthz) WithMaxHeaderBytes ¶
WithMaxHeaderBytes sets the max header bytes value and returns a reference.
func (*Healthz) WithReadHeaderTimeout ¶
WithReadHeaderTimeout returns the read header timeout for the server.
func (*Healthz) WithReadTimeout ¶
WithReadTimeout sets the read timeout for the server and returns a reference to the app for building apps with a fluent api.
func (*Healthz) WithRecoverPanics ¶
WithRecoverPanics sets if the app should recover panics.
func (*Healthz) WithWriteTimeout ¶
WithWriteTimeout sets the write timeout for the server and returns a reference to the app for building apps with a fluent api.
func (*Healthz) WriteTimeout ¶
WriteTimeout returns the write timeout for the server.
type HealthzConfig ¶
type HealthzConfig struct { BindAddr string `json:"bindAddr" yaml:"bindAddr" env:"HEALTHZ_BIND_ADDR"` GracePeriod time.Duration `json:"gracePeriod" yaml:"gracePeriod"` FailureThreshold int `json:"failureThreshold" yaml:"failureThreshold" env:"READY_FAILURE_THRESHOLD"` RecoverPanics *bool `json:"recoverPanics" yaml:"recoverPanics"` MaxHeaderBytes int `json:"maxHeaderBytes,omitempty" yaml:"maxHeaderBytes,omitempty" env:"MAX_HEADER_BYTES"` ReadTimeout time.Duration `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty" env:"READ_HEADER_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"` }
HealthzConfig is the healthz config.
func (HealthzConfig) GetBindAddr ¶
func (hzc HealthzConfig) GetBindAddr(defaults ...string) string
GetBindAddr gets the bind address.
func (HealthzConfig) GetFailureThreshold ¶
func (hzc HealthzConfig) GetFailureThreshold(defaults ...int) int
GetFailureThreshold gets the failure threshold or a default.
func (HealthzConfig) GetGracePeriod ¶
func (hzc HealthzConfig) GetGracePeriod(defaults ...time.Duration) time.Duration
GetGracePeriod gets a grace period or a default.
func (HealthzConfig) GetIdleTimeout ¶
func (hzc HealthzConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration
GetIdleTimeout gets a property.
func (HealthzConfig) GetMaxHeaderBytes ¶
func (hzc HealthzConfig) GetMaxHeaderBytes(defaults ...int) int
GetMaxHeaderBytes returns the maximum header size in bytes or a default.
func (HealthzConfig) GetReadHeaderTimeout ¶
func (hzc HealthzConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
GetReadHeaderTimeout gets a property.
func (HealthzConfig) GetReadTimeout ¶
func (hzc HealthzConfig) GetReadTimeout(defaults ...time.Duration) time.Duration
GetReadTimeout gets a property.
func (HealthzConfig) GetRecoverPanics ¶
func (hzc HealthzConfig) GetRecoverPanics(defaults ...bool) bool
GetRecoverPanics gets recover panics or a default.
func (HealthzConfig) GetWriteTimeout ¶
func (hzc HealthzConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration
GetWriteTimeout gets a property.
type HealthzHostable ¶ added in v0.3.1
HealthzHostable is a type that can be hosted by healthz.
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) 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) Claims ¶
func (jwtm JWTManager) Claims(session *Session) *jwt.StandardClaims
Claims returns the sesion as a JWT standard claims object.
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) ParseSessionValueHandler ¶
func (jwtm JWTManager) ParseSessionValueHandler(_ context.Context, sessionValue string, _ State) (*Session, error)
ParseSessionValueHandler is a shim to the auth manager.
func (JWTManager) SerializeSessionValueHandler ¶
func (jwtm JWTManager) SerializeSessionValueHandler(_ context.Context, session *Session, _ State) (output string, err error)
SerializeSessionValueHandler 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) FetchHandler ¶
func (lsc *LocalSessionCache) FetchHandler(_ context.Context, sessionID string, _ State) (*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 ¶
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 ¶
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 Middleware ¶
Middleware are steps that run in order before a given action.
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 MockRequestBuilder ¶
type MockRequestBuilder struct {
// contains filtered or unexported fields
}
MockRequestBuilder facilitates creating mock requests.
func NewMockRequestBuilder ¶
func NewMockRequestBuilder(app *App) *MockRequestBuilder
NewMockRequestBuilder returns a new mock request builder for a given app.
func (*MockRequestBuilder) Bytes ¶
func (mrb *MockRequestBuilder) Bytes() ([]byte, error)
Bytes returns the response as bytes.
func (*MockRequestBuilder) BytesWithMeta ¶
func (mrb *MockRequestBuilder) BytesWithMeta() ([]byte, *ResponseMeta, error)
BytesWithMeta returns the response as bytes with meta information.
func (*MockRequestBuilder) CreateCtx ¶
func (mrb *MockRequestBuilder) CreateCtx(p RouteParameters) (*Ctx, error)
CreateCtx returns the mock request as a request context.
func (*MockRequestBuilder) Delete ¶
func (mrb *MockRequestBuilder) Delete(pathFormat string, args ...interface{}) *MockRequestBuilder
Delete is a shortcut for WithVerb("DELETE") WithPathf(pathFormat, args...)
func (*MockRequestBuilder) Err ¶
func (mrb *MockRequestBuilder) Err() error
Err rerturns an underlying error
func (*MockRequestBuilder) Execute ¶
func (mrb *MockRequestBuilder) Execute() error
Execute just runs the request. It internally calls `Bytes()` which fully consumes the response.
func (*MockRequestBuilder) ExecuteWithMeta ¶
func (mrb *MockRequestBuilder) ExecuteWithMeta() (*ResponseMeta, error)
ExecuteWithMeta returns basic metadata for a response.
func (*MockRequestBuilder) Get ¶
func (mrb *MockRequestBuilder) Get(pathFormat string, args ...interface{}) *MockRequestBuilder
Get is a shortcut for WithVerb("GET") WithPathf(pathFormat, args...)
func (*MockRequestBuilder) GetStateValue ¶
func (mrb *MockRequestBuilder) GetStateValue(key string) interface{}
GetStateValue returns an object in the state cache.
func (*MockRequestBuilder) JSON ¶
func (mrb *MockRequestBuilder) JSON(object interface{}) error
JSON executes the mock request and reads the response to the given object as json.
func (*MockRequestBuilder) JSONWithMeta ¶
func (mrb *MockRequestBuilder) JSONWithMeta(object interface{}) (*ResponseMeta, error)
JSONWithMeta executes the mock request and reads the response to the given object as json.
func (*MockRequestBuilder) LookupRoute ¶
func (mrb *MockRequestBuilder) LookupRoute() (route *Route, params RouteParameters)
LookupRoute returns the corresponding route for the mocked request.
func (*MockRequestBuilder) Patch ¶
func (mrb *MockRequestBuilder) Patch(pathFormat string, args ...interface{}) *MockRequestBuilder
Patch is a shortcut for WithVerb("PATCH") WithPathf(pathFormat, args...)
func (*MockRequestBuilder) Post ¶
func (mrb *MockRequestBuilder) Post(pathFormat string, args ...interface{}) *MockRequestBuilder
Post is a shortcut for WithVerb("POST") WithPathf(pathFormat, args...)
func (*MockRequestBuilder) Put ¶
func (mrb *MockRequestBuilder) Put(pathFormat string, args ...interface{}) *MockRequestBuilder
Put is a shortcut for WithVerb("PUT") WithPathf(pathFormat, args...)
func (*MockRequestBuilder) Request ¶
func (mrb *MockRequestBuilder) Request() (*http.Request, error)
Request returns the mock request builder settings as an http.Request.
func (*MockRequestBuilder) Response ¶
func (mrb *MockRequestBuilder) Response() (res *http.Response, err error)
Response runs the mock request.
func (*MockRequestBuilder) State ¶
func (mrb *MockRequestBuilder) State() State
State returns the underlying state.
func (*MockRequestBuilder) WithBasicAuth ¶
func (mrb *MockRequestBuilder) WithBasicAuth(username, password string) *MockRequestBuilder
WithBasicAuth sets basic auth credentials for the request.
func (*MockRequestBuilder) WithCookie ¶
func (mrb *MockRequestBuilder) WithCookie(cookie *http.Cookie) *MockRequestBuilder
WithCookie adds a cookie for the request.
func (*MockRequestBuilder) WithCookieValue ¶
func (mrb *MockRequestBuilder) WithCookieValue(name, value string) *MockRequestBuilder
WithCookieValue adds a basic name+value cookie for the request.
func (*MockRequestBuilder) WithErr ¶
func (mrb *MockRequestBuilder) WithErr(err error) *MockRequestBuilder
WithErr sets the error if it is unset.
func (*MockRequestBuilder) WithFormValue ¶
func (mrb *MockRequestBuilder) WithFormValue(key, value string) *MockRequestBuilder
WithFormValue adds a form value for the request.
func (*MockRequestBuilder) WithHeader ¶
func (mrb *MockRequestBuilder) WithHeader(key, value string) *MockRequestBuilder
WithHeader adds a header for the request.
func (*MockRequestBuilder) WithPathf ¶
func (mrb *MockRequestBuilder) WithPathf(pathFormat string, args ...interface{}) *MockRequestBuilder
WithPathf sets the path for the request.
func (*MockRequestBuilder) WithPostBody ¶
func (mrb *MockRequestBuilder) WithPostBody(postBody []byte) *MockRequestBuilder
WithPostBody sets the post body for the request.
func (*MockRequestBuilder) WithPostBodyAsJSON ¶
func (mrb *MockRequestBuilder) WithPostBodyAsJSON(object interface{}) *MockRequestBuilder
WithPostBodyAsJSON sets the post body for the request by serializing an object to JSON.
func (*MockRequestBuilder) WithPostedFile ¶
func (mrb *MockRequestBuilder) WithPostedFile(postedFile PostedFile) *MockRequestBuilder
WithPostedFile includes a file as a post parameter.
func (*MockRequestBuilder) WithQueryString ¶
func (mrb *MockRequestBuilder) WithQueryString(key, value string) *MockRequestBuilder
WithQueryString adds a querystring param for the request.
func (*MockRequestBuilder) WithStateValue ¶
func (mrb *MockRequestBuilder) WithStateValue(key string, value interface{}) *MockRequestBuilder
WithStateValue sets the state for a key to an object.
func (*MockRequestBuilder) WithVerb ¶
func (mrb *MockRequestBuilder) WithVerb(verb string) *MockRequestBuilder
WithVerb sets the verb for the request.
func (*MockRequestBuilder) XML ¶
func (mrb *MockRequestBuilder) XML(object interface{}) error
XML executes the mock request and reads the response to the given object as json.
func (*MockRequestBuilder) XMLWithMeta ¶
func (mrb *MockRequestBuilder) XMLWithMeta(object interface{}) (*ResponseMeta, error)
XMLWithMeta executes the mock request and reads the response to the given object as json.
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 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 RawResponseWriter ¶
type RawResponseWriter struct {
// contains filtered or unexported fields
}
RawResponseWriter a better response writer
func NewRawResponseWriter ¶
func NewRawResponseWriter(w http.ResponseWriter) *RawResponseWriter
NewRawResponseWriter creates a new uncompressed response writer.
func (*RawResponseWriter) Close ¶
func (rw *RawResponseWriter) Close() error
Close disposes of the response writer.
func (*RawResponseWriter) ContentLength ¶
func (rw *RawResponseWriter) ContentLength() int
ContentLength returns the content length
func (*RawResponseWriter) Header ¶
func (rw *RawResponseWriter) Header() http.Header
Header accesses the response header collection.
func (*RawResponseWriter) InnerResponse ¶
func (rw *RawResponseWriter) InnerResponse() http.ResponseWriter
InnerResponse returns the backing writer.
func (*RawResponseWriter) StatusCode ¶
func (rw *RawResponseWriter) StatusCode() int
StatusCode returns the status code.
func (*RawResponseWriter) Write ¶
func (rw *RawResponseWriter) Write(b []byte) (int, error)
Write writes the data to the response.
func (*RawResponseWriter) WriteHeader ¶
func (rw *RawResponseWriter) WriteHeader(code int)
WriteHeader is actually a terrible name and this writes the status code.
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 (*RedirectResult) Render ¶
func (rr *RedirectResult) Render(ctx *Ctx) error
Render writes the result to the response.
type RequestMeta ¶
type RequestMeta struct { StartTime time.Time Verb string URL *url.URL Headers http.Header Body []byte }
RequestMeta is the metadata for a request.
func NewRequestMeta ¶
func NewRequestMeta(req *http.Request) *RequestMeta
NewRequestMeta returns a new meta object for a request.
func NewRequestMetaWithBody ¶
func NewRequestMetaWithBody(req *http.Request) (*RequestMeta, error)
NewRequestMetaWithBody returns a new meta object for a request and reads the body.
type ResponseMeta ¶
ResponseMeta is a metadata response struct
func NewResponseMeta ¶
func NewResponseMeta(res *http.Response) *ResponseMeta
NewResponseMeta creates a new ResponseMeta.
type ResponseWriter ¶
type ResponseWriter interface { Header() http.Header Write([]byte) (int, error) WriteHeader(int) InnerResponse() http.ResponseWriter StatusCode() int ContentLength() int Close() error }
ResponseWriter is a super-type of http.ResponseWriter that includes the StatusCode and ContentLength for the request
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(statusCode int, result ...interface{}) Result }
ResultProvider is the provider interface for results.
type ResultRenderComplete ¶
ResultRenderComplete is a result that has a RenderComplete step.
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 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 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 SessionLockPolicy ¶
type SessionLockPolicy int
SessionLockPolicy is a lock policy.
const ( // SessionUnsafe is a lock-free session policy. SessionUnsafe SessionLockPolicy = 0 // SessionReadLock is a lock policy that acquires a read lock on session. SessionReadLock SessionLockPolicy = 1 // SessionReadWriteLock is a lock policy that acquires both a read and a write lock on session. SessionReadWriteLock SessionLockPolicy = 2 )
type State ¶
type State interface { Keys() []string Get(key string) Any Set(key string, value Any) Remove(key string) Copy() State }
State is a provider for a state bag
type StaticFileServer ¶
type StaticFileServer struct {
// contains filtered or unexported fields
}
StaticFileServer is a cache of static files.
func NewStaticFileServer ¶
func NewStaticFileServer(fs http.FileSystem) *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 will run middleware if specified before serving the file.
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.
func (*StaticFileServer) Headers ¶
func (sc *StaticFileServer) Headers() http.Header
Headers returns the headers for the static server.
func (*StaticFileServer) Log ¶
func (sc *StaticFileServer) Log() *logger.Logger
Log returns a logger reference.
func (*StaticFileServer) RewriteRules ¶
func (sc *StaticFileServer) RewriteRules() []RewriteRule
RewriteRules returns the rewrite rules
func (*StaticFileServer) ServeFile ¶
func (sc *StaticFileServer) ServeFile(r *Ctx) Result
ServeFile writes the file to the response without running middleware.
func (*StaticFileServer) SetMiddleware ¶
func (sc *StaticFileServer) SetMiddleware(middlewares ...Middleware)
SetMiddleware sets the middlewares.
func (*StaticFileServer) WithLogger ¶
func (sc *StaticFileServer) WithLogger(log *logger.Logger) *StaticFileServer
WithLogger sets the logger reference for the static file cache.
type StaticResult ¶
type StaticResult struct { FilePath string FileSystem http.FileSystem RewriteRules []RewriteRule Headers http.Header }
StaticResult represents a static output.
func NewStaticResultForFile ¶
func NewStaticResultForFile(filePath string) *StaticResult
NewStaticResultForFile 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 TCPKeepAliveListener ¶
type TCPKeepAliveListener struct {
*net.TCPListener
}
TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections. It's used by ListenAndServe and ListenAndServeTLS so dead TCP connections (e.g. closing laptop mid-download) eventually go away.
type TLSConfig ¶
type TLSConfig struct { Cert []byte `json:"cert,omitempty" yaml:"cert,omitempty" env:"TLS_CERT"` CertPath string `json:"certPath,omitempty" yaml:"certPath,omitempty" env:"TLS_CERT_PATH"` Key []byte `json:"key,omitempty" yaml:"key,omitempty" env:"TLS_KEY"` KeyPath string `json:"keyPath,omitempty" yaml:"keyPath,omitempty" env:"TLS_KEY_PATH"` CAPaths []string `json:"caPaths,omitempty" yaml:"caPaths,omitempty" env:"TLS_CA_PATHS,csv"` }
TLSConfig is a config for app tls settings.
func (TLSConfig) GetCAPaths ¶
GetCAPaths returns a list of ca paths to add.
func (TLSConfig) GetCertPath ¶
GetCertPath returns a tls cert path.
func (TLSConfig) GetKeyPath ¶
GetKeyPath returns a tls key path.
func (TLSConfig) HasKeyPair ¶
HasKeyPair returns if the config names a keypair.
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 {
// contains filtered or unexported fields
}
ViewCache is the cached views used in view results.
func NewViewCacheFromConfig ¶
func NewViewCacheFromConfig(cfg *ViewCacheConfig) *ViewCache
NewViewCacheFromConfig returns a new view cache from a config.
func (*ViewCache) AddLiterals ¶
AddLiterals adds view literal strings to the view collection.
func (*ViewCache) BadRequest ¶
BadRequest returns a view result.
func (*ViewCache) BadRequestTemplateName ¶
BadRequestTemplateName returns the bad request template.
func (*ViewCache) Cached ¶
Cached indicates if the cache is enabled, or if we skip parsing views each load. Cached == True, use in memory storage for views Cached == False, read the file from disk every time we want to render the view.
func (*ViewCache) Initialize ¶
Initialize caches templates by path.
func (*ViewCache) Initialized ¶
Initialized returns if the viewcache is initialized.
func (*ViewCache) InternalError ¶
InternalError returns a view result.
func (*ViewCache) InternalErrorTemplateName ¶
InternalErrorTemplateName returns the bad request template.
func (*ViewCache) NotAuthorized ¶
NotAuthorized returns a view result.
func (*ViewCache) NotAuthorizedTemplateName ¶
NotAuthorizedTemplateName returns the not authorized template name.
func (*ViewCache) NotFoundTemplateName ¶
NotFoundTemplateName returns the not found template name.
func (*ViewCache) SetLiterals ¶
SetLiterals sets the raw views outright.
func (*ViewCache) SetTemplates ¶
SetTemplates sets the view cache for the app.
func (*ViewCache) StatusTemplateName ¶
StatusTemplateName returns the status template name.
func (*ViewCache) WithBadRequestTemplateName ¶
WithBadRequestTemplateName sets the bad request template.
func (*ViewCache) WithCached ¶
WithCached sets if we should cache views once they're compiled, or always read them from disk. Cached == True, use in memory storage for views Cached == False, read the file from disk every time we want to render the view.
func (*ViewCache) WithInternalErrorTemplateName ¶
WithInternalErrorTemplateName sets the bad request template.
func (*ViewCache) WithNotAuthorizedTemplateName ¶
WithNotAuthorizedTemplateName sets the not authorized template name.
func (*ViewCache) WithNotFoundTemplateName ¶
WithNotFoundTemplateName sets the not found request template name.
func (*ViewCache) WithStatusTemplateName ¶
WithStatusTemplateName sets the status templatename .
type ViewCacheConfig ¶
type ViewCacheConfig struct { Cached *bool `json:"cached,omitempty" yaml:"cached,omitempty" env:"VIEW_CACHE_ENABLED"` Paths []string `json:"paths,omitempty" yaml:"paths,omitempty" env:"VIEW_CACHE_PATHS,csv"` BufferPoolSize int `json:"bufferPoolSize,omitempty" yaml:"bufferPoolSize,omitempty"` InternalErrorTemplateName string `json:"internalErrorTemplateName,omitempty" yaml:"internalErrorTemplateName,omitempty"` BadRequestTemplateName string `json:"badRequestTemplateName,omitempty" yaml:"badRequestTemplateName,omitempty"` NotFoundTemplateName string `json:"notFoundTemplateName,omitempty" yaml:"notFoundTemplateName,omitempty"` NotAuthorizedTemplateName string `json:"notAuthorizedTemplateName,omitempty" yaml:"notAuthorizedTemplateName,omitempty"` StatusTemplateName string `json:"statusTemplateName,omitempty" yaml:"statusTemplateName,omitempty"` }
ViewCacheConfig is a config for the view cache.
func (ViewCacheConfig) GetBadRequestTemplateName ¶
func (vcc ViewCacheConfig) GetBadRequestTemplateName(defaults ...string) string
GetBadRequestTemplateName returns the bad request template name for the app.
func (ViewCacheConfig) GetBufferPoolSize ¶
func (vcc ViewCacheConfig) GetBufferPoolSize(defaults ...int) int
GetBufferPoolSize gets the buffer pool size or a default.
func (ViewCacheConfig) GetCached ¶
func (vcc ViewCacheConfig) GetCached(defaults ...bool) bool
GetCached returns if the viewcache should store templates in memory or read from disk.
func (ViewCacheConfig) GetInternalErrorTemplateName ¶
func (vcc ViewCacheConfig) GetInternalErrorTemplateName(defaults ...string) string
GetInternalErrorTemplateName returns the internal error template name for the app.
func (ViewCacheConfig) GetNotAuthorizedTemplateName ¶
func (vcc ViewCacheConfig) GetNotAuthorizedTemplateName(defaults ...string) string
GetNotAuthorizedTemplateName returns the not authorized template name for the app.
func (ViewCacheConfig) GetNotFoundTemplateName ¶
func (vcc ViewCacheConfig) GetNotFoundTemplateName(defaults ...string) string
GetNotFoundTemplateName returns the not found template name for the app.
func (ViewCacheConfig) GetPaths ¶
func (vcc ViewCacheConfig) GetPaths(defaults ...[]string) []string
GetPaths returns default view paths.
func (ViewCacheConfig) GetStatusTemplateName ¶
func (vcc ViewCacheConfig) GetStatusTemplateName(defaults ...string) string
GetStatusTemplateName returns the not authorized template name for the app.
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 ViewTraceFinisher ¶
type ViewTraceFinisher interface {
Finish(*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
- app_event.go
- auth_manager.go
- buffer_pool.go
- cached_static_file.go
- cached_static_file_server.go
- compressed_response_writer.go
- config.go
- constants.go
- controller.go
- ctx.go
- doc.go
- error.go
- fileserver.go
- graceful.go
- healthz.go
- healthz_config.go
- hsts_config.go
- https_upgrader.go
- https_upgrader_config.go
- json_result.go
- json_result_provider.go
- jwt_manager.go
- local_session_cache.go
- middleware.go
- mock_request_builder.go
- no_content_result.go
- posted_file.go
- raw_response_writer.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
- tcp_keep_alive_listener.go
- text_result_provider.go
- timeout.go
- tls_config.go
- tracer.go
- tree.go
- util.go
- view_cache.go
- view_cache_config.go
- view_model.go
- view_result.go
- xml_result.go
- xml_result_provider.go