ghost: github.com/PuerkitoBio/ghost/handlers Index | Files

package handlers

import "github.com/PuerkitoBio/ghost/handlers"

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

Package Files

basicauth.go chain.go context.go doc.go favicon.go ghost.go gzip.go header.go log.go panic.go redisstore.go reswriter.go session.go sstore.go static.go

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

func BadRequest Uses

func BadRequest(w http.ResponseWriter, msg string)

Writes a bad request response to the client, with an optional message.

func BasicAuthHandler Uses

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 Uses

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 Uses

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 Uses

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 Uses

func FaviconHandler(h http.Handler, path string, maxAge time.Duration) http.HandlerFunc

Efficient favicon handler, mostly a port of node's Connect library implementation of the favicon middleware. https://github.com/senchalabs/connect

func FaviconHandlerFunc Uses

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 Uses

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 Uses

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 Uses

func GetContext(w http.ResponseWriter) (map[interface{}]interface{}, bool)

Helper function to retrieve the context map from the ResponseWriter interface.

func GetPanicError Uses

func GetPanicError(w http.ResponseWriter) (interface{}, bool)

Helper function to retrieve the panic error, if any.

func GetResponseWriter Uses

func GetResponseWriter(w http.ResponseWriter,
    predicate func(http.ResponseWriter) bool) (http.ResponseWriter, bool)

Helper function to retrieve a specific ResponseWriter.

func GetUser Uses

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 Uses

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 Uses

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 Uses

func HeaderMatch(hdr http.Header, nm string, matchType HeaderMatchType, test string) bool

Check if the specified header matches the test string, applying the header match type specified.

func LogHandler Uses

func LogHandler(h http.Handler, opts *LogOptions) http.HandlerFunc

Create a log handler for every request it receives.

func LogHandlerFunc Uses

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 Uses

func PanicHandler(h http.Handler, errH http.Handler) http.HandlerFunc

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 Uses

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 Uses

func SessionHandler(h http.Handler, opts *SessionOptions) http.HandlerFunc

Create a Session handler to offer the Session behaviour to the specified handler.

func SessionHandlerFunc Uses

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 Uses

func StaticFileHandler(path string) http.HandlerFunc

StaticFileHandler, unlike net/http.FileServer, serves the contents of a specific file when it is called.

func Unauthorized Uses

func Unauthorized(w http.ResponseWriter, realm string)

Writes an unauthorized response to the client, specifying the expected authentication information.

type ChainableHandler Uses

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 Uses

func ChainHandlerFuncs(h ...http.HandlerFunc) ChainableHandler

Helper function to chain multiple handler functions in a single call.

func ChainHandlers Uses

func ChainHandlers(h ...http.Handler) ChainableHandler

Helper function to chain multiple handlers in a single call.

func NewChainableHandler Uses

func NewChainableHandler(h http.Handler) ChainableHandler

Convert a standard http handler to a chainable handler interface.

type GhostWriter Uses

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 Uses

type HeaderMatchType int

Kind of match to apply to the header check.

const (
    HmEquals HeaderMatchType = iota
    HmStartsWith
    HmEndsWith
    HmContains
)

type LogOptions Uses

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 Uses

func NewLogOptions(l func(string, ...interface{}), ft string, tok ...string) *LogOptions

Create a new LogOptions struct. The DateFormat defaults to time.RFC3339.

type MemoryStore Uses

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

In-memory implementation of a session store. Not recommended for production use.

func NewMemoryStore Uses

func NewMemoryStore(capc int) *MemoryStore

Create a new memory store.

func (*MemoryStore) Clear Uses

func (this *MemoryStore) Clear() error

Clear all sessions from the store.

func (*MemoryStore) Delete Uses

func (this *MemoryStore) Delete(id string) error

Delete the specified session ID from the store.

func (*MemoryStore) Get Uses

func (this *MemoryStore) Get(id string) (*Session, error)

Get the requested session from the store.

func (*MemoryStore) Len Uses

func (this *MemoryStore) Len() int

Get the number of sessions saved in the store.

func (*MemoryStore) Set Uses

func (this *MemoryStore) Set(sess *Session) error

Save the session to the store.

type RedisStore Uses

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

func NewRedisStore Uses

func NewRedisStore(opts *RedisStoreOptions) *RedisStore

Create a redis session store with the specified options.

func (*RedisStore) Clear Uses

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 Uses

func (this *RedisStore) Delete(id string) error

Delete the session from the store.

func (*RedisStore) Get Uses

func (this *RedisStore) Get(id string) (*Session, error)

Get the session from the store.

func (*RedisStore) Len Uses

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 Uses

func (this *RedisStore) Set(sess *Session) error

Save the session into the store.

type RedisStoreOptions Uses

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 Uses

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 Uses

func GetSession(w http.ResponseWriter) (*Session, bool)

Helper function to retrieve the session for the current request.

func (*Session) Created Uses

func (ø *Session) Created() time.Time

Get the creation time of the session.

func (*Session) ID Uses

func (ø *Session) ID() string

Gets the ID of the session.

func (*Session) IsNew Uses

func (ø *Session) IsNew() bool

Is this a new Session (created by the current request)

func (*Session) MarshalJSON Uses

func (ø *Session) MarshalJSON() ([]byte, error)

Marshal the session to JSON.

func (*Session) MaxAge Uses

func (ø *Session) MaxAge() time.Duration

Get the max age duration

func (*Session) UnmarshalJSON Uses

func (ø *Session) UnmarshalJSON(b []byte) error

Unmarshal the JSON into the internal session struct.

type SessionOptions Uses

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 Uses

func NewSessionOptions(store SessionStore, secret string) *SessionOptions

Create a new SessionOptions struct, using default cookie and proxy values.

type SessionStore Uses

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 Uses

func GetSessionStore(w http.ResponseWriter) (SessionStore, bool)

Helper function to retrieve the session store

type WrapWriter Uses

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.

Package handlers imports 20 packages (graph) and is imported by 16 packages. Updated 2016-07-14. Refresh now. Tools for package owners.