web

package
v1.0.0-b001 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2018 License: MIT Imports: 36 Imported by: 0

README

web

web is a lightweight framework for building web applications in go. It rolls together very tightly scoped middleware with API endpoint and view endpoint patterns.

Requirements

  • go 1.8+

Example

Let's say we have a controller we need to implement:

type FooController struct {}

func (fc FooContoller) Register(app *web.App) {
	app.GET("/bar", fc.bar)
}

func (fc FooController) barHandler(ctx *web.Ctx) web.Result {
	return ctx.Text().Result("bar!")
}

Then we would have the following in our main.go:

func main() {
	app := web.New()
	app.Register(new(FooController))
	app.Start() // note, this call blocks until the server exists / crashes.
}

And that's it! There are options to configure things like the port and tls certificates, but the core use case is to bind on 8080 or whatever is specified in the PORT environment variable.

Middleware

If you want to run some steps before controller actions fire (such as for auth etc.) you can add those steps as "middleware".

	app.GET("/admin/dashboard", c.dashboardAction, middle2, middle1)

This will then run middle1 and then run middle2, finally the controller action. An important detail is that the "cascading" nature of the calls depends on how you structure your middleware functions. If any of the middleware functions return without calling the action parameter, execution stops there and subsequent middleware steps do not get called (ditto the controller action). This lets us have authentication steps happen in common middlewares before our controller action gets run. It also lets us specify different middlewares per route.

What do middle1 and middle2 look like? They are Middleware; functions that take an Action and return an Action.

func middle1(action web.Action) web.Action {
	return func(ctx *web.Ctx) web.Result {
		// check if our "foo" param is correct.
		if ctx.Param("foo") != "bar" { // this is only for illustration, you'd want to do something more secure in practice
			return ctx.DefaultResultProvider().NotAuthorized() //.DefaultResultProvider() can be set by helper middlewares, otherwise defaults to `Text`
		}
		return action(ctx) //we call the input action here
	}
}

Authentication

go-web comes built in with some basic handling of authentication and a concept of session. With very basic configuration, middlewares can be added that either require a valid session, or simply read the session and provide it to the downstream controller action.

func main() {
	app := web.New()
	
	// Provide a session validation handler.
	// It is called after the session has been read off the request.
	app.Auth().SetValidateHandler(func(session *web.Session, state web.State) error {
		// here we might want to reach into our permanent session store and make sure the session is still valid
		return nil
	})

	// Provide a redirect handler if a session is required for a route.
	// This is simply a function that takes an incoming request url, and returns what it should be redirected to.
	// You can add as much logic here as you'd like, but below is a simple redirect that points people to a login page
	// with a param denoting where they were trying to go (useful for post-login).
	app.Auth().SetLoginRedirectHandler(func(u *url.URL) *url.URL {
		u.RawQuery = fmt.Sprintf("redirect=%s", url.QueryEscape(u.Path))
		u.Path = fmt.Sprintf("/login")
		return u
	})

	app.POST("/login", func(ctx *web.Ctx) web.Result {
		// if we've already got a session, exit early.
		if ctx.Session() != nil {
			return ctx.RedirectWithMethodf("GET", "/dashboard")
		}
		// audits, other events you might want to trigger.
		// Login(...) will issue cookies, and store the session in the local session cache
		// so we can validate it on subsequent requests.
		ctx.Auth().Login("my user id", ctx)
		return ctx.RedirectWithMethodf("GET", "/dashboard")
	}, web.SessionAware)

	app.GET("/logout", func(ctx *web.Ctx) web.Result {
		// if we don't already have a session, exit early.
		if ctx.Session() == nil {
			return ctx.RedirectWithMethodf("GET", "/login")
		}

		// audits, other events you might want to trigger.
		ctx.Auth().Logout(ctx)
		return ctx.RedirectWithMethodf("GET", "/login")
	}, web.SessionAware)
}

Serving Static Files

You can set a path root to serve static files.

func main() {
	app := web.New()
	app.ServeStatic("/static", "_client/dist")
	app.Start()
}

Here we tell the app that we should serve the _client/dist directory as a route prefixed by "/static". If we have a file foo.css in _client/dist, it would be accessible at /static/foo.css in our app.

You can also have a controller action return a static file:

	app.GET("/thing", func(r *web.Ctx) web.ControllerResult { return r.Static("path/to/my/file") })

You can optionally set a static re-write rule (such as if you are cache-breaking assets with timestamps in the filename):

func main() {
	app := web.New()
	app.ServeStatic("/static", "_client/dist")
	app.WithStaticRewriteRule("/static", `^(.*)\.([0-9]+)\.(css|js|html|htm)$`, func(path string, parts ...string) string {
		return fmt.Sprintf("%s.%s", parts[1], parts[3])
	})
	app.Start()
}

Here we feed the WithStaticRewriteRule function the path (the same path as our static file server, this is important), a regular expression to match, and a special handler function that returns an updated path.

Note: parts ...string is the regular expression sub matches from the expression, with parts[0] equal to the full input string. parts[1] and parts[3] in this case are the nominal root stem, and the extension respecitvely.

You can also set custom headers for static files:

func main() {
	app := web.New()
	app.ServeStatic("/static", "_client/dist")
	app.WithStaticRewriteRule("/static", `^(.*)\.([0-9]+)\.(css|js)$`, func(path string, parts ...string) string {
		return fmt.Sprintf("%s.%s", parts[1], parts[3])
	})
	app.WithStaticHeader("/static", "cache-control", "public,max-age=99999999")	
}

This will then set the specified cache headers on response for the static files, this is useful for things like cache-control.

You can finally set a static route to run middleware for that route.

func main() {
	app := web.New()
	app.ServeStatic("/static", "_client/dist")
	app.WithStaticRewriteRule("/static", `^(.*)\.([0-9]+)\.(css|js)$`, func(path string, parts ...string) string {
		return fmt.Sprintf("%s.%s", parts[1], parts[3])
	})
	app.WithStaticHeader("/static", "cache-control", "public,max-age=99999999")	
	app.WithStaticMiddleware("/static", web.SessionRequired)
}

