web

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2018 License: MIT Imports: 35 Imported by: 15

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

Overview

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

To create a new server, simply instantiate one:

import "log"
import "github.com/blend/go-sdk/web"

...

app := web.New()
app.GET("/", func(_ *web.Ctx) web.Result {
	return web.Text.Result("hello world")
})

if err := web.StartWithGracefulShutdown(app); err != nil {
	log.Fatal(err)
}

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

There are many more examples in the `_examples` directory.

Index

Constants

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"

	// HeaderUserAgent is the user agent header.
	HeaderUserAgent = "User-Agent"

	// HeaderVary is the "Vary" header.
	// It is used to indicate what fields should be used by the client as cache keys.
	HeaderVary = "Vary"

	// HeaderXServedBy is the "X-Served-By" header.
	// It is an informational header that indicates what software was used to generate the response.
	HeaderXServedBy = "X-Served-By"

	// HeaderXFrameOptions is the "X-Frame-Options" header.
	// It indicates if a browser is allowed to render the response in a <frame> element or not.
	HeaderXFrameOptions = "X-Frame-Options"

	// HeaderXXSSProtection is the "X-Xss-Protection" header.
	// It is a feature of internet explorer, and indicates if the browser should allow
	// requests across domain boundaries.
	HeaderXXSSProtection = "X-Xss-Protection"

	// HeaderXContentTypeOptions is the "X-Content-Type-Options" header.
	HeaderXContentTypeOptions = "X-Content-Type-Options"

	// HeaderStrictTransportSecurity is the hsts header.
	HeaderStrictTransportSecurity = "Strict-Transport-Security"

	// ContentTypeApplicationJSON is a content type for JSON responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeApplicationJSON = "application/json; charset=UTF-8"

	// ContentTypeHTML is a content type for html responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeHTML = "text/html; charset=utf-8"

	//ContentTypeXML is a content type for XML responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeXML = "text/xml; charset=utf-8"

	// ContentTypeText is a content type for text responses.
	// We specify chartset=utf-8 so that clients know to use the UTF-8 string encoding.
	ContentTypeText = "text/plain; charset=utf-8"

	// ConnectionKeepAlive is a value for the "Connection" header and
	// indicates the server should keep the tcp connection open
	// after the last byte of the response is sent.
	ConnectionKeepAlive = "keep-alive"

	// ContentEncodingIdentity is the identity (uncompressed) content encoding.
	ContentEncodingIdentity = "identity"
	// ContentEncodingGZIP is the gzip (compressed) content encoding.
	ContentEncodingGZIP = "gzip"
)
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"
	// DefaultIntegrationBindAddr is a bind address used for integration testing.
	DefaultIntegrationBindAddr = "127.0.0.1:0"
	// DefaultRedirectTrailingSlash is the default if we should redirect for missing trailing slashes.
	DefaultRedirectTrailingSlash = true
	// DefaultHandleOptions is a default.
	DefaultHandleOptions = false
	// DefaultHandleMethodNotAllowed is a default.
	DefaultHandleMethodNotAllowed = false
	// DefaultRecoverPanics returns if we should recover panics by default.
	DefaultRecoverPanics = true

	// DefaultHSTS is the default for if hsts is enabled.
	DefaultHSTS = true
	// DefaultHSTSMaxAgeSeconds is the default hsts max age seconds.
	DefaultHSTSMaxAgeSeconds = 31536000
	// DefaultHSTSIncludeSubDomains is a default.
	DefaultHSTSIncludeSubDomains = true
	// DefaultHSTSPreload is a default.
	DefaultHSTSPreload = true
	// DefaultMaxHeaderBytes is a default that is unset.
	DefaultMaxHeaderBytes = 0
	// DefaultReadTimeout is a default.
	DefaultReadTimeout = 5 * time.Second
	// DefaultReadHeaderTimeout is a default.
	DefaultReadHeaderTimeout time.Duration = 0
	// DefaultWriteTimeout is a default.
	DefaultWriteTimeout time.Duration = 0
	// DefaultIdleTimeout is a default.
	DefaultIdleTimeout time.Duration = 0
	// DefaultCookieName is the default name of the field that contains the session id.
	DefaultCookieName = "SID"
	// DefaultSecureCookieName is the default name of the field that contains the secure session id.
	DefaultSecureCookieName = "SSID"
	// DefaultCookiePath is the default cookie path.
	DefaultCookiePath = "/"
	// DefaultSessionTimeout is the default absolute timeout for a session (24 hours as a sane default).
	DefaultSessionTimeout time.Duration = 24 * time.Hour
	// DefaultUseSessionCache is the default if we should use the auth manager session cache.
	DefaultUseSessionCache = true
	// DefaultSessionTimeoutIsAbsolute is the default if we should set absolute session expiries.
	DefaultSessionTimeoutIsAbsolute = true

	// DefaultHTTPSUpgradeTargetPort is the default upgrade target port.
	DefaultHTTPSUpgradeTargetPort = 443

	// DefaultShutdownGracePeriod is the default shutdown grace period.
	DefaultShutdownGracePeriod = 30 * time.Second

	// DefaultHealthzFailureThreshold is the default healthz failure threshold.
	DefaultHealthzFailureThreshold = 3

	// DefaultBufferPoolSize is the default buffer pool size.
	DefaultViewBufferPoolSize = 256
)

Defaults

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.
)
View Source
const (
	// LenSessionID is the byte length of a session id.
	LenSessionID = 64
	// LenSessionIDBase64 is the length of a session id base64 encoded.
	LenSessionIDBase64 = 88
)
View Source
const (
	TestTLSCert = `` /* 1094-byte string literal not displayed */

	TestTLSKey = `` /* 1674-byte string literal not displayed */

)

test keys

View Source
const (
	// ErrSessionIDEmpty is thrown if a session id is empty.
	ErrSessionIDEmpty exception.Class = "auth session id is empty"
	// ErrSecureSessionIDEmpty is an error that is thrown if a given secure session id is invalid.
	ErrSecureSessionIDEmpty exception.Class = "auth secure session id is empty"
	// ErrUnsetViewTemplate is an error that is thrown if a given secure session id is invalid.
	ErrUnsetViewTemplate exception.Class = "view result template is unset"

	// ErrParameterMissing is an error on request validation.
	ErrParameterMissing exception.Class = "parameter is missing"
)
View Source
const (
	// ListenerHealthz is the uid of the healthz logger listeners.
	ListenerHealthz = "healthz"

	// ErrHealthzAppUnset is a common error.
	ErrHealthzAppUnset exception.Class = "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"
	// DefaultTemplateNameStatus is the default template name for status view results.
	DefaultTemplateNameStatus = "status"

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

Variables

DefaultHeaders are the default headers added by go-web.

View Source
var GracefulShutdown = graceful.Shutdown

GracefulShutdown shuts an app down gracefull. It is an alias to graceful.Shutdown

View Source
var StartWithGracefulShutdown = graceful.Shutdown

StartWithGracefulShutdown shuts an app down gracefull. It is an alias to graceful.Shutdown

Functions

func Base64URLDecode

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

Base64URLDecode decodes a base64 string.

func Base64URLEncode

func Base64URLEncode(raw []byte) string

Base64URLEncode base64 encodes data.

func BoolValue

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

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

func CSVValue

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

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

func CleanPath

func CleanPath(p string) string

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

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

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

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

func DurationValue

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

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

func Float64Value

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

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

func Int64Value

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

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

func IntValue

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

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

func IsErrSessionInvalid

func IsErrSessionInvalid(err error) bool

IsErrSessionInvalid returns if an error is a session invalid error.

func NewAppEventListener

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

NewAppEventListener returns a new app start event listener.

func NewCookie

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

NewCookie returns a new name + value pair cookie.

func NewCtxID added in v0.3.2

func NewCtxID() string

NewCtxID returns a pseudo-unique key for a context.

func NewSessionID

func NewSessionID() string

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

func ParseInt32

func ParseInt32(v string) int32

ParseInt32 parses an int32.

func PathRedirectHandler

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

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

func ReadSetCookies

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

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

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

func ResultOrDefault

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

ResultOrDefault returns a result or a default.

func SessionTimeoutProvider

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

SessionTimeoutProvider returns a new session timeout provider.

func SessionTimeoutProviderAbsolute

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

SessionTimeoutProviderAbsolute returns an absolute session timeout.

func SessionTimeoutProviderRolling

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

SessionTimeoutProviderRolling returns a rolling session timeout.

func StringValue

func StringValue(value string, _ error) string

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

Types

type Action

type Action func(*Ctx) Result

Action is the function signature for controller actions.

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 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 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 Any

type Any = interface{}

Any is an alias to the empty interface.

type App

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

App is the server for the app.

func MustNewFromEnv

func MustNewFromEnv() *App

MustNewFromEnv returns a new app with a config set from environment variabales, and it will panic if there is an error.

func 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, error)

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

