app

package
v0.0.0-...-576eb72 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2014 License: MPL-2.0 Imports: 52 Imported by: 0

Documentation

Overview

Package app provides a mux implementation which does regexp based URL routing and provides functions for managing the lifecycle of a request at different points.

Index

Constants

View Source
const (
	// WILL_LISTEN is emitted just before a *gnd.la/app.App will
	// start listening. The object is the App.
	WILL_LISTEN = "gnd.la/app.will-listen"
	// DID_LISTEN is emitted after a *gnd.la/app.App starts
	// listening. The object is the App.
	DID_LISTEN = "gnd.la/app.did-listen"
	// WILL_PREPARE is emitted at the beginning of App.Prepare.
	// The object is the App.
	WILL_PREPARE = "gnd.la/app.will-prepare"
	// DID_PREPARE is emitted when App.Prepare ends without errors.
	// The object is the App.
	DID_PREPARE = "gnd.la/app.did-prepare"
)
View Source
const StaticSitePattern = "^/(.*)$"

StaticSitePattern is the pattern used in conjuction with StaticSiteHandler.

View Source
const (
	// The name of the cookie used to store the user id.
	// The cookie is signed using the gnd.la/app.App secret.
	USER_COOKIE_NAME = "user"
)

Variables

View Source
var (
	// IPXHeaders are the default headers which are used to
	// read the client's IP, in decreasing priority order.
	// You might change them if e.g. your CDN provider uses
	// different ones. Note that, for these values to have
	// any effect, the App needs to have TrustsXHeaders set
	// to true.
	IPXHeaders = []string{"X-Real-IP", "X-Forwarded-For"}
	// SchemeXHeaders are the scheme equivalent of IPXHeaders.
	SchemeXHeaders = []string{"X-Scheme", "X-Forwarded-Proto"}
)
View Source
var (
	SignInHandlerName       = "sign-in"
	SignInFromParameterName = "from"
)
View Source
var (
	// CookieSalt is the default salt used for signing
	// cookies. For extra security, you might change this
	// value but keep in mind that all previously issued
	// signed cookies will be invalidated, since their
	// signature won't match.
	CookieSalt = []byte("gnd.la/app/cookies.salt")
)

Functions

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding".

func InvalidParameterType

func InvalidParameterType(name string, typ reflect.Type)

InvalidParameterType panics with an InvalidParameterTypeError using the given parameter name and type.

func KindNotFound

func KindNotFound(kind string)