You would now need to have a valid session to access any of the files under /static.

Benchmarks

Benchmarks are key, obviously, because the ~200us you save choosing a framework won't be wiped out by the 50ms ping time to your servers.

For a relatively clean implementation (found in benchmark/main.go) that uses go-web:

Running 10s test @ http://localhost:9090/json
  2 threads and 64 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     0.92ms  223.27us  11.82ms   86.00%
    Req/Sec    34.19k     2.18k   40.64k    65.35%
  687017 requests in 10.10s, 203.11MB read
Requests/sec:  68011.73
Transfer/sec:     20.11MB

On the same machine, with a very, very bare bones implementation using only built-in stuff in net/http:

Running 10s test @ http://localhost:9090/json
  2 threads and 64 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     0.93ms  216.64us  10.25ms   89.10%
    Req/Sec    34.22k     2.73k   40.63k    59.90%
  687769 requests in 10.10s, 109.54MB read
Requests/sec:  68091.37
Transfer/sec:     10.84MB

The key here is to make sure not to enable logging, because if logging is enabled that throughput gets cut in half.

Documentation

Index

Constants

View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
const (
	// SchemeHTTP is a protocol scheme.
	SchemeHTTP = "http"

	// SchemeHTTPS is a protocol scheme.
	SchemeHTTPS = "https"

	// SchemeSPDY is a protocol scheme.
	SchemeSPDY = "spdy"
)
View Source
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"
)
View Source
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"
)
View Source
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

View Source
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

View Source
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 = ""
)
View Source
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"
)
View Source
const (
	// DefaultTemplateNameBadRequest is the default template name for bad request view results.
	DefaultTemplateNameBadRequest = "bad_request"

	// DefaultTemplateNameInternalError is the default template name for internal server error view results.
	DefaultTemplateNameInternalError = "error"

	// DefaultTemplateNameNotFound is the default template name for not found error view results.
	DefaultTemplateNameNotFound = "not_found"

	// DefaultTemplateNameNotAuthorized is the default template name for not authorized error view results.
	DefaultTemplateNameNotAuthorized = "not_authorized"

	// 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>`
)
View Source
const (
	// DefaultTCPKeepAliveListenerPeriod is the default keep alive period for the tcp listener.
	DefaultTCPKeepAliveListenerPeriod = 3 * time.Minute
)
View Source
const (
	// StateKeyTx is the app state key for a transaction.
	StateKeyTx = "tx"
)

Variables

View Source
var (
	// BufferPool is a shared sync.Pool of bytes.Buffer instances.
	BufferPool = logger.NewBufferPool(32)
)

DefaultHeaders are the default headers added by go-web.

Functions

func Base64Decode

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

Base64Decode decodes a base64 string.

func Base64Encode

func Base64Encode(raw []byte) string

Base64Encode base64 encodes data.

func CleanPath

func CleanPath(p string) string

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

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

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

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

func DeserializeReaderAsJSON

func DeserializeReaderAsJSON(object interface{}, body io.ReadCloser) error

DeserializeReaderAsJSON deserializes a post body as json to a given object.

func EncodeSignSessionID

func EncodeSignSessionID(sessionID string, key []byte) (string, error)

EncodeSignSessionID returns a new secure session id base64 encoded..

func GenerateCryptoKey

func GenerateCryptoKey(keySize int) []byte

GenerateCryptoKey generates a cryptographic key.

func GenerateSHA512Key

func GenerateSHA512Key() []byte

GenerateSHA512Key generates a crypto key for SHA512 hashing.

func HealthzHost

func HealthzHost(app *App, hz *Healthz) (err error)

HealthzHost hosts an app with a healthz, starting both servers.

func IsErrSessionInvalid

func IsErrSessionInvalid(err error) bool

IsErrSessionInvalid returns if an error is a session invalid error.

func LocalIP

func LocalIP() string

LocalIP returns the local server ip.

func MustEncodeSignSessionID

func MustEncodeSignSessionID(sessionID string, key []byte) string

MustEncodeSignSessionID returns a signed sessionID as base64 encoded. It panics if there is an error.

func MustParseURL

func MustParseURL(rawURL string) *url.URL

MustParseURL parses a url and panics if there is an error.

func MustSignSessionID

func MustSignSessionID(sessionID string, key []byte) []byte

MustSignSessionID signs a session id and panics if there is an issue.

func NewAppEventListener

func NewAppEventListener(listener func(me *AppEvent)) logger.Listener

NewAppEventListener returns a new app start event listener.

func NewBasicCookie

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

NewBasicCookie returns a new name + value pair cookie.

func NewMockRequest

func NewMockRequest(method, path string) *http.Request

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 ParseInt32

func ParseInt32(v string) int32

ParseInt32 parses an int32.

func PortFromBindAddr

func PortFromBindAddr(bindAddr string) int32

PortFromBindAddr returns a port number as an integer from a bind addr.

func ReadSetCookieByName

func ReadSetCookieByName(h http.Header, name string) *http.Cookie

ReadSetCookieByName returns a set cookie by name.

func ReadSetCookies

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

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

func SignSessionID

func SignSessionID(sessionID string, key []byte) ([]byte, error)

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

func TxFromState(state State, keys ...string) *sql.Tx

TxFromState returns a tx from a state bag.

func WithTxForState

func WithTxForState(state State, tx *sql.Tx, keys ...string)

WithTxForState injects a tx into a statebag.

func WriteJSON

func WriteJSON(w http.ResponseWriter, r *http.Request, statusCode int, response interface{}) error

WriteJSON marshalls an object to json.

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.

func WriteXML

func WriteXML(w http.ResponseWriter, r *http.Request, statusCode int, response interface{}) error

WriteXML marshalls an object to json.

Types

type Action

type Action func(*Ctx) Result

Action is the function signature for controller actions.

func Cancel

func Cancel(action Action) Action

Cancel injects the context for a given action with a cancel func.

func JSONProviderAsDefault

func JSONProviderAsDefault(action Action) Action

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

func NestMiddleware

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

NestMiddleware reads the middleware variadic args and organizes the calls recursively in the order they appear.

func SessionAware

func SessionAware(action Action) Action