func (a *App) Config() *Config

Config returns the app config.

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.

Routes should be registered in the form:

app.GET("/myroute", myAction, myMiddleware...)

It is important to note that routes are registered in order and cannot have any wildcards inside the routes.

func (*App) HEAD

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

HEAD registers a HEAD request handler.

func (*App) HSTS

func (a *App) HSTS() *HSTSConfig

HSTS returns the hsts config.

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

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

Handler returns either a custom handler or the app.

func (*App) IdleTimeout

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

IdleTimeout is the time before we close a connection.

func (*App) IsRunning

func (a *App) IsRunning() bool

IsRunning returns if the app is running.

func (*App) Latch

func (a *App) Latch() *async.Latch

Latch returns the app lifecycle latch.

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

func (a *App) MethodNotAllowedHandler() Handler

MethodNotAllowedHandler returns the method not allowed handler.

func (*App) Mock

func (a *App) Mock() *MockRequestBuilder

Mock returns a request bulider to facilitate mocking requests against the app without having to start it and bind it to a port.

An example mock request that hits an already registered "GET" route at "/foo":

assert.Nil(app.Mock().Get("/").Execute())

This will assert that the request completes successfully, but does not return the response.

func (*App) NotFoundHandler

func (a *App) NotFoundHandler() Handler

NotFoundHandler returns the not found handler.

func (*App) NotifyStarted

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

NotifyStarted returns the notify started chan.

func (*App) NotifyStopped added in v0.3.1

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

NotifyStopped returns the notify stopped chan.

func (*App) OPTIONS

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

OPTIONS registers a OPTIONS request handler.

func (*App) PATCH

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

PATCH registers a PATCH request handler.

func (*App) POST

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

POST registers a POST request actions.

func (*App) PUT

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

PUT registers a PUT request handler.

func (*App) PanicAction

func (a *App) PanicAction() PanicAction

PanicAction returns the panic action.

func (*App) ReadHeaderTimeout

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

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

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

func (*App) Shutdown

func (a *App) Shutdown() error

Shutdown is an alias to stop, and stops the server.

func (*App) ShutdownGracePeriod

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

ShutdownGracePeriod is the grace period on shutdown.

func (*App) Start

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

Start starts the server and binds to the given address.

func (*App) StartupTasks

func (a *App) StartupTasks() error

StartupTasks runs common startup tasks.

func (*App) State

func (a *App) State() State

State is a bag for common app state.

func (*App) StateValue

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

StateValue gets app state element by key.

func (*App) Stop added in v0.3.1

func (a *App) Stop() error

Stop stops the server.

func (*App) TLSConfig

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

TLSConfig returns the app tls config.

func (*App) Tracer

func (a *App) Tracer() Tracer

Tracer returns the tracer.

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

func (a *App) WithDefaultMiddlewares(middleware ...Middleware) *App

WithDefaultMiddlewares sets the application wide default middleware.

func (*App) WithDefaultResultProvider

func (a *App) WithDefaultResultProvider(drp ResultProvider) *App

WithDefaultResultProvider sets the default result provider.

func (*App) WithHSTS

func (a *App) WithHSTS(hsts *HSTSConfig) *App

WithHSTS enables or disables issuing the strict transport security header.

func (*App) WithHandleMethodNotAllowed

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

func (a *App) WithHandler(handler http.Handler) *App

WithHandler sets the handler.

func (*App) WithIdleTimeout

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

WithIdleTimeout sets the idle timeout.

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

func (a *App) WithShutdownGracePeriod(gracePeriod time.Duration) *App

WithShutdownGracePeriod sets the shutdown grace period.

func (*App) WithStateValue

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

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

func (*App) WithTLSClientCertVerification

func (a *App) WithTLSClientCertVerification(verification tls.ClientAuthType) *App

WithTLSClientCertVerification sets the verification level for client certs.

func (*App) WithTLSConfig

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

WithTLSConfig sets the tls config for the app.

func (*App) WithTracer

func (a *App) WithTracer(tracer Tracer) *App

WithTracer sets the tracer.

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

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

WriteTimeout returns the write timeout for the server.

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 AuthManager

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

AuthManager is a manager for sessions.

func NewAuthManagerFromConfig

func NewAuthManagerFromConfig(cfg *Config) (manager *AuthManager)

NewAuthManagerFromConfig returns a new auth manager from a given config.

func NewJWTAuthManager

func NewJWTAuthManager(key []byte) *AuthManager

NewJWTAuthManager returns a new jwt session manager. It issues JWT tokens to identify users.

func NewLocalAuthManager

func NewLocalAuthManager() *AuthManager

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

func NewServerAuthManager

func NewServerAuthManager() *AuthManager

NewServerAuthManager returns a new server auth manager. You should set the `FetchHandler`, the `PersistHandler` and the `RemoveHandler`.

func (*AuthManager) CookieName

func (am *AuthManager) CookieName() string

CookieName returns the session param name.

func (*AuthManager) CookiePath

func (am *AuthManager) CookiePath() string

CookiePath returns the session param path.

func (*AuthManager) CookiesHTTPSOnly

func (am *AuthManager) CookiesHTTPSOnly() bool

CookiesHTTPSOnly returns if the cookie is for only https connections.

func (*AuthManager) FetchHandler

func (am *AuthManager) FetchHandler() AuthManagerFetchHandler

FetchHandler returns the fetch handler. It is used in `VerifySession` to satisfy session cache misses.

func (*AuthManager) Login

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

Login logs a userID in.

func (*AuthManager) LoginRedirect

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

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

func (*AuthManager) LoginRedirectHandler

func (am *AuthManager) LoginRedirectHandler() AuthManagerRedirectHandler

LoginRedirectHandler returns the login redirect handler.

func (*AuthManager) Logout

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

Logout unauthenticates a session.

func (*AuthManager) ParseSessionValueHandler

func (am *AuthManager) ParseSessionValueHandler() AuthManagerParseSessionValueHandler

ParseSessionValueHandler returns the parse session value handler.

func (*AuthManager) PersistHandler

func (am *AuthManager) PersistHandler() AuthManagerPersistHandler

PersistHandler returns the persist handler.

func (*AuthManager) PostLoginRedirect

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

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

func (*AuthManager) PostLoginRedirectHandler

