Documentation
¶
Index ¶
- Constants
- Variables
- func Base64Decode(raw string) ([]byte, error)
- func Base64Encode(raw []byte) string
- func CleanPath(p string) string
- func DeserializeReaderAsJSON(object interface{}, body io.ReadCloser) error
- func EncodeSignSessionID(sessionID string, key []byte) (string, error)
- func GenerateCryptoKey(keySize int) []byte
- func GenerateSHA512Key() []byte
- func HealthzHost(app *App, hz *Healthz) (err error)
- func IsErrSessionInvalid(err error) bool
- func LocalIP() string
- func MustEncodeSignSessionID(sessionID string, key []byte) string
- func MustParseURL(rawURL string) *url.URL
- func MustSignSessionID(sessionID string, key []byte) []byte
- func NewAppEventListener(listener func(me *AppEvent)) logger.Listener
- func NewBasicCookie(name, value string) *http.Cookie
- func NewMockRequest(method, path string) *http.Request
- func NewSessionID() string
- func ParseInt32(v string) int32
- func PortFromBindAddr(bindAddr string) int32
- func ReadSetCookieByName(h http.Header, name string) *http.Cookie
- func ReadSetCookies(h http.Header) []*http.Cookie
- func SignSessionID(sessionID string, key []byte) ([]byte, error)
- func Tx(sp StateProvider, optionalKey ...string) *sql.Tx
- func TxFromState(state State, keys ...string) *sql.Tx
- func WithTxForState(state State, tx *sql.Tx, keys ...string)
- func WriteJSON(w http.ResponseWriter, r *http.Request, statusCode int, response interface{}) error
- func WriteNoContent(w http.ResponseWriter) error
- func WriteRawContent(w http.ResponseWriter, statusCode int, content []byte) error
- func WriteXML(w http.ResponseWriter, r *http.Request, statusCode int, response interface{}) error
- type Action
- func Cancel(action Action) Action
- func JSONProviderAsDefault(action Action) Action
- func NestMiddleware(action Action, middleware ...Middleware) Action
- func SessionAware(action Action) Action
- func SessionAwareMutating(action Action) Action
- func SessionAwareUnsafe(action Action) Action
- func SessionRequired(action Action) Action
- func SessionRequiredMutating(action Action) Action
- func SessionRequiredUnsafe(action Action) Action
- func TextProviderAsDefault(action Action) Action
- func ViewProviderAsDefault(action Action) Action
- func XMLProviderAsDefault(action Action) Action
- type App
- func (a *App) Auth() *AuthManager
- func (a *App) BaseURL() *url.URL
- func (a *App) BindAddr() string
- 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) GetState(key string) interface{}
- func (a *App) HEAD(path string, action Action, middleware ...Middleware)
- func (a *App) HSTS() bool
- func (a *App) HSTSIncludeSubdomains() bool
- func (a *App) HSTSMaxAgeSeconds() int
- func (a *App) HSTSPreload() bool
- func (a *App) Handle(method, path string, handler Handler)
- func (a *App) HandleMethodNotAllowed() bool
- func (a *App) HandleOptions() bool
- func (a *App) IdleTimeout() time.Duration
- func (a *App) JSONResultProvider() *JSONResultProvider
- 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) Mock() *MockRequestBuilder
- func (a *App) OPTIONS(path string, action Action, middleware ...Middleware)
- func (a *App) OnStart(action AppStartDelegate)
- 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) 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) Running() (running bool)
- 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) SetBaseURL(baseURL *url.URL)
- func (a *App) SetParsedBaseURL(baseURL string) error
- func (a *App) SetPort(port int32)
- func (a *App) SetPortFromEnv() error
- func (a *App) SetState(key string, value interface{})
- 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) SetTLSCertPair(tlsCert, tlsKey []byte) error
- func (a *App) SetTLSCertPairFromFiles(tlsCertPath, tlsKeyPath string) error
- func (a *App) SetTLSClientCertPool(certs ...[]byte) error
- func (a *App) SetTLSConfig(config *tls.Config)
- func (a *App) SetTLSFromEnv() error
- func (a *App) Shutdown() error
- func (a *App) Start() (err error)
- func (a *App) Started() <-chan struct{}
- func (a *App) StartupTasks() error
- func (a *App) State() State
- func (a *App) TLSConfig() *tls.Config
- func (a *App) TextResultProvider() *TextResultProvider
- func (a *App) ViewResultProvider() *ViewResultProvider
- 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) WithBindAddrFromEnv() *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) WithDefaultResultProvider(drp ResultProvider) *App
- func (a *App) WithHSTS(enabled bool) *App
- func (a *App) WithHSTSIncludeSubdomains(includeSubdomains bool) *App
- func (a *App) WithHSTSMaxAgeSeconds(ageSeconds int) *App
- func (a *App) WithHSTSPreload(preload bool) *App
- func (a *App) WithHandleMethodNotAllowed(handle bool) *App
- func (a *App) WithHandleOptions(handle bool) *App
- func (a *App) WithIdleTimeout(timeout time.Duration) *App
- func (a *App) WithJSONResultProvider(jrp *JSONResultProvider) *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) WithPortFromEnv() *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) WithState(key string, value interface{}) *App
- func (a *App) WithTLSClientCertVerification(verification tls.ClientAuthType) *App
- func (a *App) WithTLSConfig(config *tls.Config) *App
- func (a *App) WithTextResultProvider(trp *TextResultProvider) *App
- func (a *App) WithViewResultProvider(vrp *ViewResultProvider) *App
- func (a *App) WithViews(vc *ViewCache) *App
- func (a *App) WithWriteTimeout(timeout time.Duration) *App
- func (a *App) WithXMLResultProvider(xrp *XMLResultProvider) *App
- func (a *App) WriteTimeout() time.Duration
- func (a *App) XMLResultProvider() *XMLResultProvider
- 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 AppStartDelegate
- type AuthManager
- func (am *AuthManager) CookieName() string
- func (am *AuthManager) CookiePath() string
- func (am *AuthManager) CookiesAsSessionBound() bool
- func (am *AuthManager) CookiesHTTPSOnly() bool
- func (am *AuthManager) FetchHandler() func(sessionID string, state State) (*Session, error)
- func (am *AuthManager) GenerateSessionTimeout(context *Ctx) *time.Time
- func (am *AuthManager) Logger() *logger.Logger
- func (am *AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error)
- func (am *AuthManager) LoginRedirectHandler() func(*Ctx) *url.URL
- func (am *AuthManager) Logout(ctx *Ctx) error
- func (am *AuthManager) PersistHandler() func(*Ctx, *Session, State) error
- func (am *AuthManager) Redirect(ctx *Ctx) Result
- func (am *AuthManager) RemoveHandler() func(sessionID string, state State) error
- func (am *AuthManager) Secret() []byte
- func (am *AuthManager) SecureCookieName() string
- func (am *AuthManager) SessionCache() *SessionCache
- func (am *AuthManager) SessionTimeout() time.Duration
- func (am *AuthManager) SessionTimeoutProvider() func(rc *Ctx) *time.Time
- func (am *AuthManager) SesssionTimeoutIsAbsolute() bool
- func (am *AuthManager) SesssionTimeoutIsRolling() bool
- func (am *AuthManager) SetCookieHTTPSOnly(isHTTPSOnly bool)
- func (am *AuthManager) SetCookieName(paramName string)
- func (am *AuthManager) SetCookiePath(path string)
- func (am *AuthManager) SetCookiesAsSessionBound()
- func (am *AuthManager) SetFetchHandler(handler func(sessionID string, state State) (*Session, error))
- func (am *AuthManager) SetLogger(log *logger.Logger)
- func (am *AuthManager) SetLoginRedirectHandler(handler func(*Ctx) *url.URL)
- func (am *AuthManager) SetPersistHandler(handler func(*Ctx, *Session, State) error)
- func (am *AuthManager) SetRemoveHandler(handler func(sessionID string, state State) error)
- func (am *AuthManager) SetSecret(secret []byte)
- func (am *AuthManager) SetSecureCookieName(paramName string)
- func (am *AuthManager) SetSessionTimeout(timeout time.Duration)
- func (am *AuthManager) SetSessionTimeoutIsAbsolute(isAbsolute bool)
- func (am *AuthManager) SetSessionTimeoutProvider(timeoutProvider func(rc *Ctx) *time.Time)
- func (am *AuthManager) SetUseSessionCache(value bool)
- func (am *AuthManager) SetValidateHandler(handler func(*Session, State) error)
- func (am *AuthManager) UseSessionCache() bool
- func (am *AuthManager) ValidateHandler() func(*Session, State) error
- func (am *AuthManager) VerifySession(ctx *Ctx) (*Session, error)
- func (am *AuthManager) WithAbsoluteSessionTimeout() *AuthManager
- func (am *AuthManager) WithCookieName(paramName string) *AuthManager
- func (am *AuthManager) WithCookiePath(path string) *AuthManager
- func (am *AuthManager) WithCookiesAsSessionBound() *AuthManager
- func (am *AuthManager) WithCookiesHTTPSOnly(isHTTPSOnly bool) *AuthManager
- func (am *AuthManager) WithFetchHandler(handler func(sessionID string, state State) (*Session, error)) *AuthManager
- func (am *AuthManager) WithLogger(log *logger.Logger) *AuthManager
- func (am *AuthManager) WithLoginRedirectHandler(handler func(*Ctx) *url.URL) *AuthManager
- func (am *AuthManager) WithPersistHandler(handler func(*Ctx, *Session, State) error) *AuthManager
- func (am *AuthManager) WithRemoveHandler(handler func(sessionID string, state State) error) *AuthManager
- func (am *AuthManager) WithRollingSessionTimeout() *AuthManager
- func (am *AuthManager) WithSecret(secret []byte) *AuthManager
- func (am *AuthManager) WithSecureCookieName(paramName string) *AuthManager
- func (am *AuthManager) WithSessionTimeout(timeout time.Duration) *AuthManager
- func (am *AuthManager) WithSessionTimeoutProvider(timeoutProvider func(rc *Ctx) *time.Time) *AuthManager
- func (am *AuthManager) WithUseSessionCache(value bool) *AuthManager
- func (am *AuthManager) WithValidateHandler(handler func(*Session, State) error) *AuthManager
- 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) 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) GetHSTS(inherited ...bool) bool
- func (c Config) GetHSTSIncludeSubDomains(inherited ...bool) bool
- func (c Config) GetHSTSMaxAgeSeconds(inherited ...int) int
- func (c Config) GetHSTSPreload(inherited ...bool) bool
- 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) GetSecureCookieHTTPSOnly(defaults ...bool) bool
- func (c Config) GetSecureCookieName(defaults ...string) string
- func (c Config) GetSessionTimeout(defaults ...time.Duration) time.Duration
- func (c Config) GetSessionTimeoutIsAbsolute(defaults ...bool) bool
- func (c Config) GetUseSessionCache(defaults ...bool) bool
- 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) Background() context.Context
- func (rc *Ctx) Cancel()
- func (rc *Ctx) DefaultResultProvider() ResultProvider
- func (rc *Ctx) Elapsed() time.Duration
- 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) GetCookie(name string) *http.Cookie
- func (rc *Ctx) HeaderParam(key string) (string, error)
- func (rc *Ctx) HeaderParamFloat64(key string) (float64, error)
- func (rc *Ctx) HeaderParamInt(key string) (int, error)
- func (rc *Ctx) HeaderParamInt64(key string) (int64, error)
- func (rc *Ctx) HeaderParamTime(key, format string) (time.Time, error)
- 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) ParamBool(name string) (bool, error)
- func (rc *Ctx) ParamFloat64(name string) (float64, error)
- func (rc *Ctx) ParamInt(name string) (int, error)
- func (rc *Ctx) ParamInt64(name string) (int64, error)
- func (rc *Ctx) ParamString(name string) string
- func (rc *Ctx) ParamTime(name, format string) (time.Time, 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) QueryParam(key string) (string, error)
- func (rc *Ctx) QueryParamFloat64(key string) (float64, error)
- func (rc *Ctx) QueryParamInt(key string) (int, error)
- func (rc *Ctx) QueryParamInt64(key string) (int64, error)
- func (rc *Ctx) QueryParamTime(key, format string) (time.Time, error)
- func (rc *Ctx) Raw(body []byte) *RawResult
- func (rc *Ctx) RawWithContentType(contentType string, body []byte) *RawResult
- 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) (string, error)
- func (rc *Ctx) RouteParamFloat64(key string) (float64, error)
- func (rc *Ctx) RouteParamInt(key string) (int, error)
- func (rc *Ctx) RouteParamInt64(key string) (int64, error)
- 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) View() *ViewResultProvider
- func (rc *Ctx) WithApp(app *App) *Ctx
- func (rc *Ctx) WithAuth(authManager *AuthManager) *Ctx
- func (rc *Ctx) WithContext(ctx context.Context) *Ctx
- func (rc *Ctx) WithDefaultResultProvider(provider ResultProvider) *Ctx
- func (rc *Ctx) WithRequest(req *http.Request) *Ctx
- func (rc *Ctx) WithResponse(res ResponseWriter) *Ctx
- func (rc *Ctx) WithSession(session *Session) *Ctx
- func (rc *Ctx) WithStateValue(key string, value interface{}) *Ctx
- func (rc *Ctx) WithTx(tx *sql.Tx, optionalKey ...string) *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 Error
- type Fileserver
- type HTTPSUpgrader
- func (hu *HTTPSUpgrader) BindAddr() string
- func (hu *HTTPSUpgrader) IdleTimeout() time.Duration
- func (hu *HTTPSUpgrader) Logger() *logger.Logger
- func (hu *HTTPSUpgrader) MaxHeaderBytes() int
- func (hu *HTTPSUpgrader) ReadHeaderTimeout() time.Duration
- func (hu *HTTPSUpgrader) ReadTimeout() time.Duration
- func (hu *HTTPSUpgrader) ServeHTTP(rw http.ResponseWriter, req *http.Request)
- func (hu *HTTPSUpgrader) Server() *http.Server
- func (hu *HTTPSUpgrader) SetPort(port int32)
- func (hu *HTTPSUpgrader) SetPortFromEnv()
- func (hu *HTTPSUpgrader) Shutdown() error
- func (hu *HTTPSUpgrader) Start() error
- func (hu *HTTPSUpgrader) StartWithServer(server *http.Server) (err error)
- func (hu *HTTPSUpgrader) TargetPort() int32
- func (hu *HTTPSUpgrader) WithBindAddr(bindAddr string) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithBindAddrFromEnv() *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithIdleTimeout(timeout time.Duration) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithLogger(log *logger.Logger) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithMaxHeaderBytes(byteCount int) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithPort(port int32) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithPortFromEnv() *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithReadHeaderTimeout(timeout time.Duration) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithReadTimeout(timeout time.Duration) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithTargetPort(port int32) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WithWriteTimeout(timeout time.Duration) *HTTPSUpgrader
- func (hu *HTTPSUpgrader) WriteTimeout() time.Duration
- type HTTPSUpgraderConfig
- func (c HTTPSUpgraderConfig) GetBindAddr(defaults ...string) string
- func (c HTTPSUpgraderConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration
- func (c HTTPSUpgraderConfig) GetMaxHeaderBytes(defaults ...int) int
- func (c HTTPSUpgraderConfig) GetPort(defaults ...int32) int32
- func (c HTTPSUpgraderConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
- func (c HTTPSUpgraderConfig) GetReadTimeout(defaults ...time.Duration) time.Duration
- func (c HTTPSUpgraderConfig) GetTargetPort(defaults ...int32) int32
- func (c HTTPSUpgraderConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration
- type Handler
- type Healthz
- func (hz *Healthz) App() *App
- func (hz *Healthz) BindAddr() string
- func (hz *Healthz) CreateServer() *http.Server
- func (hz *Healthz) DefaultHeaders() map[string]string
- func (hz *Healthz) Err() error
- func (hz *Healthz) GetState(key string) interface{}
- func (hz *Healthz) IdleTimeout() time.Duration
- func (hz *Healthz) Listener() *net.TCPListener
- func (hz *Healthz) Logger() *logger.Logger
- func (hz *Healthz) MaxHeaderBytes() int
- func (hz *Healthz) ReadHeaderTimeout() time.Duration
- func (hz *Healthz) ReadTimeout() time.Duration
- func (hz *Healthz) RecoverPanics() bool
- func (hz *Healthz) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (hz *Healthz) Server() *http.Server
- func (hz *Healthz) SetPort(port int32)
- func (hz *Healthz) SetPortFromEnv()
- func (hz *Healthz) SetState(key string, value interface{})
- func (hz *Healthz) Shutdown() error
- func (hz *Healthz) Start() (err error)
- func (hz *Healthz) State() State
- func (hz *Healthz) Vars() State
- func (hz *Healthz) WithBindAddr(bindAddr string) *Healthz
- func (hz *Healthz) WithBindAddrFromEnv() *Healthz
- func (hz *Healthz) WithDefaultHeader(key string, value string) *Healthz
- func (hz *Healthz) WithDefaultHeaders(headers map[string]string) *Healthz
- func (hz *Healthz) WithErr(err error) *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) WithPort(port int32) *Healthz
- func (hz *Healthz) WithPortFromEnv() *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) WithServer(server *http.Server) *Healthz
- func (hz *Healthz) WithState(key string, value interface{}) *Healthz
- func (hz *Healthz) WithWriteTimeout(timeout time.Duration) *Healthz
- func (hz *Healthz) WriteTimeout() time.Duration
- type HealthzConfig
- func (hc HealthzConfig) GetBindAddr(defaults ...string) string
- func (hc HealthzConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration
- func (hc HealthzConfig) GetMaxHeaderBytes(defaults ...int) int
- func (hc HealthzConfig) GetPort(defaults ...int32) int32
- func (hc HealthzConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
- func (hc HealthzConfig) GetReadTimeout(defaults ...time.Duration) time.Duration
- func (hc HealthzConfig) GetRecoverPanics(defaults ...bool) bool
- func (hc HealthzConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration
- 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
- 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) 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) WithTx(tx *sql.Tx, keys ...string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) WithVerb(verb string) *MockRequestBuilder
- func (mrb *MockRequestBuilder) XML(object interface{}) error
- func (mrb *MockRequestBuilder) XMLWithMeta(object interface{}) (*ResponseMeta, error)
- type MockResponseWriter
- func (res *MockResponseWriter) Bytes() []byte
- func (res *MockResponseWriter) Close() error
- func (res *MockResponseWriter) ContentLength() int
- func (res *MockResponseWriter) Flush() error
- func (res *MockResponseWriter) Header() http.Header
- func (res *MockResponseWriter) InnerResponse() http.ResponseWriter
- func (res *MockResponseWriter) StatusCode() int
- func (res *MockResponseWriter) Write(buffer []byte) (int, error)
- func (res *MockResponseWriter) WriteHeader(statusCode int)
- type NoContentResult
- type NoContentResultProvider
- func (ncr *NoContentResultProvider) BadRequest(err error) Result
- func (ncr *NoContentResultProvider) InternalError(err error) Result
- func (ncr *NoContentResultProvider) NotAuthorized() Result
- func (ncr *NoContentResultProvider) NotFound() Result
- func (ncr *NoContentResultProvider) Result(response interface{}) Result
- 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 Request
- type RequestMeta
- type ResponseMeta
- type ResponseWriter
- type Result
- type ResultProvider
- type RewriteAction
- type RewriteRule
- type Route
- type RouteParameters
- type Session
- type SessionCache
- type SessionLockPolicy
- type State
- type StateProvider
- type StateValueProvider
- 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 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
- type ViewCache
- func (vc *ViewCache) AddLiterals(views ...string)
- func (vc *ViewCache) AddPaths(paths ...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) Parse() (views *template.Template, err error)
- func (vc *ViewCache) Paths() []string
- func (vc *ViewCache) SetCached(cached bool)
- func (vc *ViewCache) SetLiterals(viewLiterals ...string)
- func (vc *ViewCache) SetPaths(paths ...string)
- func (vc *ViewCache) SetTemplates(viewCache *template.Template)
- func (vc *ViewCache) Templates() *template.Template
- type ViewCacheConfig
- type ViewModel
- type ViewResult
- type ViewResultProvider
- func (vr *ViewResultProvider) BadRequest(err error) Result
- func (vr *ViewResultProvider) BadRequestTemplateName() string
- func (vr *ViewResultProvider) InternalError(err error) Result
- func (vr *ViewResultProvider) InternalErrorTemplateName() string
- func (vr *ViewResultProvider) NotAuthorized() Result
- func (vr *ViewResultProvider) NotAuthorizedTemplateName() string
- func (vr *ViewResultProvider) NotFound() Result
- func (vr *ViewResultProvider) NotFoundTemplateName() string
- func (vr *ViewResultProvider) View(viewName string, viewModel interface{}) Result
- func (vr *ViewResultProvider) WithBadRequestTemplateName(templateName string) *ViewResultProvider
- func (vr *ViewResultProvider) WithInternalErrorTemplateName(templateName string) *ViewResultProvider
- func (vr *ViewResultProvider) WithNotAuthorizedTemplateName(templateName string) *ViewResultProvider
- func (vr *ViewResultProvider) WithNotFoundTemplateName(templateName string) *ViewResultProvider
- 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(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" // 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" // 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 (here implying we should use session lived sessions). DefaultSessionTimeout time.Duration = 0 // 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 )
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. // StringEmpty is the empty string. StringEmpty = "" )
const ( // VarzStarted is a common variable. VarzStarted = "startedUTC" // VarzRequests is a common variable. VarzRequests = "http_requests" // VarzRequests2xx is a common variable. VarzRequests2xx = "http_requests2xx" // VarzRequests3xx is a common variable. VarzRequests3xx = "http_requests3xx" // VarzRequests4xx is a common variable. VarzRequests4xx = "http_requests4xx" // VarzRequests5xx is a common variable. VarzRequests5xx = "http_requests5xx" // VarzErrors is a common variable. VarzErrors = "errors_total" // VarzFatals is a common variable. VarzFatals = "fatals_total" // ListenerHealthz is the uid of the healthz logger listeners. ListenerHealthz = "healthz" // ErrHealthzAppUnset is a common error. ErrHealthzAppUnset Error = "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" // 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>` )
const ( // DefaultTCPKeepAliveListenerPeriod is the default keep alive period for the tcp listener. DefaultTCPKeepAliveListenerPeriod = 3 * time.Minute )
const (
// StateKeyTx is the app state key for a transaction.
StateKeyTx = "tx"
)
Variables ¶
var ( // BufferPool is a shared sync.Pool of bytes.Buffer instances. BufferPool = logger.NewBufferPool(32) )
var DefaultHeaders = map[string]string{ HeaderServer: PackageName, HeaderXServedBy: PackageName, }
DefaultHeaders are the default headers added by go-web.
Functions ¶
func Base64Decode ¶
Base64Decode 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 DeserializeReaderAsJSON ¶
func DeserializeReaderAsJSON(object interface{}, body io.ReadCloser) error
DeserializeReaderAsJSON deserializes a post body as json to a given object.
func EncodeSignSessionID ¶
EncodeSignSessionID returns a new secure session id base64 encoded..
func GenerateCryptoKey ¶
GenerateCryptoKey generates a cryptographic key.
func GenerateSHA512Key ¶
func GenerateSHA512Key() []byte
GenerateSHA512Key generates a crypto key for SHA512 hashing.
func HealthzHost ¶
HealthzHost hosts an app with a healthz, starting both servers.
func IsErrSessionInvalid ¶
IsErrSessionInvalid returns if an error is a session invalid error.
func MustEncodeSignSessionID ¶
MustEncodeSignSessionID returns a signed sessionID as base64 encoded. It panics if there is an error.
func MustParseURL ¶
MustParseURL parses a url and panics if there is an error.
func MustSignSessionID ¶
MustSignSessionID signs a session id and panics if there is an issue.
func NewAppEventListener ¶
NewAppEventListener returns a new app start event listener.
func NewBasicCookie ¶
NewBasicCookie returns a new name + value pair cookie.
func NewMockRequest ¶
NewMockRequest creates a mock request.
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 PortFromBindAddr ¶
PortFromBindAddr returns a port number as an integer from a bind addr.
func ReadSetCookieByName ¶
ReadSetCookieByName returns a set cookie by name.
func ReadSetCookies ¶
ReadSetCookies parses all "Set-Cookie" values from the header h and returns the successfully parsed Cookies.
func SignSessionID ¶
SignSessionID returns a new secure session id.
func Tx ¶
func Tx(sp StateProvider, optionalKey ...string) *sql.Tx
Tx returns the transaction for the request. keys is an optional parameter used for additional arbitrary transactions
func TxFromState ¶
TxFromState returns a tx from a state bag.
func WithTxForState ¶
WithTxForState injects a tx into a statebag.
func WriteNoContent ¶
func WriteNoContent(w http.ResponseWriter) error
WriteNoContent writes http.StatusNoContent for a request.
func WriteRawContent ¶
func WriteRawContent(w http.ResponseWriter, statusCode int, content []byte) error
WriteRawContent writes raw content for the request.
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 SessionAwareMutating ¶
SessionAwareMutating is an action that injects the session into the context and requires a write lock.
func SessionAwareUnsafe ¶
SessionAwareUnsafe is an action that injects the session into the context without acquiring any (read or write) locks.
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 SessionRequiredMutating ¶
SessionRequiredMutating is an action that requires the session to present and also requires a write lock.
func SessionRequiredUnsafe ¶
SessionRequiredUnsafe is an action that requires the session to present and does not acquire any (read or write) locks.
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 NewFromConfig ¶
NewFromConfig returns a new app from a given config.
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.
func (*App) HEAD ¶
func (a *App) HEAD(path string, action Action, middleware ...Middleware)
HEAD registers a HEAD request handler.
func (*App) HSTSIncludeSubdomains ¶
HSTSIncludeSubdomains returns if we should include subdomains in hsts.
func (*App) HSTSMaxAgeSeconds ¶
HSTSMaxAgeSeconds is the maximum lifetime browsers should honor the secure transport header.
func (*App) HSTSPreload ¶
HSTSPreload returns if we should preload hsts.
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) JSONResultProvider ¶
func (a *App) JSONResultProvider() *JSONResultProvider
JSONResultProvider returns the json result provider.
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) Mock ¶
func (a *App) Mock() *MockRequestBuilder
Mock returns a request bulider to facilitate mocking requests.
func (*App) OPTIONS ¶
func (a *App) OPTIONS(path string, action Action, middleware ...Middleware)
OPTIONS registers a OPTIONS request handler.
func (*App) OnStart ¶
func (a *App) OnStart(action AppStartDelegate)
OnStart lets you register a task that is run before the server starts. Typically this delegate sets up the database connection and other init items.
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) 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) SetBaseURL ¶
SetBaseURL sets the base url for the app.
func (*App) SetParsedBaseURL ¶
SetParsedBaseURL sets the BaseURL from a string.
func (*App) SetPort ¶
SetPort sets the port the app listens on, typically to `:%d` which indicates listen on any interface.
func (*App) SetPortFromEnv ¶
SetPortFromEnv sets the port from an environment variable, and returns a reference to the app.
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) SetTLSCertPair ¶
SetTLSCertPair sets the app to use TLS with a given cert.
func (*App) SetTLSCertPairFromFiles ¶
SetTLSCertPairFromFiles reads a tls key pair from a given set of paths.
func (*App) SetTLSClientCertPool ¶
SetTLSClientCertPool set the client cert pool from a given set of pems.
func (*App) SetTLSConfig ¶
SetTLSConfig sets the tls config.
func (*App) SetTLSFromEnv ¶
SetTLSFromEnv reads TLS settings from the environment.
func (*App) Started ¶
func (a *App) Started() <-chan struct{}
Started returns a channel signalling the app has started.
func (*App) StartupTasks ¶
StartupTasks runs common startup tasks.
func (*App) TextResultProvider ¶
func (a *App) TextResultProvider() *TextResultProvider
TextResultProvider returns the text result provider.
func (*App) ViewResultProvider ¶
func (a *App) ViewResultProvider() *ViewResultProvider
ViewResultProvider returns the view result provider.
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) WithBindAddrFromEnv ¶
WithBindAddrFromEnv 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) WithDefaultResultProvider ¶
func (a *App) WithDefaultResultProvider(drp ResultProvider) *App
WithDefaultResultProvider sets the default result provider.
func (*App) WithHSTSIncludeSubdomains ¶
WithHSTSIncludeSubdomains sets if we should include subdomains in hsts.
func (*App) WithHSTSMaxAgeSeconds ¶
WithHSTSMaxAgeSeconds sets the hsts max age seconds.
func (*App) WithHSTSPreload ¶
WithHSTSPreload sets if we preload hsts.
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) WithIdleTimeout ¶
WithIdleTimeout sets the idle timeout.
func (*App) WithJSONResultProvider ¶
func (a *App) WithJSONResultProvider(jrp *JSONResultProvider) *App
WithJSONResultProvider sets the json result provider.
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) WithPortFromEnv ¶
WithPortFromEnv sets the port from an environment variable, 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) WithState ¶
WithState 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) WithTextResultProvider ¶
func (a *App) WithTextResultProvider(trp *TextResultProvider) *App
WithTextResultProvider sets the text result provider.
func (*App) WithViewResultProvider ¶
func (a *App) WithViewResultProvider(vrp *ViewResultProvider) *App
WithViewResultProvider sets the view result provider.
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) WithXMLResultProvider ¶
func (a *App) WithXMLResultProvider(xrp *XMLResultProvider) *App
WithXMLResultProvider sets the xml result provider.
func (*App) WriteTimeout ¶
WriteTimeout returns the write timeout for the server.
func (*App) XMLResultProvider ¶
func (a *App) XMLResultProvider() *XMLResultProvider
XMLResultProvider returns the xml result provider.
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 AppStartDelegate ¶
AppStartDelegate is a function that is run on start. Typically you use this to initialize the app.
type AuthManager ¶
type AuthManager struct {
// contains filtered or unexported fields
}
AuthManager is a manager for sessions.
func NewAuthManager ¶
func NewAuthManager() *AuthManager
NewAuthManager returns a new session manager.
func NewAuthManagerFromConfig ¶
func NewAuthManagerFromConfig(cfg *Config) *AuthManager
NewAuthManagerFromConfig returns a new auth manager from a given config.
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) CookiesAsSessionBound ¶
func (am *AuthManager) CookiesAsSessionBound() bool
CookiesAsSessionBound returns if cookies are issued with `session` liveness.
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() func(sessionID string, state State) (*Session, error)
FetchHandler returns the fetch handler. It is used in `VerifySession` to satisfy session cache misses.
func (*AuthManager) GenerateSessionTimeout ¶
func (am *AuthManager) GenerateSessionTimeout(context *Ctx) *time.Time
GenerateSessionTimeout returns the absolute time the cookie would expire.
func (*AuthManager) Logger ¶
func (am *AuthManager) Logger() *logger.Logger
Logger returns the instance logger.
func (*AuthManager) Login ¶
func (am *AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error)
Login logs a userID in.
func (*AuthManager) LoginRedirectHandler ¶
func (am *AuthManager) LoginRedirectHandler() func(*Ctx) *url.URL
LoginRedirectHandler returns the login redirect handler.
func (*AuthManager) Logout ¶
func (am *AuthManager) Logout(ctx *Ctx) error
Logout unauthenticates a session.
func (*AuthManager) PersistHandler ¶
func (am *AuthManager) PersistHandler() func(*Ctx, *Session, State) error
PersistHandler returns the persist handler.
func (*AuthManager) Redirect ¶
func (am *AuthManager) Redirect(ctx *Ctx) Result
Redirect returns a redirect result for when auth fails and you need to send the user to a login page.
func (*AuthManager) RemoveHandler ¶
func (am *AuthManager) RemoveHandler() func(sessionID string, state State) error
RemoveHandler returns the remove handler. It is used in validate session if the session is found to be invalid.
func (*AuthManager) Secret ¶
func (am *AuthManager) Secret() []byte
Secret returns the auth manager secret.
func (*AuthManager) SecureCookieName ¶
func (am *AuthManager) SecureCookieName() string
SecureCookieName returns the session param name.
func (*AuthManager) SessionCache ¶
func (am *AuthManager) SessionCache() *SessionCache
SessionCache returns the session cache.
func (*AuthManager) SessionTimeout ¶
func (am *AuthManager) SessionTimeout() time.Duration
SessionTimeout returns the session timeout.
func (*AuthManager) SessionTimeoutProvider ¶
func (am *AuthManager) SessionTimeoutProvider() func(rc *Ctx) *time.Time
SessionTimeoutProvider returns the session timeout provider.
func (*AuthManager) SesssionTimeoutIsAbsolute ¶
func (am *AuthManager) SesssionTimeoutIsAbsolute() bool
SesssionTimeoutIsAbsolute returns if the session timeout is absolute (vs. rolling).
func (*AuthManager) SesssionTimeoutIsRolling ¶
func (am *AuthManager) SesssionTimeoutIsRolling() bool
SesssionTimeoutIsRolling returns if the session timeout is absolute (vs. rolling).
func (*AuthManager) SetCookieHTTPSOnly ¶
func (am *AuthManager) SetCookieHTTPSOnly(isHTTPSOnly bool)
SetCookieHTTPSOnly overrides defaults when determining if we should use the HTTPS only cooikie option. The default depends on the app configuration (if tls is configured and enabled).
func (*AuthManager) SetCookieName ¶
func (am *AuthManager) SetCookieName(paramName string)
SetCookieName sets the session cookie name.
func (*AuthManager) SetCookiePath ¶
func (am *AuthManager) SetCookiePath(path string)
SetCookiePath sets the session cookie path.
func (*AuthManager) SetCookiesAsSessionBound ¶
func (am *AuthManager) SetCookiesAsSessionBound()
SetCookiesAsSessionBound sets the session issued cookies to be deleted after the browser closes.
func (*AuthManager) SetFetchHandler ¶
func (am *AuthManager) SetFetchHandler(handler func(sessionID string, state State) (*Session, error))
SetFetchHandler sets the fetch handler.
func (*AuthManager) SetLogger ¶
func (am *AuthManager) SetLogger(log *logger.Logger)
SetLogger sets the intance logger.
func (*AuthManager) SetLoginRedirectHandler ¶
func (am *AuthManager) SetLoginRedirectHandler(handler func(*Ctx) *url.URL)
SetLoginRedirectHandler sets the handler to determin where to redirect on not authorized attempts. It should return (nil) if you want to just show the `not_authorized` template, provided one is configured.
func (*AuthManager) SetPersistHandler ¶
func (am *AuthManager) SetPersistHandler(handler func(*Ctx, *Session, State) error)
SetPersistHandler sets the persist handler. It must be able to both create sessions and update sessions if the expiry changes.
func (*AuthManager) SetRemoveHandler ¶
func (am *AuthManager) SetRemoveHandler(handler func(sessionID string, state State) error)
SetRemoveHandler sets the remove handler. It should remove a session from the backing store by a string sessionID.
func (*AuthManager) SetSecret ¶
func (am *AuthManager) SetSecret(secret []byte)
SetSecret sets the secret for the auth manager.
func (*AuthManager) SetSecureCookieName ¶
func (am *AuthManager) SetSecureCookieName(paramName string)
SetSecureCookieName sets the session param name.
func (*AuthManager) SetSessionTimeout ¶
func (am *AuthManager) SetSessionTimeout(timeout time.Duration)
SetSessionTimeout sets the static value for session timeout.
func (*AuthManager) SetSessionTimeoutIsAbsolute ¶
func (am *AuthManager) SetSessionTimeoutIsAbsolute(isAbsolute bool)
SetSessionTimeoutIsAbsolute sets if the timeout for session should be an absolute (vs. rolling) time.
func (*AuthManager) SetSessionTimeoutProvider ¶
func (am *AuthManager) SetSessionTimeoutProvider(timeoutProvider func(rc *Ctx) *time.Time)
SetSessionTimeoutProvider sets the session to expire with a given the given timeout provider.
func (*AuthManager) SetUseSessionCache ¶
func (am *AuthManager) SetUseSessionCache(value bool)
SetUseSessionCache sets the `UseSessionCache` property to the value.
func (*AuthManager) SetValidateHandler ¶
func (am *AuthManager) SetValidateHandler(handler func(*Session, State) error)
SetValidateHandler sets the validate handler. This is an optional handler that will evaluate the session when verifying requests that are session aware.
func (*AuthManager) UseSessionCache ¶
func (am *AuthManager) UseSessionCache() bool
UseSessionCache returns if we should use the session cache.
func (*AuthManager) ValidateHandler ¶
func (am *AuthManager) ValidateHandler() func(*Session, State) error
ValidateHandler returns the validate handler.
func (*AuthManager) VerifySession ¶
func (am *AuthManager) VerifySession(ctx *Ctx) (*Session, error)
VerifySession checks a sessionID to see if it's valid. It also handles updating a rolling expiry.
func (*AuthManager) WithAbsoluteSessionTimeout ¶
func (am *AuthManager) WithAbsoluteSessionTimeout() *AuthManager
WithAbsoluteSessionTimeout sets if the session timeout is absolute (vs. rolling).
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) WithCookiesAsSessionBound ¶
func (am *AuthManager) WithCookiesAsSessionBound() *AuthManager
WithCookiesAsSessionBound sets cookies to be issued with `session` liveness.
func (*AuthManager) WithCookiesHTTPSOnly ¶
func (am *AuthManager) WithCookiesHTTPSOnly(isHTTPSOnly bool) *AuthManager
WithCookiesHTTPSOnly sets if we should issue cookies with the HTTPS flag on.
func (*AuthManager) WithFetchHandler ¶
func (am *AuthManager) WithFetchHandler(handler func(sessionID string, state State) (*Session, error)) *AuthManager
WithFetchHandler sets the fetch handler.
func (*AuthManager) WithLogger ¶
func (am *AuthManager) WithLogger(log *logger.Logger) *AuthManager
WithLogger sets the intance logger and returns a reference.
func (*AuthManager) WithLoginRedirectHandler ¶
func (am *AuthManager) WithLoginRedirectHandler(handler func(*Ctx) *url.URL) *AuthManager
WithLoginRedirectHandler sets the login redirect handler.
func (*AuthManager) WithPersistHandler ¶
func (am *AuthManager) WithPersistHandler(handler func(*Ctx, *Session, State) error) *AuthManager
WithPersistHandler sets the persist handler.
func (*AuthManager) WithRemoveHandler ¶
func (am *AuthManager) WithRemoveHandler(handler func(sessionID string, state State) error) *AuthManager
WithRemoveHandler sets the remove handler.
func (*AuthManager) WithRollingSessionTimeout ¶
func (am *AuthManager) WithRollingSessionTimeout() *AuthManager
WithRollingSessionTimeout sets if the session timeout to be rolling (i.e. rolling).
func (*AuthManager) WithSecret ¶
func (am *AuthManager) WithSecret(secret []byte) *AuthManager
WithSecret sets the secret for the auth manager.
func (*AuthManager) WithSecureCookieName ¶
func (am *AuthManager) WithSecureCookieName(paramName string) *AuthManager
WithSecureCookieName sets the secure cookie name.
func (*AuthManager) WithSessionTimeout ¶
func (am *AuthManager) WithSessionTimeout(timeout time.Duration) *AuthManager
WithSessionTimeout sets the either rolling or absolute session timeout.
func (*AuthManager) WithSessionTimeoutProvider ¶
func (am *AuthManager) WithSessionTimeoutProvider(timeoutProvider func(rc *Ctx) *time.Time) *AuthManager
WithSessionTimeoutProvider sets the session timeout provider.
func (*AuthManager) WithUseSessionCache ¶
func (am *AuthManager) WithUseSessionCache(value bool) *AuthManager
WithUseSessionCache sets if we should use the session cache.
func (*AuthManager) WithValidateHandler ¶
func (am *AuthManager) WithValidateHandler(handler func(*Session, State) error) *AuthManager
WithValidateHandler sets the validate handler.
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"` // HSTS determines if we should issue the Strict-Transport-Security header. HSTS *bool `json:"hsts,omitempty" yaml:"hsts,omitempty"` HSTSMaxAgeSeconds int `json:"hstsMaxAgeSeconds,omitempty" yaml:"hstsMaxAgeSeconds,omitempty"` HSTSIncludeSubDomains *bool `json:"hstsIncludeSubdomains,omitempty" yaml:"hstsIncludeSubdomains,omitempty"` HSTSPreload *bool `json:"hstsPreload,omitempty" yaml:"hstsPreload,omitempty"` // UseSessionCache enables or disables the in memory session cache. // Note: If the session cache is disabled you *must* provide a fetch handler. UseSessionCache *bool `json:"useSessionCache,omitempty" yaml:"useSessionCache,omitempty" env:"USE_SESSION_CACHE"` // 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"` // AuthSecret is a key to use to encrypt the sessionID as a second factor cookie. AuthSecret string `json:"authSecret,omitempty" yaml:"authSecret,omitempty" env:"AUTH_SECRET"` // SecureCookieHTTPS determines if we should flip the `https only` flag on issued secure cookies. SecureCookieHTTPSOnly *bool `json:"secureCookieHTTPSOnly,omitempty" yaml:"secureCookieHTTPSOnly,omitempty" env:"SECURE_COOKIE_HTTPS_ONLY"` // SecureCookieName is the name of the secure cookie to issue with sessions. SecureCookieName string `json:"secureCookieName,omitempty" yaml:"secureCookieName,omitempty" env:"SECURE_COOKIE_NAME"` // 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"` TLS TLSConfig `json:"tls,omitempty" yaml:"tls,omitempty"` Views ViewCacheConfig `json:"views,omitempty" yaml:"views,omitempty"` }
Config is an object used to set up a web app.
func NewConfigFromEnv ¶
func NewConfigFromEnv() *Config
NewConfigFromEnv returns a new config from the environment.
func (Config) BaseURLIsSecureScheme ¶
BaseURLIsSecureScheme returns if the base url starts with a secure scheme.
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) GetHSTSIncludeSubDomains ¶
GetHSTSIncludeSubDomains returns a property or a default.
func (Config) GetHSTSMaxAgeSeconds ¶
GetHSTSMaxAgeSeconds returns a property or a default.
func (Config) GetHSTSPreload ¶
GetHSTSPreload returns a property or a default.
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) GetSecureCookieHTTPSOnly ¶
GetSecureCookieHTTPSOnly returns a property or a default.
func (Config) GetSecureCookieName ¶
GetSecureCookieName returns a property or a default.
func (Config) GetSessionTimeout ¶
GetSessionTimeout returns a property or a default.
func (Config) GetSessionTimeoutIsAbsolute ¶
GetSessionTimeoutIsAbsolute returns a property or a default.
func (Config) GetUseSessionCache ¶
GetUseSessionCache returns a property or a default.
func (Config) GetWriteTimeout ¶
GetWriteTimeout gets a property.
type Controller ¶
type Controller interface {
Register(app *App)
}
Controller is an interface for controller objects.
type Ctx ¶
type Ctx struct {
// contains filtered or unexported fields
}
Ctx is the struct that represents the context for an hc request.
func NewCtx ¶
func NewCtx(w ResponseWriter, r *http.Request, p RouteParameters, s State) *Ctx
NewCtx returns a new hc context.
func (*Ctx) Background ¶
Background returns the background context for a request.
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) HeaderParam ¶
HeaderParam returns a header parameter value.
func (*Ctx) HeaderParamFloat64 ¶
HeaderParamFloat64 returns a header parameter value as an float64.
func (*Ctx) HeaderParamInt ¶
HeaderParamInt returns a header parameter value as an integer.
func (*Ctx) HeaderParamInt64 ¶
HeaderParamInt64 returns a header parameter value as an integer.
func (*Ctx) HeaderParamTime ¶
HeaderParamTime returns a header parameter value as an float64.
func (*Ctx) NoContent ¶
func (rc *Ctx) NoContent() *NoContentResult
NoContent returns a service response.
func (*Ctx) ParamFloat64 ¶
ParamFloat64 returns a parameter from any location as a float64.
func (*Ctx) ParamInt64 ¶
ParamInt64 returns a parameter from any location as an int64.
func (*Ctx) ParamString ¶
ParamString is a shortcut for ParamString that swallows the missing value error.
func (*Ctx) ParamTime ¶
ParamTime returns a parameter from any location as a time with a given format.
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) QueryParam ¶
QueryParam returns a query parameter.
func (*Ctx) QueryParamFloat64 ¶
QueryParamFloat64 returns a query parameter as a float64.
func (*Ctx) QueryParamInt ¶
QueryParamInt returns a query parameter as an integer.
func (*Ctx) QueryParamInt64 ¶
QueryParamInt64 returns a query parameter as an int64.
func (*Ctx) QueryParamTime ¶
QueryParamTime returns a query parameter as a time.Time.
func (*Ctx) RawWithContentType ¶
RawWithContentType returns a binary response with a given content type.
func (*Ctx) RedirectWithMethodf ¶
func (rc *Ctx) RedirectWithMethodf(method, format string, args ...interface{}) *RedirectResult
RedirectWithMethodf returns a redirect result with a given method.
func (*Ctx) Redirectf ¶
func (rc *Ctx) Redirectf(format string, args ...interface{}) *RedirectResult
Redirectf returns a redirect result.
func (*Ctx) Response ¶
func (rc *Ctx) Response() ResponseWriter
Response returns the underyling response.
func (*Ctx) RouteParam ¶
RouteParam returns a string route parameter
func (*Ctx) RouteParamFloat64 ¶
RouteParamFloat64 returns a route parameter as an float64.
func (*Ctx) RouteParamInt ¶
RouteParamInt returns a route parameter as an integer.
func (*Ctx) RouteParamInt64 ¶
RouteParamInt64 returns a route parameter as an integer.
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) 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) WithRequest ¶
WithRequest sets the underlying request.
func (*Ctx) WithResponse ¶
func (rc *Ctx) WithResponse(res ResponseWriter) *Ctx
WithResponse sets the underlying response.
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.
type Error ¶
type Error string
Error is a simple wrapper for strings to help with constant errors.
const ( // LenSessionID is the byte length of a session id. LenSessionID = 64 // LenSessionIDBase64 is the length of a session id base64 encoded. LenSessionIDBase64 = 88 // ErrSessionIDEmpty is thrown if a session id is empty. ErrSessionIDEmpty Error = "auth session id is empty" // ErrSessionIDTooLong is thrown if a session id is too long. ErrSessionIDTooLong Error = "auth session id is too long" // ErrSecureSessionIDEmpty is an error that is thrown if a given secure session id is invalid. ErrSecureSessionIDEmpty Error = "auth secure session id is empty" // ErrSecureSessionIDTooLong is an error that is thrown if a given secure session id is invalid. ErrSecureSessionIDTooLong Error = "auth secure session id is too long" // ErrSecureSessionIDInvalid is an error that is thrown if a given secure session id is invalid. ErrSecureSessionIDInvalid Error = "auth secure session id is invalid" // ErrUnsetViewTemplate is an error that is thrown if a given secure session id is invalid. ErrUnsetViewTemplate Error = "view result template is unset" )
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 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) BindAddr ¶
func (hu *HTTPSUpgrader) BindAddr() string
BindAddr returns the address the server will bind to.
func (*HTTPSUpgrader) IdleTimeout ¶
func (hu *HTTPSUpgrader) IdleTimeout() time.Duration
IdleTimeout is the time before we close a connection.
func (*HTTPSUpgrader) Logger ¶
func (hu *HTTPSUpgrader) Logger() *logger.Logger
Logger returns the underlying logger.
func (*HTTPSUpgrader) MaxHeaderBytes ¶
func (hu *HTTPSUpgrader) MaxHeaderBytes() int
MaxHeaderBytes returns the app max header bytes.
func (*HTTPSUpgrader) ReadHeaderTimeout ¶
func (hu *HTTPSUpgrader) ReadHeaderTimeout() time.Duration
ReadHeaderTimeout returns the read header timeout for the server.
func (*HTTPSUpgrader) ReadTimeout ¶
func (hu *HTTPSUpgrader) ReadTimeout() time.Duration
ReadTimeout returns the read timeout for the server.
func (*HTTPSUpgrader) ServeHTTP ¶
func (hu *HTTPSUpgrader) ServeHTTP(rw http.ResponseWriter, req *http.Request)
ServeHTTP redirects HTTP to HTTPS
func (*HTTPSUpgrader) Server ¶
func (hu *HTTPSUpgrader) Server() *http.Server
Server returns the basic http.Server for the app.
func (*HTTPSUpgrader) SetPort ¶
func (hu *HTTPSUpgrader) SetPort(port int32)
SetPort sets the port the app listens on, typically to `:%d` which indicates listen on any interface.
func (*HTTPSUpgrader) SetPortFromEnv ¶
func (hu *HTTPSUpgrader) SetPortFromEnv()
SetPortFromEnv sets the port from an environment variable, and returns a reference to the app.
func (*HTTPSUpgrader) Shutdown ¶
func (hu *HTTPSUpgrader) Shutdown() error
Shutdown stops the server.
func (*HTTPSUpgrader) Start ¶
func (hu *HTTPSUpgrader) Start() error
Start starts the server and binds to the given address.
func (*HTTPSUpgrader) StartWithServer ¶
func (hu *HTTPSUpgrader) StartWithServer(server *http.Server) (err error)
StartWithServer starts the app on a custom server. This lets you configure things like TLS keys and other options.
func (*HTTPSUpgrader) TargetPort ¶
func (hu *HTTPSUpgrader) TargetPort() int32
TargetPort returns the target upgrade port. It defaults to unset, or the https default of 443.
func (*HTTPSUpgrader) WithBindAddr ¶
func (hu *HTTPSUpgrader) WithBindAddr(bindAddr string) *HTTPSUpgrader
WithBindAddr sets the address the app listens on, and returns a reference to the app.
func (*HTTPSUpgrader) WithBindAddrFromEnv ¶
func (hu *HTTPSUpgrader) WithBindAddrFromEnv() *HTTPSUpgrader
WithBindAddrFromEnv sets the address the app listens on, and returns a reference to the app.
func (*HTTPSUpgrader) WithIdleTimeout ¶
func (hu *HTTPSUpgrader) WithIdleTimeout(timeout time.Duration) *HTTPSUpgrader
WithIdleTimeout sets the idle timeout.
func (*HTTPSUpgrader) WithLogger ¶
func (hu *HTTPSUpgrader) WithLogger(log *logger.Logger) *HTTPSUpgrader
WithLogger sets the underlying logger.
func (*HTTPSUpgrader) WithMaxHeaderBytes ¶
func (hu *HTTPSUpgrader) WithMaxHeaderBytes(byteCount int) *HTTPSUpgrader
WithMaxHeaderBytes sets the max header bytes value and returns a reference.
func (*HTTPSUpgrader) WithPort ¶
func (hu *HTTPSUpgrader) WithPort(port int32) *HTTPSUpgrader
WithPort sets the port for the bind address of the app, and returns a reference to the app.
func (*HTTPSUpgrader) WithPortFromEnv ¶
func (hu *HTTPSUpgrader) WithPortFromEnv() *HTTPSUpgrader
WithPortFromEnv sets the port from an environment variable, and returns a reference to the app.
func (*HTTPSUpgrader) WithReadHeaderTimeout ¶
func (hu *HTTPSUpgrader) WithReadHeaderTimeout(timeout time.Duration) *HTTPSUpgrader
WithReadHeaderTimeout returns the read header timeout for the server.
func (*HTTPSUpgrader) WithReadTimeout ¶
func (hu *HTTPSUpgrader) WithReadTimeout(timeout time.Duration) *HTTPSUpgrader
WithReadTimeout sets the read timeout for the server and returns a reference to the app for building apps with a fluent api.
func (*HTTPSUpgrader) WithTargetPort ¶
func (hu *HTTPSUpgrader) WithTargetPort(port int32) *HTTPSUpgrader
WithTargetPort sets the target upgrade port. It defaults to unset, or the https default of 443.
func (*HTTPSUpgrader) WithWriteTimeout ¶
func (hu *HTTPSUpgrader) WithWriteTimeout(timeout time.Duration) *HTTPSUpgrader
WithWriteTimeout sets the write timeout for the server and returns a reference to the app for building apps with a fluent api.
func (*HTTPSUpgrader) WriteTimeout ¶
func (hu *HTTPSUpgrader) WriteTimeout() time.Duration
WriteTimeout returns the write timeout for the server.
type HTTPSUpgraderConfig ¶
type HTTPSUpgraderConfig struct { Port int32 `json:"port" yaml:"port" env:"UPGRADE_PORT"` BindAddr string `json:"bindAddr" yaml:"bindAddr" env:"UPGRADE_BIND_ADDR"` TargetPort int32 `json:"targetPort" yaml:"targetPort" env:"UPGRADE_TARGET_PORT"` MaxHeaderBytes int `json:"maxHeaderBytes" yaml:"maxHeaderBytes" env:"MAX_HEADER_BYTES"` ReadTimeout time.Duration `json:"readTimeout" yaml:"readTimeout" env:"READ_HEADER_TIMEOUT"` ReadHeaderTimeout time.Duration `json:"readHeaderTimeout" yaml:"readHeaderTimeout" env:"READ_HEADER_TIMEOUT"` WriteTimeout time.Duration `json:"writeTimeout" yaml:"writeTimeout" env:"WRITE_TIMEOUT"` IdleTimeout time.Duration `json:"idleTimeout" yaml:"idleTimeout" env:"IDLE_TIMEOUT"` }
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) GetBindAddr ¶
func (c HTTPSUpgraderConfig) GetBindAddr(defaults ...string) string
GetBindAddr coalesces the bind addr, the port, or the default.
func (HTTPSUpgraderConfig) GetIdleTimeout ¶
func (c HTTPSUpgraderConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration
GetIdleTimeout gets a property.
func (HTTPSUpgraderConfig) GetMaxHeaderBytes ¶
func (c HTTPSUpgraderConfig) GetMaxHeaderBytes(defaults ...int) int
GetMaxHeaderBytes returns the maximum header size in bytes or a default.
func (HTTPSUpgraderConfig) GetPort ¶
func (c HTTPSUpgraderConfig) GetPort(defaults ...int32) int32
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 (HTTPSUpgraderConfig) GetReadHeaderTimeout ¶
func (c HTTPSUpgraderConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
GetReadHeaderTimeout gets a property.
func (HTTPSUpgraderConfig) GetReadTimeout ¶
func (c HTTPSUpgraderConfig) GetReadTimeout(defaults ...time.Duration) time.Duration
GetReadTimeout gets a property.
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.
func (HTTPSUpgraderConfig) GetWriteTimeout ¶
func (c HTTPSUpgraderConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration
GetWriteTimeout gets a property.
type Handler ¶
type Handler func(http.ResponseWriter, *http.Request, *Route, RouteParameters, State)
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. /varz - basic stats and metrics since start /debug/vars - `pkg/expvar` output.
func NewHealthzFromConfig ¶
func NewHealthzFromConfig(app *App, cfg *HealthzConfig) *Healthz
NewHealthzFromConfig returns a new healthz sidecar from a config.
func NewHealthzFromEnv ¶
NewHealthzFromEnv returns a new healthz from the env.
func (*Healthz) CreateServer ¶
CreateServer returns the basic http.Server for the app.
func (*Healthz) DefaultHeaders ¶
DefaultHeaders returns the default headers.
func (*Healthz) IdleTimeout ¶
IdleTimeout is the time before we close a connection.
func (*Healthz) Listener ¶
func (hz *Healthz) Listener() *net.TCPListener
Listener returns the underlying listener.
func (*Healthz) MaxHeaderBytes ¶
MaxHeaderBytes returns the app max header bytes.
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) SetPort ¶
SetPort sets the port the app listens on, typically to `:%d` which indicates listen on any interface.
func (*Healthz) SetPortFromEnv ¶
func (hz *Healthz) SetPortFromEnv()
SetPortFromEnv sets the port from an environment variable, and returns a reference to the app.
func (*Healthz) WithBindAddr ¶
WithBindAddr sets the address the app listens on, and returns a reference to the app.
func (*Healthz) WithBindAddrFromEnv ¶
WithBindAddrFromEnv sets the address the app listens on, and returns a reference to the app.
func (*Healthz) WithDefaultHeader ¶
WithDefaultHeader adds a default header.
func (*Healthz) WithDefaultHeaders ¶
WithDefaultHeaders sets the default headers
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) WithPort ¶
WithPort sets the port for the bind address of the app, and returns a reference to the app.
func (*Healthz) WithPortFromEnv ¶
WithPortFromEnv sets the port from an environment variable, and returns a reference to the app.
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) WithServer ¶
WithServer sets the underlying server.
func (*Healthz) WithState ¶
WithState sets app state and returns a reference to the app for building apps with a fluent api.
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 { Port int32 `json:"port" yaml:"port" env:"HEALTHZ_PORT"` BindAddr string `json:"bindAddr" yaml:"bindAddr" env:"HEALTHZ_BIND_ADDR"` // 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" yaml:"defaultHeaders"` RecoverPanics *bool `json:"recoverPanics" yaml:"recoverPanics"` MaxHeaderBytes int `json:"maxHeaderBytes" yaml:"maxHeaderBytes" env:"HEALTHZ_MAX_HEADER_BYTES"` ReadTimeout time.Duration `json:"readTimeout" yaml:"readTimeout" env:"HEALTHZ_READ_HEADER_TIMEOUT"` ReadHeaderTimeout time.Duration `json:"readHeaderTimeout" yaml:"readHeaderTimeout" env:"HEALTHZ_READ_HEADER_TIMEOUT"` WriteTimeout time.Duration `json:"writeTimeout" yaml:"writeTimeout" env:"HEALTHZ_WRITE_TIMEOUT"` IdleTimeout time.Duration `json:"idleTimeout" yaml:"idleTimeout" env:"HEALTHZ_IDLE_TIMEOUT"` }
HealthzConfig is an object used to set up a healthz sidecar.
func NewHealthzConfigFromEnv ¶
func NewHealthzConfigFromEnv() *HealthzConfig
NewHealthzConfigFromEnv returns a new config from the environment.
func (HealthzConfig) GetBindAddr ¶
func (hc HealthzConfig) GetBindAddr(defaults ...string) string
GetBindAddr util.Coalesces the bind addr, the port, or the default.
func (HealthzConfig) GetIdleTimeout ¶
func (hc HealthzConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration
GetIdleTimeout gets a property.
func (HealthzConfig) GetMaxHeaderBytes ¶
func (hc HealthzConfig) GetMaxHeaderBytes(defaults ...int) int
GetMaxHeaderBytes returns the maximum header size in bytes or a default.
func (HealthzConfig) GetPort ¶
func (hc HealthzConfig) GetPort(defaults ...int32) int32
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 (HealthzConfig) GetReadHeaderTimeout ¶
func (hc HealthzConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration
GetReadHeaderTimeout gets a property.
func (HealthzConfig) GetReadTimeout ¶
func (hc HealthzConfig) GetReadTimeout(defaults ...time.Duration) time.Duration
GetReadTimeout gets a property.
func (HealthzConfig) GetRecoverPanics ¶
func (hc HealthzConfig) GetRecoverPanics(defaults ...bool) bool
GetRecoverPanics returns if we should recover panics or not.
func (HealthzConfig) GetWriteTimeout ¶
func (hc HealthzConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration
GetWriteTimeout gets a property.
type JSONResult ¶
type JSONResult struct { StatusCode int Response interface{} }
JSONResult is a json result.
type JSONResultProvider ¶
type JSONResultProvider struct {
// contains filtered or unexported fields
}
JSONResultProvider are context results for api methods.
func NewJSONResultProvider ¶
func NewJSONResultProvider(log *logger.Logger) *JSONResultProvider
NewJSONResultProvider Creates a new JSONResults object.
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.
type Middleware ¶
Middleware are steps that run in order before a given action.
func SessionMiddleware ¶
func SessionMiddleware(notAuthorized Action, lockPolicy SessionLockPolicy) Middleware
SessionMiddleware creates a custom session middleware.
func Timeout ¶
func Timeout(d time.Duration) Middleware
Timeout 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) 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) WithTx ¶
func (mrb *MockRequestBuilder) WithTx(tx *sql.Tx, keys ...string) *MockRequestBuilder
WithTx sets the transaction for the request.
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 MockResponseWriter ¶
type MockResponseWriter struct {
// contains filtered or unexported fields
}
MockResponseWriter is an object that satisfies response writer but uses an internal buffer.
func NewMockResponseWriter ¶
func NewMockResponseWriter(buffer io.Writer) *MockResponseWriter
NewMockResponseWriter returns a mocked response writer.
func (*MockResponseWriter) Bytes ¶
func (res *MockResponseWriter) Bytes() []byte
Bytes returns the raw response.
func (*MockResponseWriter) ContentLength ¶
func (res *MockResponseWriter) ContentLength() int
ContentLength returns the content length.
func (*MockResponseWriter) Header ¶
func (res *MockResponseWriter) Header() http.Header
Header returns the response headers.
func (*MockResponseWriter) InnerResponse ¶
func (res *MockResponseWriter) InnerResponse() http.ResponseWriter
InnerResponse returns the backing httpresponse writer.
func (*MockResponseWriter) StatusCode ¶
func (res *MockResponseWriter) StatusCode() int
StatusCode returns the status code.
func (*MockResponseWriter) Write ¶
func (res *MockResponseWriter) Write(buffer []byte) (int, error)
Write writes data and adds to ContentLength.
func (*MockResponseWriter) WriteHeader ¶
func (res *MockResponseWriter) WriteHeader(statusCode int)
WriteHeader sets the status code.
type NoContentResult ¶
type NoContentResult struct{}
NoContentResult returns a no content response.
func (*NoContentResult) Render ¶
func (ncr *NoContentResult) Render(ctx *Ctx) error
Render renders a static result.
type NoContentResultProvider ¶
type NoContentResultProvider struct {
// contains filtered or unexported fields
}
NoContentResultProvider is a provider that returns `http.StatusNoContent` for all responses.
func (*NoContentResultProvider) BadRequest ¶
func (ncr *NoContentResultProvider) BadRequest(err error) Result
BadRequest returns a no content response.
func (*NoContentResultProvider) InternalError ¶
func (ncr *NoContentResultProvider) InternalError(err error) Result
InternalError returns a no content response.
func (*NoContentResultProvider) NotAuthorized ¶
func (ncr *NoContentResultProvider) NotAuthorized() Result
NotAuthorized returns a no content response.
func (*NoContentResultProvider) NotFound ¶
func (ncr *NoContentResultProvider) NotFound() Result
NotFound returns a no content response.
func (*NoContentResultProvider) Result ¶
func (ncr *NoContentResultProvider) Result(response interface{}) Result
Result returns a no content response.
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 Request ¶
type Request = Ctx
Request is an alias to Ctx. It is part of a longer term transition.
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 Result ¶
Result is the result of a controller.
func AuthManagerRedirect ¶
AuthManagerRedirect is a redirect.
type ResultProvider ¶
type ResultProvider interface { InternalError(err error) Result BadRequest(err error) Result NotFound() Result NotAuthorized() Result }
ResultProvider is the provider interface for results.
type RewriteAction ¶
RewriteAction is an action for a rewrite rule.
type RewriteRule ¶
type RewriteRule struct { MatchExpression string Action RewriteAction // contains filtered or unexported fields }
RewriteRule is a rule for re-writing incoming static urls.
type 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"` SessionID string `json:"sessionID" yaml:"sessionID"` CreatedUTC time.Time `json:"createdUTC" yaml:"createdUTC"` ExpiresUTC *time.Time `json:"expiresUTC" yaml:"expiresUTC"` State map[string]interface{} `json:"state,omitempty" yaml:"state,omitempty"` Mutex *sync.RWMutex `json:"-" yaml:"-"` }
Session is an active session
func NewSession ¶
NewSession returns a new session object.
type SessionCache ¶
SessionCache is a memory ledger of active sessions.
func NewSessionCache ¶
func NewSessionCache() *SessionCache
NewSessionCache returns a new session cache.
func (*SessionCache) Get ¶
func (sc *SessionCache) Get(sessionID string) *Session
Get gets a session.
func (*SessionCache) IsActive ¶
func (sc *SessionCache) IsActive(sessionID string) bool
IsActive returns if a sessionID is active.
func (*SessionCache) Remove ¶
func (sc *SessionCache) Remove(sessionID string)
Remove removes a session from the cache.
func (*SessionCache) Upsert ¶
func (sc *SessionCache) Upsert(session *Session)
Upsert adds or updates a session to the cache.
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 map[string]interface{}
State is the collection of state objects on a context.
type StateProvider ¶
type StateProvider interface {
State() State
}
StateProvider provide states, an example is Ctx
func WithTx ¶
func WithTx(sp StateProvider, tx *sql.Tx, keys ...string) StateProvider
WithTx sets a transaction on the state provider.
type StateValueProvider ¶
type StateValueProvider interface {
StateValue(key string) interface{}
}
StateValueProvider is a type that provides a state value.
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 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 {
// contains filtered or unexported fields
}
TextResultProvider is the default response provider if none is specified.
func NewTextResultProvider ¶
func NewTextResultProvider(log *logger.Logger) *TextResultProvider
NewTextResultProvider returns a new text result provider.
func (*TextResultProvider) BadRequest ¶
func (trp *TextResultProvider) BadRequest(err error) Result
BadRequest returns a text response.
func (*TextResultProvider) InternalError ¶
func (trp *TextResultProvider) InternalError(err error) Result
InternalError returns a text response.
func (*TextResultProvider) NotAuthorized ¶
func (trp *TextResultProvider) NotAuthorized() Result
NotAuthorized returns a text response.
func (*TextResultProvider) NotFound ¶
func (trp *TextResultProvider) NotFound() Result
NotFound returns a text response.
func (*TextResultProvider) Result ¶
func (trp *TextResultProvider) Result(response interface{}) Result
Result returns a plaintext result.
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 NewViewCacheWithTemplates ¶
NewViewCacheWithTemplates creates a new view cache wrapping the templates.
func (*ViewCache) AddLiterals ¶
AddLiterals adds view literal strings to the view collection.
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) SetCached ¶
SetCached 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) SetLiterals ¶
SetLiterals sets the raw views outright.
func (*ViewCache) SetTemplates ¶
SetTemplates sets the view cache for the app.
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"` }
ViewCacheConfig is a config for the view cache.
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) GetPaths ¶
func (vcc ViewCacheConfig) GetPaths(defaults ...[]string) []string
GetPaths returns default view paths.
type ViewModel ¶
type ViewModel struct { Ctx *Ctx ViewModel interface{} }
ViewModel is a wrapping viewmodel.
type ViewResult ¶
type ViewResult struct { StatusCode int ViewModel interface{} Template *template.Template Provider *ViewResultProvider }
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 ViewResultProvider ¶
type ViewResultProvider struct {
// contains filtered or unexported fields
}
ViewResultProvider returns results based on views.
func NewViewResultProvider ¶
func NewViewResultProvider(log *logger.Logger, vc *ViewCache) *ViewResultProvider
NewViewResultProvider creates a new ViewResults object.
func (*ViewResultProvider) BadRequest ¶
func (vr *ViewResultProvider) BadRequest(err error) Result
BadRequest returns a view result.
func (*ViewResultProvider) BadRequestTemplateName ¶
func (vr *ViewResultProvider) BadRequestTemplateName() string
BadRequestTemplateName returns the bad request template.
func (*ViewResultProvider) InternalError ¶
func (vr *ViewResultProvider) InternalError(err error) Result
InternalError returns a view result.
func (*ViewResultProvider) InternalErrorTemplateName ¶
func (vr *ViewResultProvider) InternalErrorTemplateName() string
InternalErrorTemplateName returns the bad request template.
func (*ViewResultProvider) NotAuthorized ¶
func (vr *ViewResultProvider) NotAuthorized() Result
NotAuthorized returns a view result.
func (*ViewResultProvider) NotAuthorizedTemplateName ¶
func (vr *ViewResultProvider) NotAuthorizedTemplateName() string
NotAuthorizedTemplateName returns the bad request template name.
func (*ViewResultProvider) NotFound ¶
func (vr *ViewResultProvider) NotFound() Result
NotFound returns a view result.
func (*ViewResultProvider) NotFoundTemplateName ¶
func (vr *ViewResultProvider) NotFoundTemplateName() string
NotFoundTemplateName returns the not found template name.
func (*ViewResultProvider) View ¶
func (vr *ViewResultProvider) View(viewName string, viewModel interface{}) Result
View returns a view result.
func (*ViewResultProvider) WithBadRequestTemplateName ¶
func (vr *ViewResultProvider) WithBadRequestTemplateName(templateName string) *ViewResultProvider
WithBadRequestTemplateName sets the bad request template.
func (*ViewResultProvider) WithInternalErrorTemplateName ¶
func (vr *ViewResultProvider) WithInternalErrorTemplateName(templateName string) *ViewResultProvider
WithInternalErrorTemplateName sets the bad request template.
func (*ViewResultProvider) WithNotAuthorizedTemplateName ¶
func (vr *ViewResultProvider) WithNotAuthorizedTemplateName(templateName string) *ViewResultProvider
WithNotAuthorizedTemplateName sets the bad request template.
func (*ViewResultProvider) WithNotFoundTemplateName ¶
func (vr *ViewResultProvider) WithNotFoundTemplateName(templateName string) *ViewResultProvider
WithNotFoundTemplateName sets the not found request template name.
type XMLResult ¶
type XMLResult struct { StatusCode int Response interface{} }
XMLResult is a json result.
type XMLResultProvider ¶
type XMLResultProvider struct {
// contains filtered or unexported fields
}
XMLResultProvider are context results for api methods.
func NewXMLResultProvider ¶
func NewXMLResultProvider(log *logger.Logger) *XMLResultProvider
NewXMLResultProvider Creates a new JSONResults object.
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(response interface{}) Result
Result returns an xml response.
Source Files
¶
- action.go
- app.go
- app_event.go
- app_start_delegate.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
- error.go
- fileserver.go
- healthz.go
- heathz_config.go
- https_upgrader.go
- https_upgrader_config.go
- json_result.go
- json_result_provider.go
- middleware.go
- mock_request_builder.go
- mock_response_writer.go
- no_content_result.go
- no_content_result_provider.go
- raw_response_writer.go
- raw_result.go
- redirect_result.go
- response_writer.go
- result.go
- result_provider.go
- rewrite_rule.go
- route.go
- route_parameters.go
- session.go
- session_cache.go
- session_middleware.go
- state.go
- static_file_server.go
- static_result.go
- tcp_keep_alive_listener.go
- text_result_provider.go
- tls_config.go
- tree.go
- util.go
- view_cache.go
- view_cache_config.go
- view_model.go
- view_result.go
- view_result_provider.go
- xml_result.go
- xml_result_provider.go