SessionAware is an action that injects the session into the context, it acquires a read lock on session.

func SessionAwareMutating

func SessionAwareMutating(action Action) Action

SessionAwareMutating is an action that injects the session into the context and requires a write lock.

func SessionAwareUnsafe

func SessionAwareUnsafe(action Action) Action

SessionAwareUnsafe is an action that injects the session into the context without acquiring any (read or write) locks.

func SessionRequired

func SessionRequired(action Action) Action

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

func SessionRequiredMutating

func SessionRequiredMutating(action Action) Action

SessionRequiredMutating is an action that requires the session to present and also requires a write lock.

func SessionRequiredUnsafe

func SessionRequiredUnsafe(action Action) Action

SessionRequiredUnsafe is an action that requires the session to present and does not acquire any (read or write) locks.

func TextProviderAsDefault

func TextProviderAsDefault(action Action) Action

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

func ViewProviderAsDefault

func ViewProviderAsDefault(action Action) Action

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

func XMLProviderAsDefault

func XMLProviderAsDefault(action Action) Action

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

type App

type App struct {
	// contains filtered or unexported fields
}

App is the server for the app.

func New

func New() *App

New returns a new app.

func NewFromConfig

func NewFromConfig(cfg *Config) *App

NewFromConfig returns a new app from a given config.

func NewFromEnv

func NewFromEnv() *App

NewFromEnv returns a new app from the environment.

func (*App) Auth

func (a *App) Auth() *AuthManager

Auth returns the session manager.

func (*App) BaseURL

func (a *App) BaseURL() *url.URL

BaseURL returns the domain for the app.

func (*App) BindAddr

func (a *App) BindAddr() string

BindAddr returns the address the server will bind to.

func (*App) CreateServer

func (a *App) CreateServer() *http.Server

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

func (a *App) DefaultHeaders() map[string]string

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) GetState

func (a *App) GetState(key string) interface{}

GetState gets app state element by key.

func (*App) HEAD

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

HEAD registers a HEAD request handler.

func (*App) HSTS

func (a *App) HSTS() bool

HSTS returns if strict transport security is enabled.

func (*App) HSTSIncludeSubdomains

func (a *App) HSTSIncludeSubdomains() bool

HSTSIncludeSubdomains returns if we should include subdomains in hsts.

func (*App) HSTSMaxAgeSeconds

func (a *App) HSTSMaxAgeSeconds() int

HSTSMaxAgeSeconds is the maximum lifetime browsers should honor the secure transport header.

func (*App) HSTSPreload

func (a *App) HSTSPreload() bool

HSTSPreload returns if we should preload hsts.

func (*App) Handle

func (a *App) Handle(method, path string, handler Handler)

Handle adds a raw handler at a given method and path.

func (*App) HandleMethodNotAllowed

func (a *App) HandleMethodNotAllowed() bool

HandleMethodNotAllowed returns if we should handle unhandled verbs.

func (*App) HandleOptions

func (a *App) HandleOptions() bool

HandleOptions returns if we should handle OPTIONS requests.

func (*App) IdleTimeout

func (a *App) IdleTimeout() time.Duration

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) Logger

func (a *App) Logger() *logger.Logger

Logger returns the diagnostics agent for the app.

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

func (a *App) MaxHeaderBytes() int

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

func (a *App) ReadHeaderTimeout() time.Duration

ReadHeaderTimeout returns the read header timeout for the server.

func (*App) ReadTimeout

func (a *App) ReadTimeout() time.Duration

ReadTimeout returns the read timeout for the server.

func (*App) RecoverPanics

func (a *App) RecoverPanics() bool

RecoverPanics returns if the app recovers panics.

func (*App) RedirectTrailingSlash

func (a *App) RedirectTrailingSlash() bool

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) Running

func (a *App) Running() (running bool)

Running returns if the app is running.

func (*App) ServeHTTP

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

ServeHTTP makes the router implement the http.Handler interface.

func (*App) ServeStatic

func (a *App) ServeStatic(route, filepath string)

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

func (a *App) ServeStaticCached(route, filepath string)

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) Server

func (a *App) Server() *http.Server

Server returns the underyling http server.

func (*App) SetBaseURL

func (a *App) SetBaseURL(baseURL *url.URL)

SetBaseURL sets the base url for the app.

func (*App) SetParsedBaseURL

func (a *App) SetParsedBaseURL(baseURL string) error

SetParsedBaseURL sets the BaseURL from a string.

func (*App) SetPort

func (a *App) SetPort(port int32)

SetPort sets the port the app listens on, typically to `:%d` which indicates listen on any interface.

func (*App) SetPortFromEnv

func (a *App) SetPortFromEnv() error

SetPortFromEnv sets the port from an environment variable, and returns a reference to the app.

func (*App) SetState

func (a *App) SetState(key string, value interface{})

SetState sets app state.

func (*App) SetStaticHeader

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

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

func (*App) 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

func (a *App) SetTLSCertPair(tlsCert, tlsKey []byte) error

SetTLSCertPair sets the app to use TLS with a given cert.

func (*App) SetTLSCertPairFromFiles

func (a *App) SetTLSCertPairFromFiles(tlsCertPath, tlsKeyPath string) error

SetTLSCertPairFromFiles reads a tls key pair from a given set of paths.

func (*App) SetTLSClientCertPool

func (a *App) SetTLSClientCertPool(certs ...[]byte) error

SetTLSClientCertPool set the client cert pool from a given set of pems.

func (*App) SetTLSConfig

func (a *App) SetTLSConfig(config *tls.Config)

SetTLSConfig sets the tls config.

func (*App) SetTLSFromEnv

func (a *App) SetTLSFromEnv() error

SetTLSFromEnv reads TLS settings from the environment.

func (*App) Shutdown

func (a *App) Shutdown() error

Shutdown stops the server.

func (*App) Start

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

Start starts the server and binds to the given address.

func (*App) Started

func (a *App) Started() <-chan struct{}

Started returns a channel signalling the app has started.

func (*App) StartupTasks

func (a *App) StartupTasks() error

StartupTasks runs common startup tasks.

func (*App) State