func (am *AuthManager) PostLoginRedirectHandler() AuthManagerRedirectHandler

PostLoginRedirectHandler returns the redirect handler for login complete.

func (*AuthManager) RemoveHandler

func (am *AuthManager) RemoveHandler() AuthManagerRemoveHandler

RemoveHandler returns the remove handler. It is used in validate session if the session is found to be invalid.

func (*AuthManager) SerializeSessionValueHandler

func (am *AuthManager) SerializeSessionValueHandler() AuthManagerSerializeSessionValueHandler

SerializeSessionValueHandler returns the serialize session value handler.

func (*AuthManager) SessionTimeoutProvider

func (am *AuthManager) SessionTimeoutProvider() func(*Session) time.Time

SessionTimeoutProvider returns the session timeout provider.

func (*AuthManager) ValidateHandler

func (am *AuthManager) ValidateHandler() AuthManagerValidateHandler

ValidateHandler returns the validate handler.

func (*AuthManager) VerifySession

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

VerifySession checks a sessionID to see if it's valid. It also handles updating a rolling expiry.

func (*AuthManager) WithCookieHTTPSOnly

func (am *AuthManager) WithCookieHTTPSOnly(isHTTPSOnly bool) *AuthManager

WithCookieHTTPSOnly sets if we should issue cookies with the HTTPS flag on.

func (*AuthManager) WithCookieName

func (am *AuthManager) WithCookieName(paramName string) *AuthManager

WithCookieName sets the cookie name.

func (*AuthManager) WithCookiePath

func (am *AuthManager) WithCookiePath(path string) *AuthManager

WithCookiePath sets the cookie path.

func (*AuthManager) WithFetchHandler

func (am *AuthManager) WithFetchHandler(handler AuthManagerFetchHandler) *AuthManager

WithFetchHandler sets the fetch handler.

func (*AuthManager) WithLoginRedirectHandler

func (am *AuthManager) WithLoginRedirectHandler(handler AuthManagerRedirectHandler) *AuthManager

WithLoginRedirectHandler sets the login redirect handler.

func (*AuthManager) WithParseSessionValueHandler

func (am *AuthManager) WithParseSessionValueHandler(handler AuthManagerParseSessionValueHandler) *AuthManager

WithParseSessionValueHandler sets the parse session value handler.

func (*AuthManager) WithPersistHandler

func (am *AuthManager) WithPersistHandler(handler AuthManagerPersistHandler) *AuthManager

WithPersistHandler sets the persist handler.

func (*AuthManager) WithPostLoginRedirectHandler

func (am *AuthManager) WithPostLoginRedirectHandler(handler AuthManagerRedirectHandler) *AuthManager

WithPostLoginRedirectHandler sets the post login redirect handler.

func (*AuthManager) WithRemoveHandler

func (am *AuthManager) WithRemoveHandler(handler AuthManagerRemoveHandler) *AuthManager

WithRemoveHandler sets the remove handler.

func (*AuthManager) WithSerializeSessionValueHandler

func (am *AuthManager) WithSerializeSessionValueHandler(handler AuthManagerSerializeSessionValueHandler) *AuthManager

WithSerializeSessionValueHandler sets the serialize session value handler.

func (*AuthManager) WithSessionTimeoutProvider

func (am *AuthManager) WithSessionTimeoutProvider(timeoutProvider func(*Session) time.Time) *AuthManager

WithSessionTimeoutProvider sets the session timeout provider.

func (*AuthManager) WithValidateHandler

func (am *AuthManager) WithValidateHandler(handler AuthManagerValidateHandler) *AuthManager

WithValidateHandler sets the validate handler.

type AuthManagerFetchHandler

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

AuthManagerFetchHandler fetches a session based on a session value.

type AuthManagerMode

type AuthManagerMode string

AuthManagerMode is an auth manager mode.

const (
	// AuthManagerModeJWT is the jwt auth mode.
	AuthManagerModeJWT AuthManagerMode = "jwt"
	// AuthManagerModeServer is the server managed auth mode.
	AuthManagerModeServer AuthManagerMode = "server"
	// AuthManagerModeLocal is the local cache auth mode.
	AuthManagerModeLocal AuthManagerMode = "cached"
)

type AuthManagerParseSessionValueHandler

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

AuthManagerParseSessionValueHandler deserializes a session from a string.

type AuthManagerPersistHandler

type AuthManagerPersistHandler func(context.Context, *Session, State) error

AuthManagerPersistHandler saves the session to a stable store.

type AuthManagerRedirectHandler

type AuthManagerRedirectHandler func(*Ctx) *url.URL

AuthManagerRedirectHandler is a redirect handler.

type AuthManagerRemoveHandler

type AuthManagerRemoveHandler func(context.Context, string, State) error

AuthManagerRemoveHandler removes a session based on a session value.

type AuthManagerSerializeSessionValueHandler

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

AuthManagerSerializeSessionValueHandler serializes a session as a string.

type AuthManagerSessionTimeoutProvider

type AuthManagerSessionTimeoutProvider func(*Session) time.Time

AuthManagerSessionTimeoutProvider provides a new timeout for a session.

type AuthManagerValidateHandler

type AuthManagerValidateHandler func(context.Context, *Session, State) error

AuthManagerValidateHandler validates a session.

type BufferPool

type BufferPool struct {
	sync.Pool
}

BufferPool is a sync.Pool of bytes.Buffer.

func NewBufferPool

func NewBufferPool(bufferSize int) *BufferPool

NewBufferPool returns a new BufferPool.

func (*BufferPool) Get

func (bp *BufferPool) Get() *bytes.Buffer

Get returns a pooled bytes.Buffer instance.

func (*BufferPool) Put

func (bp *BufferPool) Put(b *bytes.Buffer)

Put returns the pooled instance.

type CachedStaticFile

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

	// AuthManagerMode is a mode designation for the auth manager.
	AuthManagerMode string `json:"authManagerMode" yaml:"authManagerMode"`
	// AuthSecret is a secret key to use with auth management.
	AuthSecret string `json:"authSecret" yaml:"authSecret" env:"AUTH_SECRET"`
	// SessionTimeout is a fixed duration to use when calculating hard or rolling deadlines.
	SessionTimeout time.Duration `json:"sessionTimeout,omitempty" yaml:"sessionTimeout,omitempty" env:"SESSION_TIMEOUT"`
	// SessionTimeoutIsAbsolute determines if the session timeout is a hard deadline or if it gets pushed forward with usage.
	// The default is to use a hard deadline.
	SessionTimeoutIsAbsolute *bool `json:"sessionTimeoutIsAbsolute,omitempty" yaml:"sessionTimeoutIsAbsolute,omitempty" env:"SESSION_TIMEOUT_ABSOLUTE"`
	// CookieHTTPS determines if we should flip the `https only` flag on issued cookies.
	CookieHTTPSOnly *bool `json:"cookieHTTPSOnly,omitempty" yaml:"cookieHTTPSOnly,omitempty" env:"COOKIE_HTTPS_ONLY"`
	// CookieName is the name of the cookie to issue with sessions.
	CookieName string `json:"cookieName,omitempty" yaml:"cookieName,omitempty" env:"COOKIE_NAME"`
	// CookiePath is the path on the cookie to issue with sessions.
	CookiePath string `json:"cookiePath,omitempty" yaml:"cookiePath,omitempty" env:"COOKIE_PATH"`

	// DefaultHeaders are included on any responses. The app ships with a set of default headers, which you can augment with this property.
	DefaultHeaders map[string]string `json:"defaultHeaders,omitempty" yaml:"defaultHeaders,omitempty"`

	MaxHeaderBytes    int           `json:"maxHeaderBytes,omitempty" yaml:"maxHeaderBytes,omitempty" env:"MAX_HEADER_BYTES"`
	ReadTimeout       time.Duration `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty" env:"READ_HEADER_TIMEOUT"`
	ReadHeaderTimeout time.Duration `json:"readHeaderTimeout,omitempty" yaml:"readHeaderTimeout,omitempty" env:"READ_HEADER_TIMEOUT"`
	WriteTimeout      time.Duration `json:"writeTimeout,omitempty" yaml:"writeTimeout,omitempty" env:"WRITE_TIMEOUT"`
	IdleTimeout       time.Duration `json:"idleTimeout,omitempty" yaml:"idleTimeout,omitempty" env:"IDLE_TIMEOUT"`

	ShutdownGracePeriod time.Duration `json:"shutdownGracePeriod" yaml:"shutdownGracePeriod" env:"SHUTDOWN_GRACE_PERIOD"`

	HSTS  HSTSConfig      `json:"hsts,omitempty" yaml:"hsts,omitempty"`
	TLS   TLSConfig       `json:"tls,omitempty" yaml:"tls,omitempty"`
	Views ViewCacheConfig `json:"views,omitempty" yaml:"views,omitempty"`

	Healthz HealthzConfig `json:"healthz,omitempty" yaml:"healthz,omitempty"`
}

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

