Documentation ¶
Overview ¶
Package handlers define reusable handler components that focus on offering a single well-defined feature. Note that any http.Handler implementation can be used with Ghost's chainable or wrappable handlers design.
Go's standard library provides a number of such useful handlers in net/http:
- FileServer(http.FileSystem) - NotFoundHandler() - RedirectHandler(string, int) - StripPrefix(string, http.Handler) - TimeoutHandler(http.Handler, time.Duration, string)
This package adds the following list of handlers:
- BasicAuthHandler(http.Handler, func(string, string) (interface{}, bool), string) a Basic Authentication handler. - ContextHandler(http.Handler, int) : a volatile storage map valid only for the duration of the request, with no locking required. - FaviconHandler(http.Handler, string, time.Duration) : an efficient favicon handler. - GZIPHandler(http.Handler) : compress the content of the body if the client accepts gzip compression. - LogHandler(http.Handler, *LogOptions) : customizable request logger. - PanicHandler(http.Handler) : handle panics gracefully so that the client receives a response (status code 500). - SessionHandler(http.Handler, *SessionOptions) : a cookie-based, store-agnostic persistent session handler. - StaticFileHandler(string) : serve the contents of a specific file.
Index ¶
- Constants
- Variables
- func BadRequest(w http.ResponseWriter, msg string)
- func BasicAuthHandler(h http.Handler, authFn func(string, string) (interface{}, bool), realm string) http.HandlerFunc
- func BasicAuthHandlerFunc(h http.HandlerFunc, authFn func(string, string) (interface{}, bool), ...) http.HandlerFunc
- func ContextHandler(h http.Handler, cap int) http.HandlerFunc
- func ContextHandlerFunc(h http.HandlerFunc, cap int) http.HandlerFunc
- func FaviconHandler(h http.Handler, path string, maxAge time.Duration) http.HandlerFunc
- func FaviconHandlerFunc(h http.HandlerFunc, path string, maxAge time.Duration) http.HandlerFunc
- func GZIPHandler(h http.Handler, filterFn func(http.ResponseWriter, *http.Request) bool) http.HandlerFunc
- func GZIPHandlerFunc(h http.HandlerFunc, filterFn func(http.ResponseWriter, *http.Request) bool) http.HandlerFunc
- func GetContext(w http.ResponseWriter) (map[interface{}]interface{}, bool)
- func GetPanicError(w http.ResponseWriter) (interface{}, bool)
- func GetResponseWriter(w http.ResponseWriter, predicate func(http.ResponseWriter) bool) (http.ResponseWriter, bool)
- func GetUser(w http.ResponseWriter) (interface{}, bool)
- func GetUserName(w http.ResponseWriter) (string, bool)
- func GhostHandlerFunc(h func(w GhostWriter, r *http.Request)) http.HandlerFunc
- func HeaderMatch(hdr http.Header, nm string, matchType HeaderMatchType, test string) bool
- func LogHandler(h http.Handler, opts *LogOptions) http.HandlerFunc
- func LogHandlerFunc(h http.HandlerFunc, opts *LogOptions) http.HandlerFunc
- func PanicHandler(h http.Handler, errH http.Handler) http.HandlerFunc
- func PanicHandlerFunc(h http.HandlerFunc, errH http.HandlerFunc) http.HandlerFunc
- func SessionHandler(h http.Handler, opts *SessionOptions) http.HandlerFunc
- func SessionHandlerFunc(h http.HandlerFunc, opts *SessionOptions) http.HandlerFunc
- func StaticFileHandler(path string) http.HandlerFunc
- func Unauthorized(w http.ResponseWriter, realm string)
- type ChainableHandler
- type GhostWriter
- type HeaderMatchType
- type LogOptions
- type MemoryStore
- type RedisStore
- type RedisStoreOptions
- type Session
- type SessionOptions
- type SessionStore
- type WrapWriter
Constants ¶
const ( // Predefined logging formats that can be passed as format string. Ldefault = "_default_" Lshort = "_short_" Ltiny = "_tiny_" )
Variables ¶
var ( ErrSessionSecretMissing = errors.New("session secret is missing") ErrNoSessionID = errors.New("session ID could not be generated") )
var (
ErrNoKeyPrefix = errors.New("cannot get session keys without a key prefix")
)
Functions ¶
func BadRequest ¶
func BadRequest(w http.ResponseWriter, msg string)
Writes a bad request response to the client, with an optional message.
func BasicAuthHandler ¶
func BasicAuthHandler(h http.Handler, authFn func(string, string) (interface{}, bool), realm string) http.HandlerFunc
Returns a Basic Authentication handler, protecting the wrapped handler from being accessed if the authentication function is not successful.
func BasicAuthHandlerFunc ¶
func BasicAuthHandlerFunc(h http.HandlerFunc, authFn func(string, string) (interface{}, bool), realm string) http.HandlerFunc
BasicAuthHandlerFunc is the same as BasicAuthHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func ContextHandler ¶
func ContextHandler(h http.Handler, cap int) http.HandlerFunc
ContextHandler gives a context storage that lives only for the duration of the request, with no locking involved.
func ContextHandlerFunc ¶
func ContextHandlerFunc(h http.HandlerFunc, cap int) http.HandlerFunc
ContextHandlerFunc is the same as ContextHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func FaviconHandler ¶
Efficient favicon handler, mostly a port of node's Connect library implementation of the favicon middleware. https://github.com/senchalabs/connect
func FaviconHandlerFunc ¶
func FaviconHandlerFunc(h http.HandlerFunc, path string, maxAge time.Duration) http.HandlerFunc
FaviconHandlerFunc is the same as FaviconHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func GZIPHandler ¶
func GZIPHandler(h http.Handler, filterFn func(http.ResponseWriter, *http.Request) bool) http.HandlerFunc
Gzip compression HTTP handler. If the client supports it, it compresses the response written by the wrapped handler. The filter function is called when the response is about to be written to determine if compression should be applied. If this argument is nil, the default filter will GZIP only content types containing /json|text|javascript/.
func GZIPHandlerFunc ¶
func GZIPHandlerFunc(h http.HandlerFunc, filterFn func(http.ResponseWriter, *http.Request) bool) http.HandlerFunc
GZIPHandlerFunc is the same as GZIPHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func GetContext ¶
func GetContext(w http.ResponseWriter) (map[interface{}]interface{}, bool)
Helper function to retrieve the context map from the ResponseWriter interface.
func GetPanicError ¶
func GetPanicError(w http.ResponseWriter) (interface{}, bool)
Helper function to retrieve the panic error, if any.
func GetResponseWriter ¶
func GetResponseWriter(w http.ResponseWriter, predicate func(http.ResponseWriter) bool) (http.ResponseWriter, bool)
Helper function to retrieve a specific ResponseWriter.
func GetUser ¶
func GetUser(w http.ResponseWriter) (interface{}, bool)
Return the currently authenticated user. This is the same data that was returned by the authentication function passed to BasicAuthHandler.
func GetUserName ¶
func GetUserName(w http.ResponseWriter) (string, bool)
Return the currently authenticated user name. This is the user name that was authenticated for the current request.
func GhostHandlerFunc ¶
func GhostHandlerFunc(h func(w GhostWriter, r *http.Request)) http.HandlerFunc
Convenience handler that wraps a custom function with direct access to the authenticated user, context and session on the writer.
func HeaderMatch ¶
Check if the specified header matches the test string, applying the header match type specified.
func LogHandler ¶
func LogHandler(h http.Handler, opts *LogOptions) http.HandlerFunc
Create a log handler for every request it receives.
func LogHandlerFunc ¶
func LogHandlerFunc(h http.HandlerFunc, opts *LogOptions) http.HandlerFunc
LogHandlerFunc is the same as LogHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func PanicHandler ¶
Calls the wrapped handler and on panic calls the specified error handler. If the error handler is nil, responds with a 500 error message.
func PanicHandlerFunc ¶
func PanicHandlerFunc(h http.HandlerFunc, errH http.HandlerFunc) http.HandlerFunc
PanicHandlerFunc is the same as PanicHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func SessionHandler ¶
func SessionHandler(h http.Handler, opts *SessionOptions) http.HandlerFunc
Create a Session handler to offer the Session behaviour to the specified handler.
func SessionHandlerFunc ¶
func SessionHandlerFunc(h http.HandlerFunc, opts *SessionOptions) http.HandlerFunc
SessionHandlerFunc is the same as SessionHandler, it is just a convenience signature that accepts a func(http.ResponseWriter, *http.Request) instead of a http.Handler interface. It saves the boilerplate http.HandlerFunc() cast.
func StaticFileHandler ¶
func StaticFileHandler(path string) http.HandlerFunc
StaticFileHandler, unlike net/http.FileServer, serves the contents of a specific file when it is called.
func Unauthorized ¶
func Unauthorized(w http.ResponseWriter, realm string)
Writes an unauthorized response to the client, specifying the expected authentication information.
Types ¶
type ChainableHandler ¶
type ChainableHandler interface { http.Handler Chain(http.Handler) ChainableHandler ChainFunc(http.HandlerFunc) ChainableHandler }
ChainableHandler is a valid Handler interface, and adds the possibility to chain other handlers.
func ChainHandlerFuncs ¶
func ChainHandlerFuncs(h ...http.HandlerFunc) ChainableHandler
Helper function to chain multiple handler functions in a single call.
func ChainHandlers ¶
func ChainHandlers(h ...http.Handler) ChainableHandler
Helper function to chain multiple handlers in a single call.
func NewChainableHandler ¶
func NewChainableHandler(h http.Handler) ChainableHandler
Convert a standard http handler to a chainable handler interface.
type GhostWriter ¶
type GhostWriter interface { http.ResponseWriter UserName() string User() interface{} Context() map[interface{}]interface{} Session() *Session }
Interface giving easy access to the most common augmented features.
type HeaderMatchType ¶
type HeaderMatchType int
Kind of match to apply to the header check.
const ( HmEquals HeaderMatchType = iota HmStartsWith HmEndsWith HmContains )
type LogOptions ¶
type LogOptions struct { LogFn func(string, ...interface{}) // Defaults to ghost.LogFn if nil Format string Tokens []string CustomTokens map[string]func(http.ResponseWriter, *http.Request) string Immediate bool DateFormat string }
LogHandler options
func NewLogOptions ¶
func NewLogOptions(l func(string, ...interface{}), ft string, tok ...string) *LogOptions
Create a new LogOptions struct. The DateFormat defaults to time.RFC3339.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
In-memory implementation of a session store. Not recommended for production use.
func (*MemoryStore) Clear ¶
func (this *MemoryStore) Clear() error
Clear all sessions from the store.
func (*MemoryStore) Delete ¶
func (this *MemoryStore) Delete(id string) error
Delete the specified session ID from the store.
func (*MemoryStore) Get ¶
func (this *MemoryStore) Get(id string) (*Session, error)
Get the requested session from the store.
func (*MemoryStore) Len ¶
func (this *MemoryStore) Len() int
Get the number of sessions saved in the store.
func (*MemoryStore) Set ¶
func (this *MemoryStore) Set(sess *Session) error
Save the session to the store.
type RedisStore ¶
type RedisStore struct {
// contains filtered or unexported fields
}
func NewRedisStore ¶
func NewRedisStore(opts *RedisStoreOptions) *RedisStore
Create a redis session store with the specified options.
func (*RedisStore) Clear ¶
func (this *RedisStore) Clear() error
Clear all sessions from the store. Requires the use of a key prefix in the store options, otherwise the method refuses to delete all keys.
func (*RedisStore) Delete ¶
func (this *RedisStore) Delete(id string) error
Delete the session from the store.
func (*RedisStore) Get ¶
func (this *RedisStore) Get(id string) (*Session, error)
Get the session from the store.
func (*RedisStore) Len ¶
func (this *RedisStore) Len() int
Get the number of session keys in the store. Requires the use of a key prefix in the store options, otherwise returns -1 (cannot tell session keys from other keys).
func (*RedisStore) Set ¶
func (this *RedisStore) Set(sess *Session) error
Save the session into the store.
type RedisStoreOptions ¶
type RedisStoreOptions struct { Network string Address string ConnectTimeout time.Duration ReadTimeout time.Duration WriteTimeout time.Duration Database int // Redis database to use for session keys KeyPrefix string // If set, keys will be KeyPrefix:SessionID (semicolon added) BrowserSessServerTTL time.Duration // Defaults to 2 days }
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
The Session holds the data map that persists for the duration of the session. The information stored in this map should be marshalable for the target Session store format (i.e. json, sql, gob, etc. depending on how the store persists the data).
func GetSession ¶
func GetSession(w http.ResponseWriter) (*Session, bool)
Helper function to retrieve the session for the current request.
func (*Session) MarshalJSON ¶
Marshal the session to JSON.
func (*Session) UnmarshalJSON ¶
Unmarshal the JSON into the internal session struct.
type SessionOptions ¶
type SessionOptions struct { Store SessionStore CookieTemplate http.Cookie TrustProxy bool Secret string }
Options object for the session handler. It specified the Session store to use for persistence, the template for the session cookie (name, path, maxage, etc.), whether or not the proxy should be trusted to determine if the connection is secure, and the required secret to sign the session cookie.
func NewSessionOptions ¶
func NewSessionOptions(store SessionStore, secret string) *SessionOptions
Create a new SessionOptions struct, using default cookie and proxy values.
type SessionStore ¶
type SessionStore interface { Get(id string) (*Session, error) // Get the session from the store Set(sess *Session) error // Save the session in the store Delete(id string) error // Delete the session from the store Clear() error // Delete all sessions from the store Len() int // Get the number of sessions in the store }
SessionStore interface, must be implemented by any store to be used for session storage.
func GetSessionStore ¶
func GetSessionStore(w http.ResponseWriter) (SessionStore, bool)
Helper function to retrieve the session store
type WrapWriter ¶
type WrapWriter interface { http.ResponseWriter WrappedWriter() http.ResponseWriter }
This interface can be implemented by an augmented ResponseWriter, so that it doesn't hide other augmented writers in the chain.