func (a *App) State() State

State is a bag for common app state.

func (*App) TLSConfig

func (a *App) TLSConfig() *tls.Config

TLSConfig returns the app tls config.

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) Views

func (a *App) Views() *ViewCache

Views returns the view cache.

func (*App) WithAuth

func (a *App) WithAuth(am *AuthManager) *App

WithAuth sets the auth manager.

func (*App) WithBaseURL

func (a *App) WithBaseURL(baseURL *url.URL) *App

WithBaseURL sets the `BaseURL` field and returns a reference to the app for building apps with a fluent api.

func (*App) WithBindAddr

func (a *App) WithBindAddr(bindAddr string) *App

WithBindAddr sets the address the app listens on, and returns a reference to the app.

func (*App) WithBindAddrFromEnv

func (a *App) WithBindAddrFromEnv() *App

WithBindAddrFromEnv sets the address the app listens on, and returns a reference to the app.

func (*App) WithConfig

func (a *App) WithConfig(cfg *Config) *App

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

func (a *App) WithDefaultHeader(key string, value string) *App

WithDefaultHeader adds a default header.

func (*App) WithDefaultHeaders

func (a *App) WithDefaultHeaders(headers map[string]string) *App

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) WithHSTS

func (a *App) WithHSTS(enabled bool) *App

WithHSTS enables or disables issuing the strict transport security header.

func (*App) WithHSTSIncludeSubdomains

func (a *App) WithHSTSIncludeSubdomains(includeSubdomains bool) *App

WithHSTSIncludeSubdomains sets if we should include subdomains in hsts.

func (*App) WithHSTSMaxAgeSeconds

func (a *App) WithHSTSMaxAgeSeconds(ageSeconds int) *App

WithHSTSMaxAgeSeconds sets the hsts max age seconds.

func (*App) WithHSTSPreload

func (a *App) WithHSTSPreload(preload bool) *App

WithHSTSPreload sets if we preload hsts.

func (*App) WithHandleMethodNotAllowed

func (a *App) WithHandleMethodNotAllowed(handle bool) *App

WithHandleMethodNotAllowed sets if we should handlem ethod not allowed.

func (*App) WithHandleOptions

func (a *App) WithHandleOptions(handle bool) *App

WithHandleOptions returns if we should handle OPTIONS requests.

func (*App) WithIdleTimeout

func (a *App) WithIdleTimeout(timeout time.Duration) *App

WithIdleTimeout sets the idle timeout.

func (*App) WithJSONResultProvider

func (a *App) WithJSONResultProvider(jrp *JSONResultProvider) *App

WithJSONResultProvider sets the json result provider.

func (*App) WithLogger

func (a *App) WithLogger(log *logger.Logger) *App

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

func (a *App) WithMaxHeaderBytes(byteCount int) *App

WithMaxHeaderBytes sets the max header bytes value and returns a reference.

func (*App) WithMethodNotAllowedHandler

func (a *App) WithMethodNotAllowedHandler(handler Action) *App

WithMethodNotAllowedHandler sets the not allowed handler.

func (*App) WithNotFoundHandler

func (a *App) WithNotFoundHandler(handler Action) *App

WithNotFoundHandler sets the not found handler.

func (*App) WithPanicAction

func (a *App) WithPanicAction(action PanicAction) *App

WithPanicAction sets the panic action.

func (*App) WithPort

func (a *App) WithPort(port int32) *App

WithPort sets the port for the bind address of the app, and returns a reference to the app.

func (*App) WithPortFromEnv

func (a *App) WithPortFromEnv() *App

WithPortFromEnv sets the port from an environment variable, and returns a reference to the app.

func (*App) WithReadHeaderTimeout

func (a *App) WithReadHeaderTimeout(timeout time.Duration) *App

WithReadHeaderTimeout returns the read header timeout for the server.

func (*App) WithReadTimeout

func (a *App) WithReadTimeout(timeout time.Duration) *App

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

func (a *App) WithRecoverPanics(value bool) *App

WithRecoverPanics sets if the app should recover panics.

func (*App) WithRedirectTrailingSlash

func (a *App) WithRedirectTrailingSlash(value bool) *App

WithRedirectTrailingSlash sets if we should redirect missing trailing slashes.

func (*App) WithServer

func (a *App) WithServer(server *http.Server) *App

WithServer sets the server.

func (*App) WithState

func (a *App) WithState(key string, value interface{}) *App

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

func (a *App) WithTLSConfig(config *tls.Config) *App

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) WithViews

func (a *App) WithViews(vc *ViewCache) *App

WithViews sets the view cache.

func (*App) WithWriteTimeout

func (a *App) WithWriteTimeout(timeout time.Duration) *App

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

func (a *App) WriteTimeout() time.Duration

WriteTimeout returns the write timeout for the server.

func (*App) XMLResultProvider

func (a *App) XMLResultProvider() *XMLResultProvider

XMLResultProvider returns the xml result provider.

type AppEvent

type AppEvent struct {
	*logger.EventMeta
	// contains filtered or unexported fields
}

AppEvent is an event.

func NewAppEvent

func NewAppEvent(flag logger.Flag) *AppEvent

NewAppEvent creates a new app start event.

func (AppEvent) App

func (ae AppEvent) App() *App

App returns the app reference.

func (*AppEvent) Elapsed

func (ae *AppEvent) Elapsed() time.Duration

Elapsed returns the elapsed time.

func (*AppEvent) Err

func (ae *AppEvent) Err() error

Err returns an underlying error.

func (AppEvent) Healthz

func (ae AppEvent) Healthz() *Healthz

Healthz returns the healthz reference.

func (AppEvent) Upgrader

func (ae AppEvent) Upgrader() *HTTPSUpgrader

Upgrader returns the https upgrader reference.

func (*AppEvent) WithAnnotation

func (ae *AppEvent) WithAnnotation(key, value string) *AppEvent

WithAnnotation adds an annotation to the event.

func (*AppEvent) WithApp

func (ae *AppEvent) WithApp(app *App) *AppEvent

WithApp sets the event app reference.

func (*AppEvent) WithElapsed