func MustNewConfigFromEnv

func MustNewConfigFromEnv() *Config

MustNewConfigFromEnv returns a new config from environment variables, and will panic on error.

func NewConfigFromEnv

func NewConfigFromEnv() (*Config, error)

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

func (c Config) GetAuthManagerMode(inherited ...string) AuthManagerMode

GetAuthManagerMode returns the auth manager mode.

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

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

GetShutdownGracePeriod gets the shutdown grace period.

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.

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

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

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

type Ctx

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

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

func NewCtx

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

NewCtx returns a new ctx.

func NewMockCtx

func NewMockCtx(method, path string) *Ctx

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

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

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

Context returns the context.

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

func (rc Ctx) End() time.Time

End returns the end request time.

func (*Ctx) ExpireCookie

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

ExpireCookie expires a cookie.

func (*Ctx) ExtendCookie

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

ExtendCookie extends a cookie by years, months or days.

func (*Ctx) ExtendCookieByDuration

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

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

func (*Ctx) FormValue

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

FormValue returns a form value.

func (*Ctx) GetCookie

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

GetCookie returns a named cookie from the request.

func (*Ctx) HeaderValue

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

HeaderValue returns a header value.

func (*Ctx) ID

func (rc *Ctx) ID() string

ID returns a pseudo unique id for the request.

func (*Ctx) JSON

func (rc *Ctx) JSON() JSONResultProvider

JSON returns the JSON result provider.

It can be eschewed for:

return web.JSON.Result(foo)

But is left in place for legacy reasons.

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

It checks, in order:

  • RouteParam
  • QueryValue
  • HeaderValue
  • FormValue
  • CookieValue

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

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

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

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

func (*Ctx) PostBody

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

PostBody 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) QueryValue

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

QueryValue returns a query value.

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

func (rc *Ctx) Redirect(destination string) *RedirectResult

Redirect returns a redirect result to a given destination.

func (*Ctx) RedirectWithMethod

func (rc *Ctx) RedirectWithMethod(method, destination string) *RedirectResult

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

func (*Ctx) RedirectWithMethodf

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

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

func (*Ctx) Redirectf

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

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

func (*Ctx) 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) (output string, err error)

RouteParam returns a string route parameter

func (*Ctx) RouteParams

func (rc *Ctx) RouteParams() RouteParameters

RouteParams returns the route parameters for the request.

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 start request time.

func (*Ctx) State

func (rc *Ctx) State() State

State returns the state.

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.

It can be eschewed for:

return web.Text.Result(foo)

But is left in place for legacy reasons.

func (*Ctx) Tracer

func (rc *Ctx) Tracer() Tracer

Tracer returns the tracer.

func (*Ctx) View

func (rc *Ctx) View() *ViewCache

View returns the view cache as a result provider.

It returns a reference to the view cache where views can either be read from disk for every request (uncached) or read from an in-memory cache.

To return a web result for a view with the name "index" simply return:

return r.View().View("index", myViewmodel)

It is important to not you'll want to have loaded the "index" view at some point in the application bootstrap (typically when you register your controller).

func (*Ctx) 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(context 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) WithID

func (rc *Ctx) WithID(id string) *Ctx

WithID sets the context ID.

func (*Ctx) WithLogger

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

WithLogger sets the logger.

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

func (rc *Ctx) WithRoute(route *Route) *Ctx

WithRoute sets the route.

func (*Ctx) WithRouteParams

func (rc *Ctx) WithRouteParams(params RouteParameters) *Ctx

WithRouteParams sets the route parameters.

func (*Ctx) WithSession

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

WithSession sets the session for the request.

func (*Ctx) WithState

func (rc *Ctx) WithState(state State) *Ctx

WithState sets the state.

func (*Ctx) WithStateValue

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

WithStateValue sets the state for a key to an object.

func (*Ctx) WithTracer

func (rc *Ctx) WithTracer(tracer Tracer) *Ctx

WithTracer sets the tracer.

func (*Ctx) WithViews

func (rc *Ctx) WithViews(vc *ViewCache) *Ctx

WithViews sets the view cache for the ctx.

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.

It can be eschewed for:

return web.XML.Result(foo)

But is left in place for legacy reasons.

type Fileserver

type Fileserver interface {
	AddHeader(key, value string)
	AddRewriteRule(match string, rewriteAction RewriteAction) error
	SetMiddleware(middleware ...Middleware)
	Headers() http.Header
	RewriteRules() []RewriteRule
	Action(*Ctx) Result
}

Fileserver is a type that implements the basics of a fileserver.

type HSTSConfig

type HSTSConfig struct {
	Enabled           *bool `json:"enabled" yaml:"enabled"`
	MaxAgeSeconds     int   `json:"maxAgeSeconds" yaml:"maxAgeSeconds"`
	IncludeSubDomains *bool `json:"includeSubDomains" yaml:"includeSubDomains"`
	Preload           *bool `json:"preload" yaml:"preload"`
}

HSTSConfig are hsts options.

func (HSTSConfig) GetEnabled

func (h HSTSConfig) GetEnabled(defaults ...bool) bool

GetEnabled returns if hsts should be enabled.

func (HSTSConfig) GetIncludeSubDomains

func (h HSTSConfig) GetIncludeSubDomains(defaults ...bool) bool

GetIncludeSubDomains returns if hsts should include sub-domains.

func (HSTSConfig) GetMaxAgeSeconds

func (h HSTSConfig) GetMaxAgeSeconds(defaults ...int) int

GetMaxAgeSeconds returns the max age seconds.

func (HSTSConfig) GetPreload

func (h HSTSConfig) GetPreload(defaults ...bool) bool

GetPreload returns if hsts should apply before requests.

type HTTPSUpgrader

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

HTTPSUpgrader redirects HTTP to HTTPS

func NewHTTPSUpgrader

func NewHTTPSUpgrader() *HTTPSUpgrader

NewHTTPSUpgrader returns a new HTTPSUpgrader which redirects HTTP to HTTPS

func NewHTTPSUpgraderFromConfig

func NewHTTPSUpgraderFromConfig(cfg *HTTPSUpgraderConfig) *HTTPSUpgrader

NewHTTPSUpgraderFromConfig creates a new https upgrader from a config.