KindNotFound panics with a NotFoundError indicating what was not found (.e.g "Article not found).

func MissingParameter

func MissingParameter(name string)

MissingParameter panics with a MissingParameterError, using the given parameter name.

func NotFound

func NotFound()

NotFound panics with NotFoundError.

func SignOutHandler

func SignOutHandler(ctx *Context)

SignOutHandler can be added directly to an App. It signs out the current user (if any) and redirects back to the previous page unless the request was made via XHR.

Types

type App

type App struct {
	ContextProcessors []ContextProcessor
	ContextFinalizers []ContextFinalizer
	RecoverHandlers   []RecoverHandler

	// Logger to use when logging requests. By default, it's
	// gnd.la/log.Std, but you can set it to nil to avoid
	// logging at all and gain a bit more of performance.
	Logger *log.Logger

	// CookieOptions indicates the default options used
	// used for cookies. If nil, the default values as returned
	// by cookies.Defaults() are used.
	CookieOptions *cookies.Options
	// CookieCodec indicates the codec used for encoding and
	// decoding cookies. If nil, gob is used.
	CookieCodec *codec.Codec

	// Hasher is the hash function used to sign values. If nil,
	// it defaults to HMAC-SHA1.
	Hasher cryptoutil.Hasher

	// Cipherer is the cipher function used to encrypt values. If nil,
	// it defaults to AES.
	Cipherer cryptoutil.Cipherer
	// contains filtered or unexported fields
}

App is the central piece of a Gondola application. It routes requests, invokes the requires handlers, manages connections to the cache and the database, caches templates and stores most of the configurable parameters of a Gondola application. Use New() to initialize an App, since there are some private fields which require initialization.

Cookie configuration fields should be set from your code, since there are no configuration options for them. Note that the defaults will work fine in most cases, but applications with special security or performance requirements might need to alter them. As with other configuration parameters, these can only be changed before the app adding any included apps and must not be changed once the app starts listening.

func New

func New() *App

New returns a new App initialized with the given config. If config is nil, the default configuration (exposed via gnd.la/config) is used instead.

func (*App) AddContextFinalizer

func (app *App) AddContextFinalizer(cf ContextFinalizer)

AddContextFinalizer adds a context finalizer to the app. Context finalizers run in the order they were added and after the request has been served (even if it was stopped by a context processor). They're intended as a way to perform some logging or cleanup (e.g. closing database connections that might have been opened during the request lifetime)

func (*App) AddContextProcessor

func (app *App) AddContextProcessor(cp ContextProcessor)

AddContextProcessor adds context processor to the App. Context processors run in the same order they were added before the app starts matching the request to a handler and may alter the request in any way they see fit as well as writing to the context. If any of the processors returns true, the request is considered as served and no further processing to it is done.

func (*App) AddHook

func (app *App) AddHook(hook *template.Hook)

func (*App) AddRecoverHandler

func (app *App) AddRecoverHandler(rh RecoverHandler)

AddRecoverHandler adds a recover handler to the app. Recover handlers are executed in the order they were added in case there's a panic while serving a request. The handlers may write to the context. If any recover handler returns nil the error is considered as handled and no panic is raised.

func (*App) AddTemplateProcessor

func (app *App) AddTemplateProcessor(processor TemplateProcessor)

AddTemplateProcessor adds a new template processor. Template processors may modify a template after it's been loaded.

func (*App) AddTemplateVars

func (app *App) AddTemplateVars(vars template.VarMap)

AddTemplateVars adds additional variables which will be passed to the templates executed by this app. The values in the map might either be values or functions which receive a *Context instance and return either one or two values (the second one must be an error), in which case they will be called with the current context to obtain the variable that will be passed to the template. You must call this function before any templates have been compiled. The value for each provided variable is its default value, and it can be overriden by using ExecuteVars() rather than Execute() when executing the template.

func (*App) Address

func (app *App) Address() string

Address returns the address this app is configured to listen on. By default, it's empty, meaning the app will listen on all interfaces.

func (*App) AppendsSlash

func (app *App) AppendsSlash() bool

AppendSlash returns if the app will automatically append a slash when appropriate. See SetAppendSlash for a more detailed description.

func (*App) AssetsManager

func (app *App) AssetsManager() *assets.Manager

AssetsManager returns the manager for static assets

func (*App) Blobstore

func (app *App) Blobstore() (*blobstore.Blobstore, error)

Blobstore returns a blobstore using the default blobstore parameters, as returned by DefaultBlobstore(). Use gnd.la/config to change the default blobstore. See gnd.la/blobstore for further information on using the blobstore. Note that this function does not work on App Engine. Use Context.Blobstore instead.

func (*App) Cache

func (app *App) Cache() (*cache.Cache, error)

Cache returns this app's cache connection, using DefaultCache(). Use gnd.la/config to change the default cache. The cache.Cache is initialized only once and shared among all requests and tasks served from this app. On App Engine, this method always returns an error. Use Context.Cache instead.

func (*App) Clone

func (app *App) Clone() *App

Clone returns a copy of the *App. This is mainly useful for including an app multiple times. Note that cloning an App which has been already included is considered a programming error and will result in a panic.

func (*App) CloseContext

func (app *App) CloseContext(ctx *Context)

CloseContext closes the passed context, which should have been created via NewContext(). Keep in mind that this function is called for you most of the time. As a rule of thumb, if you don't call NewContext() yourself, you don't need to call CloseContext().

func (*App) Config

func (app *App) Config() *Config

Config returns the App configuration, which will always be non-nil. Note that is not recommended altering the Config fields from your code. Instead, use the configuration file and flags.

func (*App) EncryptSigner

func (app *App) EncryptSigner(salt []byte) (*cryptoutil.EncryptSigner, error)

EncryptSigner returns a *cryptoutil.EncryptSigner composed by App.Signer and App.Encrypter. See those methods for more details.

func (*App) Encrypter

func (app *App) Encrypter() (*cryptoutil.Encrypter, error)

Encrypter returns a *cryptoutil.Encrypter using the App Cipherer and Key to encrypt values. If the App has no Key, an error will be returned.

func (*App) ErrorHandler

func (app *App) ErrorHandler() ErrorHandler

ErrorHandler returns the error handler (if any) associated with this app

func (*App) Get

func (app *App) Get(key string) interface{}

Get returns the value for the given key, previously stored with Set.

func (*App) Handle

func (app *App) Handle(pattern string, handler Handler)

Handle is a shorthand for HandleOptions, passing nil as the Options.

func (*App) HandleAssets

func (app *App) HandleAssets(prefix string, dir string)

HandleAssets adds several handlers to the app which handle assets efficiently and allows the use of the "assset" function from the templates. This function will also modify the asset loader associated with this app. prefix might be a relative (e.g. /static/) or absolute (e.g. http://static.example.com/) url while dir should be the path to the directory where the static assets reside. You probably want to use pathutil.Relative() to define the directory relative to the application binary. Note that /favicon.ico and /robots.txt will be handled too, but they will must be in the directory which contains the rest of the assets.

func (*App) HandleNamed

func (app *App) HandleNamed(pattern string, handler Handler, name string)

HandleNamed is a shorthand for HandleOptions, passing an Options instance with just the name set.

func (*App) HandleOptions

func (app *App) HandleOptions(pattern string, handler Handler, opts *HandlerOptions)

HandleOptions adds a new handler to the App. If the Options include a non-empty name, it can be be reversed using Context.Reverse or the "reverse" template function. To add a host-specific Handler, set the Host field in Options to a non-empty string. Note that handler patterns are tried in the same order that they were added to the App.

func (*App) Include

func (app *App) Include(prefix string, included *App, containerTemplate string)

func (*App) Included

func (app *App) Included() []*App

Included returns the apps which have been included by this app.

func (*App) LanguageHandler

func (app *App) LanguageHandler() LanguageHandler

LanguageHandler returns the language handler for this app. See SetLanguageHandler() for further information about language handlers.

func (*App) ListenAndServe

func (app *App) ListenAndServe() error

ListenAndServe starts listening on the configured address and port (see Address() and Port).

func (*App) LoadTemplate

func (app *App) LoadTemplate(name string) (*Template, error)

LoadTemplate loads a template using the template loader and the asset manager assocciated with this app

func (*App) MustListenAndServe

func (app *App) MustListenAndServe()

MustListenAndServe works like ListenAndServe, but panics if there's an error

func (*App) MustReverse

func (app *App) MustReverse(name string, args ...interface{}) string

MustReverse calls Reverse and panics if it finds an error. See Reverse for further details.

func (*App) Name

func (app *App) Name() string

func (*App) NewContext

func (app *App) NewContext(p ContextProvider) *Context

NewContext initializes and returns a new context asssocciated with this app using the given ContextProvider to retrieve its arguments.

func (*App) Once

func (app *App) Once(f func(*Context))

Once executes f with the first request it receives. This is mainly used for ORM initialization on App Engine.

func (*App) Orm

func (app *App) Orm() (*orm.Orm, error)

App returns this app's ORM connection, using the default database parameters, as returned by DefaultDatabase(). Use gnd.la/config to change the default ORM. The orm.Orm is initialized only once and shared among all requests and tasks served from this app. On App Engine, this method always returns an error. Use Context.Orm instead. To perform ORM initialization, use App.Once.

func (*App) Parent

func (app *App) Parent() *App

Parent returns the parent App. Note that this is non-nil only for apps which have been included into another app.

func (*App) Prepare

func (app *App) Prepare() error

Prepare is automatically called for you. This function is only exposed because the gnd.la/app/tester package needs to call it to set the App up without making it listen on a port.

func (*App) Reverse

func (app *App) Reverse(name string, args ...interface{}) (string, error)

Reverse obtains the url given a handler name and its arguments. The number of arguments must be equal to the number of captured parameters in the patttern for the handler e.g. given the pattern ^/article/\d+/[\w\-]+/$, you should provide 2 arguments and passing 42 and "the-ultimate-answer-to-life-the-universe-and-everything" would return "/article/42/the-ultimate-answer-to-life-the-universe-and-everything/" If the handler is also restricted to a given hostname, the return value will be a scheme relative url e.g. //www.example.com/article/...

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is called from the net/http system. You shouldn't need to call this function

func (*App) Set

func (app *App) Set(key string, value interface{})

Set stores an arbitraty value associated with the given key. This is mainly used for reusable apps which require storing some global state related to the app.

Note that any keys used internally by Gondola will have the __gondola prefix, so users should not use keys starting with that string.

func (*App) SetAddress

func (app *App) SetAddress(address string)

SetAddress changes the address this app will listen on.

func (*App) SetAppendSlash

func (app *App) SetAppendSlash(b bool)

SetAppendSlash enables or disables automatic slash appending. When enabled, GET and HEAD requests for /foo will be redirected to /foo/ if there's a valid handler for that URL, rather than returning a 404. The default is true.

func (*App) SetAssetsManager

func (app *App) SetAssetsManager(manager *assets.Manager)

SetAssetsManager sets the static assets manager for the app. See the documention on gnd.la/template/assets.Manager for further information.

func (*App) SetErrorHandler

func (app *App) SetErrorHandler(handler ErrorHandler)

SetErrorHandler sets the error handler for this app. See the documentation on ErrorHandler for a more detailed description.

func (*App) SetLanguageHandler

func (app *App) SetLanguageHandler(handler LanguageHandler)

SetLanguageHandler sets the language handler for this app. The LanguageHandler is responsible for determining the language used in translations for a request. If the empty string is returned the strings won't be translated. Finally, when a app does not have a language handler it uses the language specified by DefaultLanguage().

func (*App) SetName

func (app *App) SetName(name string)

func (*App) SetTemplatesFS

func (app *App) SetTemplatesFS(fs vfs.VFS)

SetTemplatesFS sets the VFS used to load the templates associated with this app. By default, templates will be loaded from the tmpl directory relative to the application binary.

func (*App) SetTrustXHeaders

func (app *App) SetTrustXHeaders(t bool)

SetTrustXHeaders sets if the app uses X headers like X-Real-IP, X-Forwarded-For, X-Scheme and X-Forwarded-Proto to override the remote IP and scheme. This is useful when running your application behind a proxy or load balancer. The default is disabled. Please, keep in mind that enabling XHeaders processing when not running behind a proxy or load balancer which sanitizes the input *IS A SECURITY RISK*.

func (*App) SetUserFunc

func (app *App) SetUserFunc(f UserFunc)

func (*App) Signer

func (app *App) Signer(salt []byte) (*cryptoutil.Signer, error)

Signer returns a *cryptoutil.Signer using the given salt and the App Hasher and Secret to sign values. If salt is smaller than 16 bytes or the App has no Secret, an error is returned.

func (*App) TemplatesFS

func (app *App) TemplatesFS() vfs.VFS

TemplatesFS returns the VFS for the templates assocciated with this app. By default, templates will be loaded from the tmpl directory relative to the application binary.

func (*App) Transform

func (app *App) Transform(tr Transformer)

Transform transforms all the registered handlers using the given Transformer. Note that handlers registered after this call won't be transformed. This function might be used to cache an entire App using gnd.la/cache/layer.

func (*App) TrustsXHeaders

func (app *App) TrustsXHeaders() bool

TrustsXHeaders returns if the app uses X headers for determining the remote IP and scheme. See SetTrustXHeaders() for a more detailed explanation.

func (*App) UserFunc

func (app *App) UserFunc() UserFunc

type Config

type Config struct {
	// Debug indicates if debug mode is enabled. If true,
	// runtime errors generate detailed an error page with
	// stack traces and request information.
	Debug bool `help:"Enable app debug mode. This causes runtime errors to generate a detailed error page"`
	// TemplateDebug indicates if the app should handle
	// templates in debug mode. When it's enabled, assets
	// are not bundled and templates are recompiled each
	// time they are loaded.
	TemplateDebug bool `help:"Enable template debug mode. This disables asset bundling and template caching"`
	// Language indicates the language used for
	// translating strings when there's no LanguageHandler
	// or when it returns an empty string.
	Language string `help:"Set the default language for translating strings"`
	// Port indicates the port to listen on.
	Port      int         `default:"8888" help:"Port to listen on"`
	Database  *config.URL `help:"Default database to use, used by Context.Orm()"`
	Cache     *config.URL `help:"Default cache, returned by Context.Cache()"`
	Blobstore *config.URL `help:"Default blobstore, returned by Context.Blobstore()"`
	// Secret indicates the secret associated with the app,
	// which is used for signed cookies. It should be a
	// random string with at least 32 characters.
	// You can use gondola random-string to generate one.
	Secret string `help:"Secret used for, among other things, hashing cookies"`
	// EncriptionKey is the encryption key for used by the
	// app for, among other things, encrypted cookies. It should
	// be a random string of 16 or 24 or 32 characters.
	EncryptionKey string `help:"Key used for encryption (e.g. encrypted cookies)"`
}

Type Config is represents the App configuration.

type Context

type Context struct {
	http.ResponseWriter
	R *http.Request
	// contains filtered or unexported fields
}

func (*Context) AddHeader

func (c *Context) AddHeader(key string, value string)

AddHeader is a shorthand for Context.Header().Add

func (*Context) App

func (c *Context) App() *App

App returns the App this Context originated from.

func (*Context) BadRequest

func (c *Context) BadRequest(args ...interface{})

BadRequest is equivalent to calling Context.Error() with http.StatusBadRequest as the error code.

func (*Context) BadRequestf

func (c *Context) BadRequestf(format string, args ...interface{})

BadRequestf is equivalent to calling Context.Errorf() with http.StatusBadRequest as the error code.

func (*Context) BasicAuth

func (c *Context) BasicAuth() (*url.Userinfo, error)

BasicAuth returns the basic user authentication info as a *url.Userinfo. If the Authorization is not present or it's not correctly formed, an error is returned.

func (*Context) Blobstore

func (c *Context) Blobstore() *blobstore.Blobstore

Blobstore is a shorthand for ctx.App().Blobstore(), but panics in case of error instead of returning it.

func (*Context) Cache

func (c *Context) Cache() *cache.Cache

Cache is a shorthand for ctx.App().Cache(), but panics in case of error, instead of returning it.

func (*Context) Cached

func (c *Context) Cached() bool

Cached() returns true if the request was cached by a cache layer. See gnd.la/cache/layer for more information.

func (*Context) Close

func (c *Context) Close()

Close closes any resources opened by the context. It's automatically called by the App, so you don't need to call it manually

func (*Context) Cookies

func (c *Context) Cookies() *cookies.Cookies

Cookies returns a coookies.Cookies object which can be used to set and delete cookies. See the documentation on gnd.la/cookies for more information.

func (*Context) Count

func (c *Context) Count() int

Count returns the number of elements captured by the pattern which matched the handler.

func (*Context) Elapsed

func (c *Context) Elapsed() time.Duration

Elapsed returns the duration since this context started processing the request.

func (*Context) Error

func (c *Context) Error(code int, args ...interface{})

Error replies to the request with the specified HTTP code. The error message is constructed from the given arguments using fmt.Sprint. If an error handler has been defined for the App (see App.SetErrorHandler), it will be given the opportunity to intercept the error and provide its own response.

Note that the standard 4xx and 5xx errors will use a default error message if none is provided.

See also Context.Errorf, Context.NotFound, Context.NotFoundf, Context.Forbidden, Context.Forbiddenf, Context.BadRequest and Context.BadRequestf.

func (*Context) Errorf

func (c *Context) Errorf(code int, format string, args ...interface{})

Errorf works like Context.Error, but formats the error message using fmt.Sprintf.

func (*Context) Execute

func (c *Context) Execute(name string, data interface{}) error

Execute loads the template with the given name using the App template loader and executes it with the data argument.

func (*Context) Forbidden

func (c *Context) Forbidden(args ...interface{})

Forbidden is equivalent to to Context.Error() with http.StatusForbidden as the error code.

func (*Context) Forbiddenf

func (c *Context) Forbiddenf(format string, args ...interface{})

Forbiddenf is equivalent to to Context.Errorf() with http.StatusForbidden as the error code.

func (*Context) FormValue

func (c *Context) FormValue(name string) string

FormValue returns the result of performing FormValue on the incoming request and trims any whitespaces on both sides. See the documentation for net/http for more details.

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get returns the value for the given key, previously stored with Set.

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

GetHeader is a shorthand for Context.R.Header.Get()

func (*Context) Go

func (c *Context) Go(f func(*Context))

Go spawns a new goroutine using a copy of the given Context suitable for using after the request has been serviced (id est, in goroutines spawned from the Handler which might outlast the Handler's lifetime). Additionaly, Go also handles error recovering and profiling in the spawned goroutine. The initial Context can also wait for all background contexts to finish by calling Wait().

In the following example, the handler finishes and returns the executed template while CrunchData is still potentially running.

 func MyHandler(ctx *app.Context) {
	data := AcquireData(ctx)
	ctx.Go(func (c *app.Context) {
	    CrunchData(c, data) // note the usage of c rather than ctx
	}
	ctx.MustExecute("mytemplate.html", data)
 }

func (*Context) HandlerName

func (c *Context) HandlerName() string

HandlerName returns the name of the handler which handled this context

func (*Context) IndexValue

func (c *Context) IndexValue(idx int) string

IndexValue returns the captured parameter at the given index or an empty string if no such parameter exists. Pass -1 to obtain the whole match.

func (*Context) IsXHR

func (c *Context) IsXHR() bool

IsXHR returns wheter the request was made via XMLHTTPRequest. Internally, it uses X-Requested-With, which is set by all major JS libraries.

func (*Context) Language

func (c *Context) Language() string

func (*Context) Logger

func (c *Context) Logger() log.Interface

Logger returns a Logger which allows logging mesages in several levels. See gnd.la/log.Interface interface for more information. Note that this function will always return non-nil even when logging is disabled, so it's safe to call any gnd.la/log.Interface methods unconditionally (i.e. don't check if the returned value is nil, it'll never be).

func (*Context) MustExecute

func (c *Context) MustExecute(name string, data interface{})

MustExecute works like Execute, but panics if there's an error

func (*Context) MustParseFormValue

func (c *Context) MustParseFormValue(name string, arg interface{})

MustParseFormValue works like ParseFormValue but raises a MissingParameterError if the parameter is missing or an InvalidParameterTypeError if the parameter does not have the required type

func (*Context) MustParseIndexValue

func (c *Context) MustParseIndexValue(idx int, arg interface{})

MustParseIndexValue works like ParseIndexValue but raises a MissingParameterError if the parameter is missing or an InvalidParameterTypeError if the parameter does not have the required type

func (*Context) MustRedirectReverse

func (c *Context) MustRedirectReverse(permanent bool, name string, args ...interface{})

MustRedirectReverse works like RedirectReverse, but panics if there's an error.

func (*Context) MustReverse

func (c *Context) MustReverse(name string, args ...interface{}) string

MustReverse is a shorthand for Context.Reverse which panics instead of returning an error.

func (*Context) MustSendMail

func (c *Context) MustSendMail(template string, data interface{}, msg *mail.Message)

MustSendMail works like SendMail, but panics if there's an error.

func (*Context) MustSignIn

func (c *Context) MustSignIn(user User)

MustSignIn works like SignIn, but panics if there's an error.

func (*Context) NotFound

func (c *Context) NotFound(args ...interface{})

NotFound is equivalent to Context.Error() with http.StatusNotFound as the error code.

func (*Context) NotFoundf

func (c *Context) NotFoundf(format string, args ...interface{})

NotFoundf is equivalent to Context.Errorf() with http.StatusNotFound as the error code.

func (*Context) Orm

func (c *Context) Orm() *orm.Orm

Orm is a shorthand for ctx.App().Orm(), but panics in case of error, rather than returning it.

func (*Context) Pager

func (c *Context) Pager() paginator.Pager

Pager returns a pager which can be used with a paginator.Paginator. In order for the automatic pager to work, the request must be served by a named handler (so the Pager can call ctx.Reverse), use only named capture parameters in its pattern and have the last parameter be optional and named page (which indicates the page number). e.g. a handler like this would work.

App.HandleNamed("^/c/(?P<cat_id>\\d+)/(?:(?P<page>\\d+)/)?$", ListHandler, "category")

Then the handler would need to retrieve the page number and use it to create the paginator.

 const itemsPerPage = 42
 var page int
 ctx.ParseParamValue("page", &page)
 if page <= 0 {
	page = 1
 }
 count, err := ...
 items, err := ...
 p := paginator.New(int(count+1)/itemsPerPage, page, ctx.Pager())

func (*Context) ParamValue

func (c *Context) ParamValue(name string) string

ParamValue returns the named captured parameter with the given name or an empty string if it does not exist.

func (*Context) Params

func (c *Context) Params() []string

Params returns the parameter names provided to the Context. In the case of URL handlers, the parameter names are the named capture groups in the URL pattern.

func (*Context) ParseFormValue

func (c *Context) ParseFormValue(name string, arg interface{}) bool

ParseFormValue tries to parse the named form value into the given arg e.g. var f float32 ctx.ParseFormValue("quality", &f) var width uint ctx.ParseFormValue("width", &width) Supported types are: bool, u?int(8|16|32|64)? and float(32|64) Internally, ParseFormValue uses gnd.la/form/input to parse its arguments.

func (*Context) ParseIndexValue

func (c *Context) ParseIndexValue(idx int, arg interface{}) bool

ParseIndexValue uses the captured parameter at the given index and tries to parse it into the given argument. See ParseFormValue for examples as well as the supported types.

func (*Context) ParseParamValue

func (c *Context) ParseParamValue(name string, arg interface{}) bool

ParseParamValue uses the named captured parameter with the given name and tries to parse it into the given argument. See ParseFormValue for examples as well as the supported types.

func (*Context) Redirect

func (c *Context) Redirect(redir string, permanent bool)

Redirect sends an HTTP redirect to the client, using the provided redirect, which may be either absolute or relative. The permanent argument indicates if the redirect should be sent as a permanent or a temporary one.

func (*Context) RedirectBack

func (c *Context) RedirectBack()

RedirectBack redirects the user to the previous page using a temporary redirect. The previous page is determined by first looking at the "from" GET or POST parameter (like in the sign in form) and then looking at the "Referer" header. If there's no previous page or the previous page was from another host, a redirect to / is issued.

func (*Context) RedirectReverse

func (c *Context) RedirectReverse(permanent bool, name string, args ...interface{}) error

RedirectReverse calls Reverse to find the URL and then sends the redirect to the client. See the documentation on App.Reverse for further details.

func (*Context) RemoteAddress

func (c *Context) RemoteAddress() string

RemoteAddress returns the remote IP without the port number.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the *http.Request associated with this context. Note that users should access the Context.R field directly, rather than using this method (it solely exists for App Engine compatibility).

func (*Context) RequireFormValue

func (c *Context) RequireFormValue(name string) string

RequireFormValue works like FormValue, but raises a MissingParameter error if the value is not present or empty.

func (*Context) RequireIndexValue

func (c *Context) RequireIndexValue(idx int) string

RequireIndexValue works like IndexValue, but raises a MissingParameter error if the value is not present or empty.

func (*Context) Reverse

func (c *Context) Reverse(name string, args ...interface{}) (string, error)

Reverse calls Reverse on the App this context originated from. See App.Reverse for details. Note that Context.Reverse might return a different value than App.Reverse for host-specific handlers, since App.Reverse will return a protocol-relative URL (e.g. //www.gondolaweb.com) while Context.Reverse can return an absolute URL (e.g. http://www.gondolaweb.com) if the Context has a Request associated with it.

func (*Context) SendMail

func (c *Context) SendMail(template string, data interface{}, msg *mail.Message) error

SendMail is a shorthand function for sending an email from a template. If the loaded gnd.la/template.Template.ContentType() returns a string containing "html", the gnd.la/net/mail.Message HTMLBody field is set, other the TextBody field is used. Note that if template is empty, the msg is passed unmodified to mail.Send(). Other Message fields are never altered.

Note: mail.Send does not work on App Engine, users must always use this function instead.

func (*Context) ServedFromCache

func (c *Context) ServedFromCache() bool

ServedFromCache returns true if the request was served by a cache layer. See gnd.la/cache/layer for more information.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set stores an arbitraty value associated with the given key.

Note that any keys used internally by Gondola will have the __gondola prefix, so users should not use keys starting with that string.

func (*Context) SetHeader

func (c *Context) SetHeader(key string, value string)

SetHeader is a shorthand for Context.Header().Set

func (*Context) SignIn

func (c *Context) SignIn(user User) error

SignIn sets the cookie for signin in the given user. The default cookie options for the App are used.

func (*Context) SignOut

func (c *Context) SignOut()

SignOut deletes the signed in cookie for the current user. If there's no current signed in user, it does nothing.

func (*Context) StatusCode

func (c *Context) StatusCode() int

StatusCode returns the response status code. If the headers haven't been written yet, it returns 0

func (*Context) T

func (c *Context) T(str string) string

func (*Context) Tc

func (c *Context) Tc(context string, str string) string

func (*Context) Tn

func (c *Context) Tn(singular string, plural string, n int) string

func (*Context) Tnc

func (c *Context) Tnc(context string, singular string, plural string, n int) string

func (*Context) TranslationTable

func (c *Context) TranslationTable() *table.Table

func (*Context) URL

func (c *Context) URL() *url.URL

URL return the absolute URL for the current request.

func (*Context) User

func (c *Context) User() User

User returns the currently signed in user, or nil if there's no user. In order to find the user, the App must have a UserFunc defined.

func (*Context) Wait

func (c *Context) Wait()

Wait waits for any pending background contexts spawned from Go() to finish. If there are no background contexts spawned from this context, this functions returns immediately.

func (*Context) Write

func (c *Context) Write(data []byte) (int, error)

func (*Context) WriteHeader

func (c *Context) WriteHeader(code int)

func (*Context) WriteJSON

func (c *Context) WriteJSON(data interface{}) (int, error)

WriteJSON is equivalent to serialize.WriteJSON(ctx, data)

func (*Context) WriteString

func (c *Context) WriteString(s string) (int, error)

func (*Context) WriteXML

func (c *Context) WriteXML(data interface{}) (int, error)

WriteXML is equivalent to serialize.WriteXML(ctx, data)

type ContextFinalizer

type ContextFinalizer func(*Context)

type ContextProcessor

type ContextProcessor func(*Context) bool

ContextProcessor functions run before the request is matched to a Handler and might alter the context in any way they see fit

type ContextProvider

type ContextProvider interface {
	// Count returns the number of arguments
	Count() int
	// Arg returns the argument at index idx or the
	// empty string if there's no such argument.
	Arg(idx int) string
	// Param returns the parameter named with the given
	// name or the empty string if there's no such parameter.
	Param(name string) string
	// Params returns the names of the available parameters,
	// in the order they were specified.
	Params() []string
}

ContextProvider represents the interface which types which provide a context with its arguments and parameters must satisfy.

type DataHandler

type DataHandler func(*Context) (interface{}, error)

DataHandler is a handler than returns the data as an interface{} rather than sending it back to the client. A DataHandler can't be added directly to an App, it must be wrapped with a function which creates a Handler, like JSONHandler or ExecuteHandler.

type Error

type Error interface {
	error
	StatusCode() int
}

Error represents an error which, besides a message, has also an assocciated status code to be sent to the client.

type ErrorHandler

type ErrorHandler func(*Context, string, int) bool

ErrorHandler is called before an error is sent to the client. The parameters are the current context, the error message and the error code. If the handler returns true, the error is considered as handled and no further data is sent to the client.

type Handler

type Handler func(*Context)

Handler is the function type used to satisfy a request (not necessarily HTTP) with a given *Context. Gondola uses Handler for responding to HTTP requests (via gnd.la/app.App), executing commands (via gnd.la/commands) and tasks (via gnd.la/task).

func Anonymous

func Anonymous(handler Handler) Handler

Anonymous returns a new handler which redirects signed in users to the previous page (or the root page if there's no referrer).

func ExecuteHandler

func ExecuteHandler(dataHandler DataHandler, template string) Handler

ExecuteHandler returns a Handler which executes the given DataHandler to obtain the data and, if it succeeds, executes the given template passing it the obtained data.

func HandlerFromHTTPFunc

func HandlerFromHTTPFunc(f http.HandlerFunc) Handler

HandlerFromHTTPFunc returns a Handler from an http.HandlerFunc.

func HandlerFromHTTPHandler

func HandlerFromHTTPHandler(h http.Handler) Handler

HandlerFromHTTPHandler returns a Handler from an http.Handler.

func Headers

func Headers(handler Handler, headers Header) Handler

Headers returns a new Handler which adds the given headers to every response.

func JSONHandler

func JSONHandler(dataHandler DataHandler) Handler

JSONHandler returns a Handler which executes the given DataHandler to obtain the data and, if it succeeds, serializes the data using JSON and returns it back to the client.

func Private

func Private(handler Handler) Handler

Private returns a new Handler which adds the headers Vary: Cookie and Cache-Control: private.

func RedirectHandler

func RedirectHandler(destination string, permanent bool) Handler

RedirectHandler returns a handler which redirects to the given url. The permanent argument indicates if the redirect should be temporary or permanent. The destination string might contain expanded replacements by using the ${x} notation. If x is a number, the expression will expand to the value returned by ctx.IndexValue(x), otherwise it will expand to the result of ctx.ParamValue(x).

func SignedIn

func SignedIn(handler Handler) Handler

SignedIn returns a new Handler which requires a signed in user to be executed. If there's no signed in user, it returns a redirect to the handler named "sign-in", indicating the previous url in the "from" parameter. If there's no handler named "sign-in", it panics. It also adds "Cookie" to the Vary header, and "private" to the Cache-Control header.

func StaticSiteHandler

func StaticSiteHandler(disabled []string, data interface{}) Handler

StaticSiteHandler returns a handler which serves the template named by the request path (e.g. /foo will serve foo.html). The disabled argument can be used to always return a 404 for some paths, like templates which are only used as the base or included in another ones. The data argument is passed as is to template.Template.Execute. Usually, this handler should be used with StaticSitePattern.

func TemplateHandler

func TemplateHandler(name string, data interface{}) Handler

TemplateHandler returns a handler which executes the given template with the given data.

func Vary

func Vary(handler Handler, values []string) Handler

Vary returns a new Handler which adds the given values to the Vary header.

type HandlerInfo

type HandlerInfo struct {
	Handler Handler
	Options *HandlerOptions
}

func NamedHandler

func NamedHandler(name string, handler Handler) *HandlerInfo

type HandlerOptions

type HandlerOptions struct {
	// Name indicates the Handler's name, which might be used
	// to reverse it with Context.Reverse of the "reverse"
	// template function.
	Name string
	// Host specifies the host the Handler will match. If non-empty,
	// only requests to this specific host will match the Handler.
	Host string
}

HandlerOptions represent the different options which might be specified when registering a Handler in an App.

type Header http.Header

A Header represents the key-value pairs in an HTTP header. Header is also convertible to http.Header.

func (Header) Add

func (h Header) Add(key, value string)

Add adds the key, value pair to the header. It appends to any existing values associated with key.

func (Header) Del

func (h Header) Del(key string)

Del deletes the values associated with key.

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". To access multiple values of a key, access the map directly with CanonicalHeaderKey.

func (Header) Set

func (h Header) Set(key, value string)

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

type InvalidParameterTypeError

type InvalidParameterTypeError struct {
	*MissingParameterError
	Type reflect.Type
}

Indicates that a parameter does not have the required type (e.g. an int was requested but a string was provided). Its status code is 400.

func (*InvalidParameterTypeError) Error

func (i *InvalidParameterTypeError) Error() string

type LanguageHandler

type LanguageHandler func(*Context) string

LanguageHandler is use to determine the language when serving a request. See App.SetLanguageHandler().

type MissingParameterError

type MissingParameterError struct {
	Name string
}

Indicates that a required parameter is mising. Its status code is 400.

func (*MissingParameterError) Error

func (m *MissingParameterError) Error() string

func (*MissingParameterError) StatusCode

func (m *MissingParameterError) StatusCode() int

type NotFoundError

type NotFoundError struct {
	Kind string
}

Indicates that something wasn't found. Its status code is 404.

func (*NotFoundError) Error

func (n *NotFoundError) Error() string

func (*NotFoundError) StatusCode

func (n *NotFoundError) StatusCode() int

type RecoverHandler

type RecoverHandler func(*Context, interface{}) interface{}

type Template

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

Template is a thin wrapper around gnd.la/template.Template, which simplifies execution, provides extra functions, like URL reversing and translations, and always passes the current *Context as the template Context.

When executing these templates, at least the @Ctx variable is always passed to the template, representing the current *app.Context. To define additional variables, use App.AddTemplateVars.

Most of the time, users should not use this type directly, but rather Context.Execute and Context.MustExecute.

To write the result of the template to an arbitraty io.Writer rather than to a *Context, load the template using App.LoadTemplate and then use Template.ExecuteTo.

func LoadTemplate

func LoadTemplate(app *App, fs vfs.VFS, manager *assets.Manager, name string) (*Template, error)

LoadTemplate loads a template for the given *App, using the given vfs.VFS and *assets.Manager. Note that users should rarely use this function and most of the time App.LoadTemplate() should be used. The purpose of this function is allowing apps to load templates from multiple sources. Note that, as opposed to App.LoadTemplate, this function does not perform any caching.

func (*Template) Execute

func (t *Template) Execute(ctx *Context, data interface{}) error

Execute executes the template, writing its result to the given *Context. Note that Template uses an intermediate buffer, so nothing will be written to the *Context in case of error.

func (*Template) ExecuteTo

func (t *Template) ExecuteTo(w io.Writer, ctx *Context, data interface{}) error

ExecuteTo works like Execute, but allows writing the template result to an arbitraty io.Writer rather than the current *Context.

type TemplateProcessor

type TemplateProcessor func(*template.Template) (*template.Template, error)

type Transformer

type Transformer func(Handler) Handler

Transformer is a function which receives a Handler and returns another handler, usually with some functionality added (e.g. requiring a signed in user, or adding a cache layer).

type User

type User interface {
	// Returns the numeric id of the user
	Id() int64
	// IsAdmin returns wheter the user is an administrator.
	IsAdmin() bool
}

User is the interface implemented by any struct that can be used to represent a user in a Gondola app.

type UserFunc

type UserFunc func(ctx *Context, id int64) User

UserFunc is called when getting the current signed in user. It receives the current context and the user id and must return the current user (if any).

Directories

Path Synopsis
Package cookies contains helper functions for setting and retrieving cookies, including signed and encrypted ones.
Package cookies contains helper functions for setting and retrieving cookies, including signed and encrypted ones.
Package serialize provides conveniency functions for serializing values to either JSON or XML
Package serialize provides conveniency functions for serializing values to either JSON or XML
Package tester implements functions for testing and benchmarking Gondola applications.
Package tester implements functions for testing and benchmarking Gondola applications.

Jump to

Keyboard shortcuts

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