func (ae *AppEvent) WithElapsed(elapsed time.Duration) *AppEvent

WithElapsed sets the elapsed time on the event.

func (*AppEvent) WithErr

func (ae *AppEvent) WithErr(err error) *AppEvent

WithErr sets the event error.

func (*AppEvent) WithFlag

func (ae *AppEvent) WithFlag(flag logger.Flag) *AppEvent

WithFlag sets the flag.

func (*AppEvent) WithHeadings

func (ae *AppEvent) WithHeadings(headings ...string) *AppEvent

WithHeadings sets the headings.

func (*AppEvent) WithHealthz

func (ae *AppEvent) WithHealthz(hz *Healthz) *AppEvent

WithHealthz sets the event hz reference.

func (*AppEvent) WithLabel

func (ae *AppEvent) WithLabel(key, value string) *AppEvent

WithLabel sets a label on the event for later filtering.

func (*AppEvent) WithTimestamp

func (ae *AppEvent) WithTimestamp(ts time.Time) *AppEvent

WithTimestamp sets the timestamp.

func (*AppEvent) WithUpgrader

func (ae *AppEvent) WithUpgrader(upgrader *HTTPSUpgrader) *AppEvent

WithUpgrader sets the event hz reference.

func (*AppEvent) WriteJSON

func (ae *AppEvent) WriteJSON() logger.JSONObj

WriteJSON implements logger.JSONWritable.

func (*AppEvent) WriteText

func (ae *AppEvent) WriteText(tf logger.TextFormatter, buf *bytes.Buffer)

WriteText implements logger.TextWritable.

type AppStartDelegate

type AppStartDelegate func(app *App) error

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

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

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

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

func (c Config) BaseURLIsSecureScheme() bool

BaseURLIsSecureScheme returns if the base url starts with a secure scheme.

func (Config) GetAuthSecret

func (c Config) GetAuthSecret(defaults ...[]byte) []byte

GetAuthSecret returns a property or a default.

func (Config) GetBaseURL

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

GetBaseURL gets a property.

func (Config) GetBindAddr

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

GetBindAddr util.Coalesces the bind addr, the port, or the default.

func (Config) GetCookieHTTPSOnly

func (c Config) GetCookieHTTPSOnly(defaults ...bool) bool

GetCookieHTTPSOnly returns a property or a default.

func (Config) GetCookieName

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

GetCookieName returns a property or a default.

func (Config) GetCookiePath

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

GetCookiePath returns a property or a default.

func (Config) GetDefaultHeaders

func (c Config) GetDefaultHeaders(inherited ...map[string]string) map[string]string

GetDefaultHeaders returns the default headers from the config.

func (Config) GetHSTS

func (c Config) GetHSTS(inherited ...bool) bool

GetHSTS returns a property or a default.

func (Config) GetHSTSIncludeSubDomains

func (c Config) GetHSTSIncludeSubDomains(inherited ...bool) bool

GetHSTSIncludeSubDomains returns a property or a default.

func (Config) GetHSTSMaxAgeSeconds

func (c Config) GetHSTSMaxAgeSeconds(inherited ...int) int

GetHSTSMaxAgeSeconds returns a property or a default.

func (Config) GetHSTSPreload

func (c Config) GetHSTSPreload(inherited ...bool) bool

GetHSTSPreload returns a property or a default.

func (Config) GetHandleMethodNotAllowed

func (c Config) GetHandleMethodNotAllowed(defaults ...bool) bool

GetHandleMethodNotAllowed returns if we should handle method not allowed results.

func (Config) GetHandleOptions

func (c Config) GetHandleOptions(defaults ...bool) bool

GetHandleOptions returns if we should handle OPTIONS verb requests.

func (Config) GetIdleTimeout

func (c Config) GetIdleTimeout(defaults ...time.Duration) time.Duration

GetIdleTimeout gets a property.

func (Config) GetMaxHeaderBytes

func (c Config) GetMaxHeaderBytes(defaults ...int) int

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

func (Config) GetPort

func (c Config) 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 (Config) GetReadHeaderTimeout

func (c Config) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration

GetReadHeaderTimeout gets a property.

func (Config) GetReadTimeout

func (c Config) GetReadTimeout(defaults ...time.Duration) time.Duration

GetReadTimeout gets a property.

func (Config) GetRecoverPanics

func (c Config) GetRecoverPanics(defaults ...bool) bool

GetRecoverPanics returns if we should recover panics or not.

func (Config) GetRedirectTrailingSlash

func (c Config) GetRedirectTrailingSlash(defaults ...bool) bool

GetRedirectTrailingSlash returns if we automatically redirect for a missing trailing slash.

func (Config) GetSecureCookieHTTPSOnly

func (c Config) GetSecureCookieHTTPSOnly(defaults ...bool) bool

GetSecureCookieHTTPSOnly returns a property or a default.

func (Config) GetSecureCookieName

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

GetSecureCookieName returns a property or a default.

func (Config) GetSessionTimeout

func (c Config) GetSessionTimeout(defaults ...time.Duration) time.Duration

GetSessionTimeout returns a property or a default.

func (Config) GetSessionTimeoutIsAbsolute

func (c Config) GetSessionTimeoutIsAbsolute(defaults ...bool) bool

GetSessionTimeoutIsAbsolute returns a property or a default.

func (Config) GetUseSessionCache

func (c Config) GetUseSessionCache(defaults ...bool) bool

GetUseSessionCache returns a property or a default.

func (Config) GetWriteTimeout

func (c Config) GetWriteTimeout(defaults ...time.Duration) time.Duration

GetWriteTimeout gets a property.

func (Config) IsSecure

func (c Config) IsSecure() bool

IsSecure returns if the config specifies the app will eventually be handling https requests.

func (Config) ListenTLS

func (c Config) ListenTLS() bool

ListenTLS returns if the server will directly serve requests with tls.

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) App

func (rc *Ctx) App() *App

App returns the app reference.

func (*Ctx) Auth

func (rc *Ctx) Auth() *AuthManager

Auth returns the AuthManager for the request.

func (*Ctx) Background

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

Background returns the background context for a request.

func (*Ctx) Cancel