func NewHTTPSUpgraderFromEnv

func NewHTTPSUpgraderFromEnv() *HTTPSUpgrader

NewHTTPSUpgraderFromEnv returns a new https upgrader from enviroment variables.

func (*HTTPSUpgrader) Logger

func (hu *HTTPSUpgrader) Logger() *logger.Logger

Logger returns the logger.

func (*HTTPSUpgrader) ServeHTTP

func (hu *HTTPSUpgrader) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP redirects HTTP to HTTPS

func (*HTTPSUpgrader) TargetPort

func (hu *HTTPSUpgrader) TargetPort() int32

TargetPort returns the target port.

func (*HTTPSUpgrader) WithLogger

func (hu *HTTPSUpgrader) WithLogger(log *logger.Logger) *HTTPSUpgrader

WithLogger sets the logger.

func (*HTTPSUpgrader) WithTargetPort

func (hu *HTTPSUpgrader) WithTargetPort(targetPort int32) *HTTPSUpgrader

WithTargetPort sets the target port.

type HTTPSUpgraderConfig

type HTTPSUpgraderConfig struct {
	TargetPort int32 `json:"targetPort" yaml:"targetPort" env:"UPGRADE_TARGET_PORT"`
}

HTTPSUpgraderConfig is the config for the https upgrader server.

func NewHTTPSUpgraderConfigFromEnv

func NewHTTPSUpgraderConfigFromEnv() *HTTPSUpgraderConfig

NewHTTPSUpgraderConfigFromEnv returns an https upgrader config populated from the environment.

func (HTTPSUpgraderConfig) GetTargetPort

func (c HTTPSUpgraderConfig) GetTargetPort(defaults ...int32) int32

GetTargetPort gets the target port. It defaults to unset, i.e. use the https default of 443.

type Handler

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.
			should be used as a kubernetes readiness probe.
/debug/vars - `pkg/expvar` output.

func NewHealthz

func NewHealthz(hosted HealthzHostable) *Healthz

NewHealthz returns a new healthz.

func (*Healthz) BindAddr

func (hz *Healthz) BindAddr() string

BindAddr returns the bind address.

func (*Healthz) Config

func (hz *Healthz) Config() *HealthzConfig

Config returns the healthz config.

func (*Healthz) DefaultHeaders

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

DefaultHeaders returns the default headers.

func (*Healthz) FailureThreshold

func (hz *Healthz) FailureThreshold() int

FailureThreshold returns the failure threshold.

func (*Healthz) GracePeriod

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

GracePeriod returns the grace period in seconds

func (*Healthz) Hosted

func (hz *Healthz) Hosted() graceful.Graceful

Hosted returns the hosted app.

func (*Healthz) IdleTimeout

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

IdleTimeout is the time before we close a connection.

func (*Healthz) IsRunning

func (hz *Healthz) IsRunning() bool

IsRunning returns if the healthz server is running.

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

func (hz *Healthz) NotifyStarted() <-chan struct{}

NotifyStarted returns the notify started signal.

func (*Healthz) NotifyStopped added in v0.3.1

func (hz *Healthz) NotifyStopped() <-chan struct{}

NotifyStopped returns the notify shutdown signal.

func (*Healthz) NotifyStopping added in v0.3.1

func (hz *Healthz) NotifyStopping() <-chan struct{}

NotifyStopping returns the notify shutdown signal.

func (*Healthz) ReadHeaderTimeout

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

func (hz *Healthz) Self() *App

Self returns the inner web server.

func (*Healthz) ServeHTTP

func (hz *Healthz) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

func (*Healthz) Start

func (hz *Healthz) Start() error

Start implements shutdowner.

func (*Healthz) Stop added in v0.3.1

func (hz *Healthz) Stop() error

Stop implements shutdowner.

func (*Healthz) WithBindAddr

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

WithBindAddr sets the bind address.

func (*Healthz) WithConfig

func (hz *Healthz) WithConfig(cfg *HealthzConfig) *Healthz

WithConfig sets the healthz config and relevant properties.

func (*Healthz) WithDefaultHeader

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

WithDefaultHeader adds a default header.

func (*Healthz) WithFailureThreshold

func (hz *Healthz) WithFailureThreshold(failureThreshold int) *Healthz

WithFailureThreshold sets the failure threshold.

func (*Healthz) WithGracePeriod

func (hz *Healthz) WithGracePeriod(gracePeriod time.Duration) *Healthz

WithGracePeriod sets the grace period seconds

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) 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) 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 {
	BindAddr         string        `json:"bindAddr" yaml:"bindAddr" env:"HEALTHZ_BIND_ADDR"`
	GracePeriod      time.Duration `json:"gracePeriod" yaml:"gracePeriod"`
	FailureThreshold int           `json:"failureThreshold" yaml:"failureThreshold" env:"READY_FAILURE_THRESHOLD"`
	RecoverPanics    *bool         `json:"recoverPanics" yaml:"recoverPanics"`

	MaxHeaderBytes    int           `json:"maxHeaderBytes,omitempty" yaml:"maxHeaderBytes,omitempty" env:"MAX_HEADER_BYTES"`
	ReadTimeout       time.Duration `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty" env:"READ_HEADER_TIMEOUT"`
	ReadHeaderTimeout time.Duration `json:"readHeaderTimeout,omitempty" yaml:"readHeaderTimeout,omitempty" env:"READ_HEADER_TIMEOUT"`
	WriteTimeout      time.Duration `json:"writeTimeout,omitempty" yaml:"writeTimeout,omitempty" env:"WRITE_TIMEOUT"`
	IdleTimeout       time.Duration `json:"idleTimeout,omitempty" yaml:"idleTimeout,omitempty" env:"IDLE_TIMEOUT"`
}

HealthzConfig is the healthz config.

func (HealthzConfig) GetBindAddr

func (hzc HealthzConfig) GetBindAddr(defaults ...string) string

GetBindAddr gets the bind address.

func (HealthzConfig) GetFailureThreshold

func (hzc HealthzConfig) GetFailureThreshold(defaults ...int) int

GetFailureThreshold gets the failure threshold or a default.

func (HealthzConfig) GetGracePeriod

func (hzc HealthzConfig) GetGracePeriod(defaults ...time.Duration) time.Duration

GetGracePeriod gets a grace period or a default.

func (HealthzConfig) GetIdleTimeout

func (hzc HealthzConfig) GetIdleTimeout(defaults ...time.Duration) time.Duration

GetIdleTimeout gets a property.

func (HealthzConfig) GetMaxHeaderBytes

func (hzc HealthzConfig) GetMaxHeaderBytes(defaults ...int) int

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

func (HealthzConfig) GetReadHeaderTimeout

func (hzc HealthzConfig) GetReadHeaderTimeout(defaults ...time.Duration) time.Duration

GetReadHeaderTimeout gets a property.

func (HealthzConfig) GetReadTimeout

func (hzc HealthzConfig) GetReadTimeout(defaults ...time.Duration) time.Duration

GetReadTimeout gets a property.

func (HealthzConfig) GetRecoverPanics

func (hzc HealthzConfig) GetRecoverPanics(defaults ...bool) bool

GetRecoverPanics gets recover panics or a default.

func (HealthzConfig) GetWriteTimeout

func (hzc HealthzConfig) GetWriteTimeout(defaults ...time.Duration) time.Duration

GetWriteTimeout gets a property.

type HealthzHostable added in v0.3.1

type HealthzHostable interface {
	graceful.Graceful
	IsRunning() bool
}

HealthzHostable is a type that can be hosted by healthz.