func (rc *Ctx) Cancel()

Cancel calls the cancel func if it's set.

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) Elapsed

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

Elapsed is the time delta between start and end.

func (*Ctx) ExpireCookie

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

ExpireCookie expires a cookie.

func (*Ctx) ExtendCookie

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

ExtendCookie extends a cookie by years, months or days.

func (*Ctx) ExtendCookieByDuration

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

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

func (*Ctx) GetCookie

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

GetCookie returns a named cookie from the request.

func (*Ctx) HeaderParam

func (rc *Ctx) HeaderParam(key string) (string, error)

HeaderParam returns a header parameter value.

func (*Ctx) HeaderParamFloat64

func (rc *Ctx) HeaderParamFloat64(key string) (float64, error)

HeaderParamFloat64 returns a header parameter value as an float64.

func (*Ctx) HeaderParamInt

func (rc *Ctx) HeaderParamInt(key string) (int, error)

HeaderParamInt returns a header parameter value as an integer.

func (*Ctx) HeaderParamInt64

func (rc *Ctx) HeaderParamInt64(key string) (int64, error)

HeaderParamInt64 returns a header parameter value as an integer.

func (*Ctx) HeaderParamTime

func (rc *Ctx) HeaderParamTime(key, format string) (time.Time, error)

HeaderParamTime returns a header parameter value as an float64.

func (*Ctx) JSON

func (rc *Ctx) JSON() *JSONResultProvider

JSON returns the JSON result provider.

func (*Ctx) Logger

func (rc *Ctx) Logger() *logger.Logger

Logger returns the diagnostics agent.

func (*Ctx) NoContent

func (rc *Ctx) NoContent() *NoContentResult

NoContent returns a service response.

func (*Ctx) Param

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

Param returns a parameter from the request.

func (*Ctx) ParamBool

func (rc *Ctx) ParamBool(name string) (bool, error)

ParamBool returns a boolean value for a param.

func (*Ctx) ParamFloat64

func (rc *Ctx) ParamFloat64(name string) (float64, error)

ParamFloat64 returns a parameter from any location as a float64.

func (*Ctx) ParamInt

func (rc *Ctx) ParamInt(name string) (int, error)

ParamInt returns a parameter from any location as an integer.

func (*Ctx) ParamInt64

func (rc *Ctx) ParamInt64(name string) (int64, error)

ParamInt64 returns a parameter from any location as an int64.

func (*Ctx) ParamString

func (rc *Ctx) ParamString(name string) string

ParamString is a shortcut for ParamString that swallows the missing value error.

func (*Ctx) ParamTime

func (rc *Ctx) ParamTime(name, format string) (time.Time, error)

ParamTime returns a parameter from any location as a time with a given format.

func (*Ctx) PostBody

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

PostBody returns the bytes in a post body.

func (*Ctx) PostBodyAsJSON

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

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

func (*Ctx) PostBodyAsString

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

PostBodyAsString returns the post body as a string.

func (*Ctx) PostBodyAsXML

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

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

func (*Ctx) PostedFiles

func (rc *Ctx) PostedFiles() ([]PostedFile, error)

PostedFiles returns any files posted

func (*Ctx) QueryParam

func (rc *Ctx) QueryParam(key string) (string, error)

QueryParam returns a query parameter.

func (*Ctx) QueryParamFloat64

func (rc *Ctx) QueryParamFloat64(key string) (float64, error)

QueryParamFloat64 returns a query parameter as a float64.

func (*Ctx) QueryParamInt

func (rc *Ctx) QueryParamInt(key string) (int, error)

QueryParamInt returns a query parameter as an integer.

func (*Ctx) QueryParamInt64

func (rc *Ctx) QueryParamInt64(key string) (int64, error)

QueryParamInt64 returns a query parameter as an int64.

func (*Ctx) QueryParamTime

func (rc *Ctx) QueryParamTime(key, format string) (time.Time, error)

QueryParamTime returns a query parameter as a time.Time.

func (*Ctx) Raw

func (rc *Ctx) Raw(body []byte) *RawResult

Raw returns a binary response body, sniffing the content type.

func (*Ctx) RawWithContentType

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

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) Request

func (rc *Ctx) Request() *http.Request

Request returns the underlying request.

func (*Ctx) Response

func (rc *Ctx) Response() ResponseWriter

Response returns the underyling response.

func (*Ctx) Route

func (rc *Ctx) Route() *Route

Route returns the original route match for the request.

func (*Ctx) RouteParam

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

RouteParam returns a string route parameter

func (*Ctx) RouteParamFloat64

func (rc *Ctx) RouteParamFloat64(key string) (float64, error)

RouteParamFloat64 returns a route parameter as an float64.

func (*Ctx) RouteParamInt

func (rc *Ctx) RouteParamInt(key string) (int, error)

RouteParamInt returns a route parameter as an integer.

func (*Ctx) RouteParamInt64

func (rc *Ctx) RouteParamInt64(key string) (int64, error)

RouteParamInt64 returns a route parameter as an integer.

func (*Ctx) Session

func (rc *Ctx) Session() *Session

Session returns the session (if any) on the request.

func (Ctx) Start

func (rc Ctx) Start() time.Time

Start returns the request start time.

func (*Ctx) State

func (rc *Ctx) State() State

State returns the full state bag.

func (*Ctx) StateValue

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

StateValue returns an object in the state cache.

func (*Ctx) Static

func (rc *Ctx) Static(filePath string) *StaticResult

Static returns a static result.

func (*Ctx) Text

func (rc *Ctx) Text() *TextResultProvider

Text returns the text result provider.

func (*Ctx) View

func (rc *Ctx) View() *ViewResultProvider

View returns the view result provider.

func (*Ctx) WithApp

func (rc *Ctx) WithApp(app *App) *Ctx

WithApp sets the app reference for the ctx.

func (*Ctx) WithAuth

func (rc *Ctx) WithAuth(authManager *AuthManager) *Ctx

WithAuth sets the request context auth.

func (*Ctx) WithContext

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

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

func (rc *Ctx) WithRequest(req *http.Request) *Ctx

WithRequest sets the underlying request.

func (*Ctx) WithResponse