type JSONResult

type JSONResult struct {
	StatusCode int
	Response   interface{}
}

JSONResult is a json result.

func (*JSONResult) Render

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

Render renders the result

type JSONResultProvider

type JSONResultProvider struct{}

JSONResultProvider are context results for api methods.

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

func (JSONResultProvider) BadRequest

func (jrp JSONResultProvider) BadRequest(err error) Result

BadRequest returns a service response.

func (JSONResultProvider) InternalError

func (jrp JSONResultProvider) InternalError(err error) Result

InternalError returns a service response.

func (JSONResultProvider) NotAuthorized

func (jrp JSONResultProvider) NotAuthorized() Result

NotAuthorized returns a service response.

func (JSONResultProvider) NotFound

func (jrp JSONResultProvider) NotFound() Result

NotFound returns a service response.

func (JSONResultProvider) OK

func (jrp JSONResultProvider) OK() Result

OK returns a service response.

func (JSONResultProvider) Result

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

Result returns a json response.

func (JSONResultProvider) Status

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

Status returns a plaintext result.

type JWTManager

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

JWTManager is a manager for JWTs.

func NewJWTManager

func NewJWTManager(key []byte) *JWTManager

NewJWTManager returns a new jwt manager from a key.

func (JWTManager) Claims

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

Claims returns the sesion as a JWT standard claims object.

func (JWTManager) FromClaims

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

FromClaims returns a session from a given claims set.

func (JWTManager) KeyFunc

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

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

func (JWTManager) ParseSessionValueHandler

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

ParseSessionValueHandler is a shim to the auth manager.

func (JWTManager) SerializeSessionValueHandler

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

SerializeSessionValueHandler is a shim to the auth manager.

type LocalSessionCache

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

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

func NewLocalSessionCache

func NewLocalSessionCache() *LocalSessionCache

NewLocalSessionCache returns a new session cache.

func (*LocalSessionCache) FetchHandler

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

FetchHandler is a shim to interface with the auth manager.

func (*LocalSessionCache) Get

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

Get gets a session.

func (*LocalSessionCache) PersistHandler

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

PersistHandler is a shim to interface with the auth manager.

func (*LocalSessionCache) Remove

func (lsc *LocalSessionCache) Remove(sessionID string)

Remove removes a session from the cache.

func (*LocalSessionCache) RemoveHandler

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

RemoveHandler is a shim to interface with the auth manager.

func (*LocalSessionCache) Upsert

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

Upsert adds or updates a session to the cache.

type Middleware

type Middleware func(Action) Action

Middleware are steps that run in order before a given action.

func SessionMiddleware

func SessionMiddleware(notAuthorized Action) Middleware

SessionMiddleware implements a custom notAuthorized action.

func WithTimeout

func WithTimeout(d time.Duration) Middleware

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

type MockRequestBuilder

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

MockRequestBuilder facilitates creating mock requests.

func NewMockRequestBuilder

func NewMockRequestBuilder(app *App) *MockRequestBuilder

NewMockRequestBuilder returns a new mock request builder for a given app.

func (*MockRequestBuilder) Bytes

func (mrb *MockRequestBuilder) Bytes() ([]byte, error)

Bytes returns the response as bytes.

func (*MockRequestBuilder) BytesWithMeta

func (mrb *MockRequestBuilder) BytesWithMeta() ([]byte, *ResponseMeta, error)

BytesWithMeta returns the response as bytes with meta information.

func (*MockRequestBuilder) CreateCtx

func (mrb *MockRequestBuilder) CreateCtx(p RouteParameters) (*Ctx, error)

CreateCtx returns the mock request as a request context.

func (*MockRequestBuilder) Delete

func (mrb *MockRequestBuilder) Delete(pathFormat string, args ...interface{}) *MockRequestBuilder

Delete is a shortcut for WithVerb("DELETE") WithPathf(pathFormat, args...)

func (*MockRequestBuilder) Err

func (mrb *MockRequestBuilder) Err() error

Err rerturns an underlying error

func (*MockRequestBuilder) Execute

func (mrb *MockRequestBuilder) Execute() error

Execute just runs the request. It internally calls `Bytes()` which fully consumes the response.

func (*MockRequestBuilder) ExecuteWithMeta

func (mrb *MockRequestBuilder) ExecuteWithMeta() (*ResponseMeta, error)

ExecuteWithMeta returns basic metadata for a response.

func (*MockRequestBuilder) Get

func (mrb *MockRequestBuilder) Get(pathFormat string, args ...interface{}) *MockRequestBuilder

Get is a shortcut for WithVerb("GET") WithPathf(pathFormat, args...)

func (*MockRequestBuilder) GetStateValue

func (mrb *MockRequestBuilder) GetStateValue(key string) interface{}

GetStateValue returns an object in the state cache.

func (*MockRequestBuilder) JSON

func (mrb *MockRequestBuilder) JSON(object interface{}) error

JSON executes the mock request and reads the response to the given object as json.

func (*MockRequestBuilder) JSONWithMeta

func (mrb *MockRequestBuilder) JSONWithMeta(object interface{}) (*ResponseMeta, error)

JSONWithMeta executes the mock request and reads the response to the given object as json.

func (*MockRequestBuilder) LookupRoute

func (mrb *MockRequestBuilder) LookupRoute() (route *Route, params RouteParameters)

LookupRoute returns the corresponding route for the mocked request.

func (*MockRequestBuilder) Patch

func (mrb *MockRequestBuilder) Patch(pathFormat string, args ...interface{}) *MockRequestBuilder

Patch is a shortcut for WithVerb("PATCH") WithPathf(pathFormat, args...)

func (*MockRequestBuilder) Post

func (mrb *MockRequestBuilder) Post(pathFormat string, args ...interface{}) *MockRequestBuilder

Post is a shortcut for WithVerb("POST") WithPathf(pathFormat, args...)

func (*MockRequestBuilder) Put

func (mrb *MockRequestBuilder) Put(pathFormat string, args ...interface{}) *MockRequestBuilder

Put is a shortcut for WithVerb("PUT") WithPathf(pathFormat, args...)

func (*MockRequestBuilder) Request

func (mrb *MockRequestBuilder) Request() (*http.Request, error)

Request returns the mock request builder settings as an http.Request.

func (*MockRequestBuilder) Response

func (mrb *MockRequestBuilder) Response() (res *http.Response, err error)

Response runs the mock request.

func (*MockRequestBuilder) State

func (mrb *MockRequestBuilder) State() State

State returns the underlying state.

func (*MockRequestBuilder) WithBasicAuth

func (mrb *MockRequestBuilder) WithBasicAuth(username, password string) *MockRequestBuilder

WithBasicAuth sets basic auth credentials for the request.

func (*MockRequestBuilder) WithCookie

func (mrb *MockRequestBuilder) WithCookie(cookie *http.Cookie) *MockRequestBuilder

WithCookie adds a cookie for the request.

func (*MockRequestBuilder) WithCookieValue

func (mrb *MockRequestBuilder) WithCookieValue(name, value string) *MockRequestBuilder

WithCookieValue adds a basic name+value cookie for the request.

func (*MockRequestBuilder) WithErr

func (mrb *MockRequestBuilder) WithErr(err error) *MockRequestBuilder

WithErr sets the error if it is unset.

func (*MockRequestBuilder) WithFormValue

func (mrb *MockRequestBuilder) WithFormValue(key, value string) *MockRequestBuilder

WithFormValue adds a form value for the request.

func (*MockRequestBuilder) WithHeader

func (mrb *MockRequestBuilder) WithHeader(key, value string) *MockRequestBuilder

WithHeader adds a header for the request.

func (*MockRequestBuilder) WithPathf

func (mrb *MockRequestBuilder) WithPathf(pathFormat string, args ...interface{}) *MockRequestBuilder

WithPathf sets the path for the request.

func (*MockRequestBuilder) WithPostBody

func (mrb *MockRequestBuilder) WithPostBody(postBody []byte) *MockRequestBuilder

WithPostBody sets the post body for the request.

func (*MockRequestBuilder) WithPostBodyAsJSON

func (mrb *MockRequestBuilder) WithPostBodyAsJSON(object interface{}) *MockRequestBuilder

WithPostBodyAsJSON sets the post body for the request by serializing an object to JSON.

func (*MockRequestBuilder) WithPostedFile

func (mrb *MockRequestBuilder) WithPostedFile(postedFile PostedFile) *MockRequestBuilder

WithPostedFile includes a file as a post parameter.

func (*MockRequestBuilder) WithQueryString

func (mrb *MockRequestBuilder) WithQueryString(key, value string) *MockRequestBuilder

WithQueryString adds a querystring param for the request.

func (*MockRequestBuilder) WithStateValue

func (mrb *MockRequestBuilder) WithStateValue(key string, value interface{}) *MockRequestBuilder

WithStateValue sets the state for a key to an object.

func (*MockRequestBuilder) WithVerb

func (mrb *MockRequestBuilder) WithVerb(verb string) *MockRequestBuilder

WithVerb sets the verb for the request.

func (*MockRequestBuilder) XML

func (mrb *MockRequestBuilder) XML(object interface{}) error

XML executes the mock request and reads the response to the given object as json.

func (*MockRequestBuilder) XMLWithMeta

func (mrb *MockRequestBuilder) XMLWithMeta(object interface{}) (*ResponseMeta, error)

XMLWithMeta executes the mock request and reads the response to the given object as json.

type NoContentResult

type NoContentResult struct{}

NoContentResult returns a no content response.

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

func (NoContentResult) Render

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

Render renders a static result.

type PanicAction

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
	Response    []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 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.

type ResultPreRender

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

ResultPreRender is a result that has a PreRender step.

type ResultProvider

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

ResultProvider is the provider interface for results.

type ResultRenderComplete

type ResultRenderComplete interface {
	RenderComplete(ctx *Ctx) error
}

ResultRenderComplete is a result that has a RenderComplete step.

type RewriteAction

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

RewriteAction is an action for a rewrite rule.

type RewriteRule

type RewriteRule struct {
	MatchExpression string

	Action RewriteAction
	// contains filtered or unexported fields
}

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

func (RewriteRule) Apply

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

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

type Route

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

Route is an entry in the route tree.

func (Route) String

func (r Route) String() string

String returns the path.

func (Route) StringWithMethod

func (r Route) StringWithMethod() string

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

type 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"`
	BaseURL    string                 `json:"baseURL" yaml:"baseURL"`
	SessionID  string                 `json:"sessionID" yaml:"sessionID"`
	CreatedUTC time.Time              `json:"createdUTC" yaml:"createdUTC"`
	ExpiresUTC time.Time              `json:"expiresUTC" yaml:"expiresUTC"`
	UserAgent  string                 `json:"userAgent" yaml:"userAgent"`
	RemoteAddr string                 `json:"remoteAddr" yaml:"remoteAddr"`
	State      map[string]interface{} `json:"state,omitempty" yaml:"state,omitempty"`
}

Session is an active session

func NewSession

func NewSession(userID string, sessionID string) *Session

NewSession returns a new session object.

func (*Session) IsExpired

func (s *Session) IsExpired() bool

IsExpired returns if the session is expired.

func (*Session) IsZero

func (s *Session) IsZero() bool

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

func (*Session) WithBaseURL

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

WithBaseURL sets the base url.

func (*Session) WithRemoteAddr

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

WithRemoteAddr sets the remote addr.

func (*Session) WithUserAgent

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

WithUserAgent sets the user agent.

type SessionLockPolicy

type SessionLockPolicy int

SessionLockPolicy is a lock policy.

const (
	// SessionUnsafe is a lock-free session policy.
	SessionUnsafe SessionLockPolicy = 0

	// SessionReadLock is a lock policy that acquires a read lock on session.
	SessionReadLock SessionLockPolicy = 1

	// SessionReadWriteLock is a lock policy that acquires both a read and a write lock on session.
	SessionReadWriteLock SessionLockPolicy = 2
)

type State

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

State is a provider for a state bag

type StaticFileServer

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

StaticFileServer is a cache of static files.

func NewStaticFileServer

func NewStaticFileServer(fs http.FileSystem) *StaticFileServer

NewStaticFileServer returns a new static file cache.

func (*StaticFileServer) Action

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

Action is the entrypoint for the static server. It will run middleware if specified before serving the file.

func (*StaticFileServer) AddHeader

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

AddHeader adds a header to the static cache results.

func (*StaticFileServer) AddRewriteRule

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

AddRewriteRule adds a static re-write rule.

func (*StaticFileServer) Headers

func (sc *StaticFileServer) Headers() http.Header

Headers returns the headers for the static server.

func (*StaticFileServer) Log

func (sc *StaticFileServer) Log() *logger.Logger

Log returns a logger reference.

func (*StaticFileServer) RewriteRules

func (sc *StaticFileServer) RewriteRules() []RewriteRule

RewriteRules returns the rewrite rules

func (*StaticFileServer) ServeFile

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

ServeFile writes the file to the response without running middleware.

func (*StaticFileServer) SetMiddleware

func (sc *StaticFileServer) SetMiddleware(middlewares ...Middleware)

SetMiddleware sets the middlewares.

func (*StaticFileServer) WithLogger

func (sc *StaticFileServer) WithLogger(log *logger.Logger) *StaticFileServer

WithLogger sets the logger reference for the static file cache.

type StaticResult

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

StaticResult represents a static output.

func NewStaticResultForFile

func NewStaticResultForFile(filePath string) *StaticResult

NewStaticResultForFile returns a static result for an individual file.

func (StaticResult) Render

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

Render renders a static result.

type StatusViewModel

type StatusViewModel struct {
	StatusCode int
	Response   interface{}
}

StatusViewModel returns the status view model.

type SyncState

type SyncState struct {
	sync.Mutex
	Values map[string]Any
}

SyncState is the collection of state objects on a context.

func (*SyncState) Copy

func (s *SyncState) Copy() State

Copy creates a new copy of the vars.

func (*SyncState) Get

func (s *SyncState) Get(key string) Any

Get gets a value.

func (*SyncState) Keys

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

Keys returns

func (*SyncState) Remove

func (s *SyncState) Remove(key string)

Remove removes a key.

func (*SyncState) Set

func (s *SyncState) Set(key string, value Any)

Set sets a value.

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{}

TextResultProvider is the default response provider if none is specified.

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

func (TextResultProvider) BadRequest

func (trp TextResultProvider) BadRequest(err error) Result

BadRequest returns a plaintext result.

func (TextResultProvider) InternalError

func (trp TextResultProvider) InternalError(err error) Result

InternalError returns a plainttext result.

func (TextResultProvider) NotAuthorized

func (trp TextResultProvider) NotAuthorized() Result

NotAuthorized returns a plaintext result.

func (TextResultProvider) NotFound

func (trp TextResultProvider) NotFound() Result

NotFound returns a plaintext result.

func (TextResultProvider) OK

func (trp TextResultProvider) OK() Result

OK returns an plaintext result.

func (TextResultProvider) Result

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