func (rc *Ctx) WithResponse(res ResponseWriter) *Ctx

WithResponse sets the underlying response.

func (*Ctx) WithSession

func (rc *Ctx) WithSession(session *Session) *Ctx

WithSession sets the session for the request.

func (*Ctx) WithStateValue

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

WithStateValue sets the state for a key to an object.

func (*Ctx) WithTx

func (rc *Ctx) WithTx(tx *sql.Tx, optionalKey ...string) *Ctx

WithTx sets a transaction on the context.

func (*Ctx) WriteCookie

func (rc *Ctx) WriteCookie(cookie *http.Cookie)

WriteCookie writes the cookie to the response.

func (*Ctx) WriteNewCookie

func (rc *Ctx) WriteNewCookie(name string, value string, expires *time.Time, path string, secure bool)

WriteNewCookie is a helper method for WriteCookie.

func (*Ctx) XML

func (rc *Ctx) XML() *XMLResultProvider

XML returns the xml result provider.

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"
)

func (Error) Error

func (e Error) Error() string

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

Handler is the most basic route handler.

func WrapHandler

func WrapHandler(handler http.Handler) Handler

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 NewHealthz

func NewHealthz(app *App) *Healthz

NewHealthz returns a new healthz.

func NewHealthzFromConfig

func NewHealthzFromConfig(app *App, cfg *HealthzConfig) *Healthz

NewHealthzFromConfig returns a new healthz sidecar from a config.

func NewHealthzFromEnv

func NewHealthzFromEnv(app *App) *Healthz

NewHealthzFromEnv returns a new healthz from the env.

func (*Healthz) App

func (hz *Healthz) App() *App

App returns the underlying app.

func (*Healthz) BindAddr

func (hz *Healthz) BindAddr() string

BindAddr returns the address the server will bind to.

func (*Healthz) CreateServer

func (hz *Healthz) CreateServer() *http.Server

CreateServer returns the basic http.Server for the app.

func (*Healthz) DefaultHeaders

func (hz *Healthz) DefaultHeaders() map[string]string

DefaultHeaders returns the default headers.

func (*Healthz) Err

func (hz *Healthz) Err() error

Err returns any errors that are generated before app start.

func (*Healthz) GetState

func (hz *Healthz) GetState(key string) interface{}

GetState gets app state element by key.

func (*Healthz) IdleTimeout

func (hz *Healthz) IdleTimeout() time.Duration

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) Logger

func (hz *Healthz) Logger() *logger.Logger

Logger returns the diagnostics agent for the app.

func (*Healthz) MaxHeaderBytes

func (hz *Healthz) MaxHeaderBytes() int

MaxHeaderBytes returns the app max header bytes.

func (*Healthz) ReadHeaderTimeout

func (hz *Healthz) ReadHeaderTimeout() time.Duration

ReadHeaderTimeout returns the read header timeout for the server.

func (*Healthz) ReadTimeout

func (hz *Healthz) ReadTimeout() time.Duration

ReadTimeout returns the read timeout for the server.

func (*Healthz) RecoverPanics

func (hz *Healthz) RecoverPanics() bool

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) Server

func (hz *Healthz) Server() *http.Server

Server returns the underlying server.

func (*Healthz) SetPort

func (hz *Healthz) SetPort(port int32)

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) SetState

func (hz *Healthz) SetState(key string, value interface{})

SetState sets app state.

func (*Healthz) Shutdown

func (hz *Healthz) Shutdown() error

Shutdown stops the server.

func (*Healthz) Start

func (hz *Healthz) Start() (err error)

Start starts the server.

func (*Healthz) State

func (hz *Healthz) State() State

State is a bag for common app state.

func (*Healthz) Vars

func (hz *Healthz) Vars() State

Vars returns the underlying vars collection.

func (*Healthz) WithBindAddr

func (hz *Healthz) WithBindAddr(bindAddr string) *Healthz

WithBindAddr sets the address the app listens on, and returns a reference to the app.

func (*Healthz) WithBindAddrFromEnv

func (hz *Healthz) WithBindAddrFromEnv() *Healthz

WithBindAddrFromEnv sets the address the app listens on, and returns a reference to the app.

func (*Healthz) WithDefaultHeader

func (hz *Healthz) WithDefaultHeader(key string, value string) *Healthz

WithDefaultHeader adds a default header.

func (*Healthz) WithDefaultHeaders

func (hz *Healthz) WithDefaultHeaders(headers map[string]string) *Healthz

WithDefaultHeaders sets the default headers

func (*Healthz) WithErr

func (hz *Healthz) WithErr(err error) *Healthz

WithErr sets the err that will abort app start.

func (*Healthz) WithIdleTimeout

func (hz *Healthz) WithIdleTimeout(timeout time.Duration) *Healthz

WithIdleTimeout sets the idle timeout.

func (*Healthz) WithLogger

func (hz *Healthz) WithLogger(log *logger.Logger) *Healthz

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

func (hz *Healthz) WithMaxHeaderBytes(byteCount int) *Healthz

WithMaxHeaderBytes sets the max header bytes value and returns a reference.

func (*Healthz) WithPort

func (hz *Healthz) WithPort(port int32) *Healthz

WithPort sets the port for the bind address of the app, and returns a reference to the app.

func (*Healthz) WithPortFromEnv

func (hz *Healthz) WithPortFromEnv() *Healthz

WithPortFromEnv sets the port from an environment variable, and returns a reference to the app.

func (*Healthz) WithReadHeaderTimeout

func (hz *Healthz) WithReadHeaderTimeout(timeout time.Duration) *Healthz

WithReadHeaderTimeout returns the read header timeout for the server.

func (*Healthz) WithReadTimeout

func (hz *Healthz) WithReadTimeout(timeout time.Duration) *Healthz

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

func (hz *Healthz) WithRecoverPanics(value bool) *Healthz

WithRecoverPanics sets if the app should recover panics.

func (*Healthz) WithServer

func (hz *Healthz) WithServer(server *http.Server) *Healthz

WithServer sets the underlying server.

func (*Healthz) WithState

func (hz *Healthz) WithState(key string, value interface{}) *Healthz