Result returns a plaintext result.

func (TextResultProvider) Status

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

Status returns a plaintext result.

type TraceFinisher

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

TraceFinisher is a finisher for a trace.

type Tracer

type Tracer interface {
	Start(*Ctx) TraceFinisher
}

Tracer is a type that traces complete requests.

type Values

type Values = map[string]interface{}

Values is an alias to map[string]interface{}

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 (*ViewCache) AddLiterals

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

AddLiterals adds view literal strings to the view collection.

func (*ViewCache) AddPaths

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

AddPaths adds paths to the view collection.

func (*ViewCache) BadRequest

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

BadRequest returns a view result.

func (*ViewCache) BadRequestTemplateName

func (vc *ViewCache) BadRequestTemplateName() string

BadRequestTemplateName returns the bad request template.

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

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

InternalError returns a view result.

func (*ViewCache) InternalErrorTemplateName

func (vc *ViewCache) InternalErrorTemplateName() string

InternalErrorTemplateName returns the bad request template.

func (*ViewCache) Literals

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

Literals returns the view literals.

func (*ViewCache) Lookup

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

Lookup looks up a view.

func (*ViewCache) NotAuthorized

func (vc *ViewCache) NotAuthorized() Result

NotAuthorized returns a view result.

func (*ViewCache) NotAuthorizedTemplateName

func (vc *ViewCache) NotAuthorizedTemplateName() string

NotAuthorizedTemplateName returns the not authorized template name.

func (*ViewCache) NotFound

func (vc *ViewCache) NotFound() Result

NotFound returns a view result.

func (*ViewCache) NotFoundTemplateName

func (vc *ViewCache) NotFoundTemplateName() string

NotFoundTemplateName returns the not found template name.

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

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

Status returns a status view result.

func (*ViewCache) StatusTemplateName

func (vc *ViewCache) StatusTemplateName() string

StatusTemplateName returns the status template name.

func (*ViewCache) Templates

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

Templates gets the view cache for the app.

func (*ViewCache) View

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

View returns a view result.

func (*ViewCache) WithBadRequestTemplateName

func (vc *ViewCache) WithBadRequestTemplateName(templateName string) *ViewCache

WithBadRequestTemplateName sets the bad request template.

func (*ViewCache) WithCached

func (vc *ViewCache) WithCached(cached bool) *ViewCache

WithCached sets if we should cache views once they're compiled, or always read them from disk. Cached == True, use in memory storage for views Cached == False, read the file from disk every time we want to render the view.

func (*ViewCache) WithInternalErrorTemplateName

func (vc *ViewCache) WithInternalErrorTemplateName(templateName string) *ViewCache

WithInternalErrorTemplateName sets the bad request template.

func (*ViewCache) WithNotAuthorizedTemplateName

func (vc *ViewCache) WithNotAuthorizedTemplateName(templateName string) *ViewCache

WithNotAuthorizedTemplateName sets the not authorized template name.

func (*ViewCache) WithNotFoundTemplateName

func (vc *ViewCache) WithNotFoundTemplateName(templateName string) *ViewCache

WithNotFoundTemplateName sets the not found request template name.

func (*ViewCache) WithStatusTemplateName

func (vc *ViewCache) WithStatusTemplateName(templateName string) *ViewCache

WithStatusTemplateName sets the status templatename .

type ViewCacheConfig

type ViewCacheConfig struct {
	Cached                    *bool    `json:"cached,omitempty" yaml:"cached,omitempty" env:"VIEW_CACHE_ENABLED"`
	Paths                     []string `json:"paths,omitempty" yaml:"paths,omitempty" env:"VIEW_CACHE_PATHS,csv"`
	BufferPoolSize            int      `json:"bufferPoolSize,omitempty" yaml:"bufferPoolSize,omitempty"`
	InternalErrorTemplateName string   `json:"internalErrorTemplateName,omitempty" yaml:"internalErrorTemplateName,omitempty"`
	BadRequestTemplateName    string   `json:"badRequestTemplateName,omitempty" yaml:"badRequestTemplateName,omitempty"`
	NotFoundTemplateName      string   `json:"notFoundTemplateName,omitempty" yaml:"notFoundTemplateName,omitempty"`
	NotAuthorizedTemplateName string   `json:"notAuthorizedTemplateName,omitempty" yaml:"notAuthorizedTemplateName,omitempty"`
	StatusTemplateName        string   `json:"statusTemplateName,omitempty" yaml:"statusTemplateName,omitempty"`
}

ViewCacheConfig is a config for the view cache.

func (ViewCacheConfig) GetBadRequestTemplateName

func (vcc ViewCacheConfig) GetBadRequestTemplateName(defaults ...string) string

GetBadRequestTemplateName returns the bad request template name for the app.

func (ViewCacheConfig) GetBufferPoolSize

func (vcc ViewCacheConfig) GetBufferPoolSize(defaults ...int) int

GetBufferPoolSize gets the buffer pool size or a default.

func (ViewCacheConfig) GetCached

func (vcc ViewCacheConfig) GetCached(defaults ...bool) bool

GetCached returns if the viewcache should store templates in memory or read from disk.

func (ViewCacheConfig) GetInternalErrorTemplateName

func (vcc ViewCacheConfig) GetInternalErrorTemplateName(defaults ...string) string

GetInternalErrorTemplateName returns the internal error template name for the app.

func (ViewCacheConfig) GetNotAuthorizedTemplateName

func (vcc ViewCacheConfig) GetNotAuthorizedTemplateName(defaults ...string) string

GetNotAuthorizedTemplateName returns the not authorized template name for the app.

func (ViewCacheConfig) GetNotFoundTemplateName

func (vcc ViewCacheConfig) GetNotFoundTemplateName(defaults ...string) string

GetNotFoundTemplateName returns the not found template name for the app.

func (ViewCacheConfig) GetPaths

func (vcc ViewCacheConfig) GetPaths(defaults ...[]string) []string

GetPaths returns default view paths.

func (ViewCacheConfig) GetStatusTemplateName

func (vcc ViewCacheConfig) GetStatusTemplateName(defaults ...string) string

GetStatusTemplateName returns the not authorized template name for the app.

type ViewModel

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

ViewModel is a wrapping viewmodel.

type ViewResult

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

ViewResult is a result that renders a view.

func (*ViewResult) Render

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

Render renders the result to the given response writer.

type ViewTraceFinisher

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

ViewTraceFinisher is a finisher for view traces.

type ViewTracer

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

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

type XMLResult

type XMLResult struct {
	StatusCode int
	Response   interface{}
}

XMLResult is a json result.

func (*XMLResult) Render

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

Render renders the result

type XMLResultProvider

type XMLResultProvider struct{}

XMLResultProvider are context results for api methods.

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

func (XMLResultProvider) BadRequest

func (xrp XMLResultProvider) BadRequest(err error) Result

BadRequest returns a service response.

func (XMLResultProvider) InternalError

func (xrp XMLResultProvider) InternalError(err error) Result

InternalError returns a service response.

func (XMLResultProvider) NotAuthorized

func (xrp XMLResultProvider) NotAuthorized() Result

NotAuthorized returns a service response.

func (XMLResultProvider) NotFound

func (xrp XMLResultProvider) NotFound() Result

NotFound returns a service response.

func (XMLResultProvider) OK

func (xrp XMLResultProvider) OK() Result

OK returns a service response.

func (XMLResultProvider) Result

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

Result returns an xml response.

func (XMLResultProvider) Status

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

Status returns a plaintext result.

Directories

Path Synopsis
_examples
api

Jump to

Keyboard shortcuts

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