WithState sets app state and returns a reference to the app for building apps with a fluent api.

func (*Healthz) WithWriteTimeout

func (hz *Healthz) WithWriteTimeout(timeout time.Duration) *Healthz

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

func (hz *Healthz) WriteTimeout() time.Duration

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.

func (*JSONResult) Render

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

Render renders the 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

type Middleware func(Action) Action

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) Close

func (res *MockResponseWriter) Close() error

Close is a no-op.

func (*MockResponseWriter) ContentLength

func (res *MockResponseWriter) ContentLength() int

ContentLength returns the content length.

func (*MockResponseWriter) Flush

func (res *MockResponseWriter) Flush() error

Flush is a no-op.

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

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

PanicAction is a receiver for app.PanicHandler.

type PanicHandler

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

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

type PostedFile

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

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

type 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 RawResult

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

RawResult is for when you just want to dump bytes.

func (*RawResult) Render

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

Render renders the result.

type RedirectResult

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

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

func (*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

type ResponseMeta struct {
	StatusCode    int
	ContentLength int64
	Headers       http.Header
}

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

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

Result is the result of a controller.

func AuthManagerRedirect

func AuthManagerRedirect(ctx *Ctx) Result

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

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

RewriteAction is an action for a rewrite rule.

type RewriteRule

type RewriteRule struct {
	MatchExpression string

	Action RewriteAction
	// contains filtered or unexported fields
}

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

func (RewriteRule) Apply

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

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

type Route

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

Route is an entry in the route tree.

func (Route) String

func (r Route) String() string

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

type RouteParameters

type RouteParameters map[string]string

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

func (RouteParameters) Get

func (rp RouteParameters) Get(key string) string

Get gets a value for a key.

func (RouteParameters) Has

func (rp RouteParameters) Has(key string) bool

Has returns if the collection has a key or not.

func (RouteParameters) Set

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

Set stores a value for a key.

type 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

func NewSession(userID string, sessionID string) *Session

NewSession returns a new session object.

func (*Session) IsExpired

func (s *Session) IsExpired() bool

IsExpired returns if the session is expired.

func (*Session) IsZero

func (s *Session) IsZero() bool

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

func (*Session) Lock

func (s *Session) Lock()

Lock locks the session.

func (*Session) RLock

func (s *Session) RLock()

RLock read locks the session.

func (*Session) RUnlock

func (s *Session) RUnlock()

RUnlock read unlocks the session.

func (*Session) Unlock

func (s *Session) Unlock()

Unlock unlocks the session.

type SessionCache

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

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.

func (TCPKeepAliveListener) Accept

func (ln TCPKeepAliveListener) Accept() (net.Conn, error)

Accept accepts the connection.

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

func (tc TLSConfig) GetCAPaths(defaults ...[]string) []string

GetCAPaths returns a list of ca paths to add.

func (TLSConfig) GetCert

func (tc TLSConfig) GetCert(defaults ...[]byte) []byte

GetCert returns a tls cert.

func (TLSConfig) GetCertPath

func (tc TLSConfig) GetCertPath(defaults ...string) string

GetCertPath returns a tls cert path.

func (TLSConfig) GetConfig

func (tc TLSConfig) GetConfig() (*tls.Config, error)

GetConfig returns a stdlib tls config for the config.

func (TLSConfig) GetKey

func (tc TLSConfig) GetKey(defaults ...[]byte) []byte

GetKey returns a tls key.

func (TLSConfig) GetKeyPath

func (tc TLSConfig) GetKeyPath(defaults ...string) string

GetKeyPath returns a tls key path.

func (TLSConfig) HasKeyPair

func (tc TLSConfig) HasKeyPair() bool

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 NewViewCache

func NewViewCache() *ViewCache

NewViewCache returns a new view cache.

func NewViewCacheFromConfig

func NewViewCacheFromConfig(cfg *ViewCacheConfig) *ViewCache

NewViewCacheFromConfig returns a new view cache from a config.

func NewViewCacheWithTemplates

func NewViewCacheWithTemplates(templates *template.Template) *ViewCache

NewViewCacheWithTemplates creates a new view cache wrapping the templates.

func (*ViewCache) AddLiterals

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

AddLiterals adds view literal strings to the view collection.

func (*ViewCache) AddPaths

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

AddPaths adds paths to the view collection.

func (*ViewCache) Cached

func (vc *ViewCache) Cached() bool

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) FuncMap

func (vc *ViewCache) FuncMap() template.FuncMap

FuncMap returns the global view func map.

func (*ViewCache) Initialize

func (vc *ViewCache) Initialize() error

Initialize caches templates by path.

func (*ViewCache) Initialized

func (vc *ViewCache) Initialized() bool

Initialized returns if the viewcache is initialized.

func (*ViewCache) Parse

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

Parse parses the view tree.

func (*ViewCache) Paths

func (vc *ViewCache) Paths() []string

Paths returns the view paths.

func (*ViewCache) SetCached

func (vc *ViewCache) SetCached(cached bool)

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

func (vc *ViewCache) SetLiterals(viewLiterals ...string)

SetLiterals sets the raw views outright.

func (*ViewCache) SetPaths

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

SetPaths sets the view paths outright.

func (*ViewCache) SetTemplates

func (vc *ViewCache) SetTemplates(viewCache *template.Template)

SetTemplates sets the view cache for the app.

func (*ViewCache) Templates

func (vc *ViewCache) Templates() *template.Template

Templates gets 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.

func (*ViewModel) Env

func (vm *ViewModel) Env(key string, defaults ...string) string

Env returns a value from the environment.

func (*ViewModel) HasEnv

func (vm *ViewModel) HasEnv(key string) bool

HasEnv returns if an env var is set.

func (*ViewModel) UUIDv4

func (vm *ViewModel) UUIDv4() string

UUIDv4 returns a uuidv4 as a string.

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.

func (*XMLResult) Render

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

Render renders the 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.

Directories

Path Synopsis
clean command
echo command
_examples
api command
auth command
basic command
healthz command
logging command
middleware command
static command
upgrades command
views command

Jump to

Keyboard shortcuts

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