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
- Variables
- func CanonicalHeaderKey(s string) string
- func SignOutHandler(ctx *Context)
- type App
- func (app *App) AddContextFinalizer(cf ContextFinalizer)
- func (app *App) AddContextProcessor(cp ContextProcessor)
- func (app *App) AddRecoverHandler(rh RecoverHandler)
- func (app *App) AddTemplatePlugin(plugin *template.Plugin)
- func (app *App) AddTemplateProcessor(processor TemplateProcessor)
- func (app *App) AddTemplateVars(vars template.VarMap)
- func (app *App) Address() string
- func (app *App) AppendsSlash() bool
- func (app *App) AssetsManager() *assets.Manager
- func (app *App) Blobstore() (*blobstore.Blobstore, error)
- func (app *App) Cache() (*cache.Cache, error)
- func (app *App) CloseContext(ctx *Context)
- func (app *App) Config() *Config
- func (app *App) EncryptSigner(salt []byte) (*cryptoutil.EncryptSigner, error)
- func (app *App) Encrypter() (*cryptoutil.Encrypter, error)
- func (app *App) ErrorHandler() ErrorHandler
- func (app *App) Get(key interface{}) interface{}
- func (app *App) Handle(pattern string, handler Handler, opts ...HandlerOption)
- func (app *App) HandleAssets(prefix string, dir string)
- func (app *App) HandleWebsocket(pattern string, handler Handler, opts ...HandlerOption)
- func (app *App) Include(prefix string, name string, included *App, containerTemplate string)
- func (app *App) Included() []*App
- func (app *App) LanguageHandler() LanguageHandler
- func (app *App) ListenAndServe() error
- func (app *App) LoadTemplate(name string) (*Template, error)
- func (app *App) LoadTemplatePlugin(name string, pos assets.Position) error
- func (app *App) MustListenAndServe()
- func (app *App) MustLoadTemplatePlugin(name string, pos assets.Position)
- func (app *App) MustReverse(name string, args ...interface{}) string
- func (app *App) Name() string
- func (app *App) NewContext(p ContextProvider) *Context
- func (app *App) Once(f func(*Context))
- func (app *App) Orm() (*orm.Orm, error)
- func (app *App) Parent() *App
- func (app *App) Prepare() error
- func (app *App) Reverse(name string, args ...interface{}) (string, error)
- func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (app *App) Set(key, value interface{})
- func (app *App) SetAddress(address string)
- func (app *App) SetAppendSlash(b bool)
- func (app *App) SetAssetsManager(manager *assets.Manager)
- func (app *App) SetErrorHandler(handler ErrorHandler)
- func (app *App) SetLanguageHandler(handler LanguageHandler)
- func (app *App) SetTemplatesFS(fs vfs.VFS)
- func (app *App) SetTrustXHeaders(t bool)
- func (app *App) SetUserFunc(f UserFunc)
- func (app *App) Signer(salt []byte) (*cryptoutil.Signer, error)
- func (app *App) TemplatesFS() vfs.VFS
- func (app *App) Transform(tr Transformer)
- func (app *App) TrustsXHeaders() bool
- func (app *App) UserFunc() UserFunc
- type Config
- type Context
- func (c *Context) AddHeader(key string, value string)
- func (c *Context) App() *App
- func (c *Context) BadRequest(args ...interface{})
- func (c *Context) BadRequestf(format string, args ...interface{})
- func (c *Context) BasicAuth() (*url.Userinfo, error)
- func (c *Context) Blobstore() *blobstore.Blobstore
- func (c *Context) Cache() *cache.Cache
- func (c *Context) Cached() bool
- func (c *Context) Close()
- func (c *Context) Cookies() *cookies.Cookies
- func (c *Context) Count() int
- func (c *Context) DecodeJSON(v interface{}) error
- func (c *Context) Elapsed() time.Duration
- func (c *Context) Error(code int, args ...interface{})
- func (c *Context) Errorf(code int, format string, args ...interface{})
- func (c *Context) Execute(name string, data interface{}) error
- func (c *Context) Forbidden(args ...interface{})
- func (c *Context) Forbiddenf(format string, args ...interface{})
- func (c *Context) FormValue(name string) string
- func (c *Context) Get(key interface{}) interface{}
- func (c *Context) GetHeader(key string) string
- func (c *Context) Go(f func(*Context))
- func (c *Context) HandlerName() string
- func (c *Context) IndexValue(idx int) string
- func (c *Context) IsXHR() bool
- func (c *Context) Language() string
- func (c *Context) Logger() log.Interface
- func (c *Context) MustDecodeJSON(v interface{})
- func (c *Context) MustExecute(name string, data interface{})
- func (c *Context) MustParseFormValue(name string, arg interface{})
- func (c *Context) MustParseIndexValue(idx int, arg interface{})
- func (c *Context) MustRedirectReverse(permanent bool, name string, args ...interface{})
- func (c *Context) MustReverse(name string, args ...interface{}) string
- func (c *Context) MustSendMail(template string, data interface{}, msg *mail.Message)
- func (c *Context) MustSignIn(user User)
- func (c *Context) NotFound(args ...interface{})
- func (c *Context) NotFoundf(format string, args ...interface{})
- func (c *Context) Orm() *orm.Orm
- func (c *Context) ParamValue(name string) string
- func (c *Context) ParseFormValue(name string, arg interface{}) error
- func (c *Context) ParseIndexValue(idx int, arg interface{}) error
- func (c *Context) ParseParamValue(name string, arg interface{}) error
- func (c *Context) Provider() ContextProvider
- func (c *Context) Read(p []byte) (n int, err error)
- func (c *Context) Redirect(redir string, permanent bool)
- func (c *Context) RedirectBack()
- func (c *Context) RedirectReverse(permanent bool, name string, args ...interface{}) error
- func (c *Context) RemoteAddress() string
- func (c *Context) Request() *http.Request
- func (c *Context) RequireFormValue(name string) string
- func (c *Context) RequireIndexValue(idx int) string
- func (c *Context) Reverse(name string, args ...interface{}) (string, error)
- func (c *Context) SendMail(template string, data interface{}, msg *mail.Message) error
- func (c *Context) ServedFromCache() bool
- func (c *Context) Set(key, value interface{})
- func (c *Context) SetHeader(key string, value string)
- func (c *Context) SetStatusCode(code int)
- func (c *Context) SignIn(user User) error
- func (c *Context) SignOut()
- func (c *Context) StatusCode() int
- func (c *Context) T(str string) string
- func (c *Context) Tc(context string, str string) string
- func (c *Context) Tn(singular string, plural string, n int) string
- func (c *Context) Tnc(context string, singular string, plural string, n int) string
- func (c *Context) TranslationTable() *table.Table
- func (c *Context) URL() *url.URL
- func (c *Context) User() User
- func (c *Context) Wait()
- func (c *Context) Websocket() *websocket.Conn
- func (c *Context) WebsocketURL(rel string) (*url.URL, error)
- func (c *Context) Write(data []byte) (int, error)
- func (c *Context) WriteHeader(code int)
- func (c *Context) WriteJSON(data interface{}) (int, error)
- func (c *Context) WriteString(s string) (int, error)
- func (c *Context) WriteXML(data interface{}) (int, error)
- type ContextFinalizer
- type ContextProcessor
- type ContextProvider
- type DataHandler
- type Error
- type ErrorHandler
- type Handler
- func Anonymous(handler Handler) Handler
- func ExecuteHandler(dataHandler DataHandler, template string) Handler
- func HandlerFromHTTPFunc(f http.HandlerFunc) Handler
- func HandlerFromHTTPHandler(h http.Handler) Handler
- func Headers(handler Handler, headers Header) Handler
- func JSONHandler(dataHandler DataHandler) Handler
- func Private(handler Handler) Handler
- func RedirectHandler(destination string, permanent bool) Handler
- func SignedIn(handler Handler) Handler
- func StaticSiteHandler(disabled []string, data interface{}) Handler
- func TemplateHandler(name string, data interface{}) Handler
- func Vary(handler Handler, values []string) Handler
- type HandlerOption
- type HandlerOptions
- type Header
- type InvalidParameterError
- type LanguageHandler
- type MissingParameterError
- type NotFoundError
- type RecoverHandler
- type Template
- type TemplateProcessor
- type Transformer
- type User
- type UserFunc
Constants ¶
const StaticSitePattern = "^/(.*)$"
StaticSitePattern is the pattern used in conjuction with StaticSiteHandler.
const ( // The name of the cookie used to store the user id. // The cookie is signed using the gondola/app.App secret. USER_COOKIE_NAME = "user" )
Variables ¶
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"} )
var ( SignInHandlerName = "sign-in" SignInFromParameterName = "from" )
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("gondola/app/cookies.salt") )
var Signals = struct { // WillListen is emitted just before a *gondola/app.App will // start listening. WillListen *appSignal // DidListen is emitted after a *gondola/app.App starts // listening. DidListen *appSignal // WillPrepare is emitted at the beginning of App.Prepare. WillPrepare *appSignal // DidPrepare is emitted when App.Prepare ends without errors. DidPrepare *appSignal }{ WillListen: &appSignal{signals.New("will-listen")}, DidListen: &appSignal{signals.New("did-listen")}, WillPrepare: &appSignal{signals.New("will-prepare")}, DidPrepare: &appSignal{signals.New("did-prepare")}, }
Signals declares the signals emitted by this package. See gondola/signals for more information.
Functions ¶
func CanonicalHeaderKey ¶
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 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 // gondola/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 NewWithConfig ¶
NewWithConfig returns a new App initialized with the given config. If config is nil, the default configuration (exposed via gondola/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) 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) AddTemplatePlugin ¶
AddTemplatePlugin adds a *template.Plugin which will be added to all templates rendered by this app. See gondola/template.Plugin for more information.
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 ¶
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 ¶
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 ¶
AppendSlash returns if the app will automatically append a slash when appropriate. See SetAppendSlash for a more detailed description.
func (*App) AssetsManager ¶
AssetsManager returns the manager for static assets
func (*App) Blobstore ¶
Blobstore returns a blobstore using the default blobstore parameters, as returned by DefaultBlobstore(). Use gondola/config to change the default blobstore. See gondola/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 ¶
Cache returns this app's cache connection, using DefaultCache(). Use gondola/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) CloseContext ¶
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 ¶
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 interface{}) interface{}
Get implements gondola/kvs.Storage.Get
func (*App) Handle ¶
func (app *App) Handle(pattern string, handler Handler, opts ...HandlerOption)
Handle adds a new handler to the App. See the available HandlerOption functions and the HandlerOptions type for the available handler options.
A named handler can be be reversed using Context.Reverse or the "reverse" template function. Use NamedHandler() to set a name.
To add a host-specific Handler, use HostHandler().
func (*App) HandleAssets ¶
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) HandleWebsocket ¶
func (app *App) HandleWebsocket(pattern string, handler Handler, opts ...HandlerOption)
HandleWebsocket has the same semantics as App.Handle, but responds to websocket requests rather than normal HTTP(S) requests. Use Context.Websocket to retrieve the *websocket.Conn in the Handler.
func (*App) Include ¶
Include should be considered a private API. It's only exported so gondola/app/reusableapp can call into it.
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 ¶
ListenAndServe starts listening on the configured address and port (see Address() and Port).
func (*App) LoadTemplate ¶
LoadTemplate loads a template using the template loader and the asset manager assocciated with this app
func (*App) LoadTemplatePlugin ¶
LoadTemplatePlugin loads the template from name, using the app templates VFS and assets manager, and then adds it as a plugin at the given position. See also App.AddTemplatePlugin.
func (*App) MustListenAndServe ¶
func (app *App) MustListenAndServe()
MustListenAndServe works like ListenAndServe, but panics if there's an error
func (*App) MustLoadTemplatePlugin ¶
MustLoadTemplatePlugin is a shorthand for LoadTemplatesPlugin which panics when there's an error.
func (*App) MustReverse ¶
MustReverse calls Reverse and panics if it finds an error. See Reverse for further details.
func (*App) Name ¶
Name returns the app name. Note that only apps which have been included into another app have a name. The main app will always have an empty name.
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 ¶
Once executes f with the first request it receives. This is mainly used for ORM initialization on App Engine.
func (*App) Orm ¶
App returns this app's ORM connection, using the default database parameters, as returned by DefaultDatabase(). Use gondola/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 ¶
Parent returns the parent App. Note that this is non-nil only for apps which have been included into another app.
func (*App) Prepare ¶
Prepare is automatically called for you. This function is only exposed because the gondola/app/tester package needs to call it to set the App up without making it listen on a port.
func (*App) Reverse ¶
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, value interface{})
Set implements gondola/kvs.Storage.Set
func (*App) SetAddress ¶
SetAddress changes the address this app will listen on.
func (*App) SetAppendSlash ¶
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 ¶
SetAssetsManager sets the static assets manager for the app. See the documention on gondola/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) SetTemplatesFS ¶
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 ¶
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) 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 ¶
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 gondola/cache/layer.
func (*App) TrustsXHeaders ¶
TrustsXHeaders returns if the app uses X headers for determining the remote IP and scheme. See SetTrustXHeaders() for a more detailed explanation.
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) BadRequest ¶
func (c *Context) BadRequest(args ...interface{})
BadRequest is equivalent to calling Context.Error() with http.StatusBadRequest as the error code.
func (*Context) BadRequestf ¶
BadRequestf is equivalent to calling Context.Errorf() with http.StatusBadRequest as the error code.
func (*Context) BasicAuth ¶
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 ¶
Blobstore is a shorthand for ctx.App().Blobstore(), but panics in case of error instead of returning it.
func (*Context) Cache ¶
Cache is a shorthand for ctx.App().Cache(), but panics in case of error, instead of returning it.
func (*Context) Cached ¶
Cached returns true if the request was cached by a cache layer. See gondola/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 ¶
Cookies returns a coookies.Cookies object which can be used to set and delete cookies. See the documentation on gondola/cookies for more information.
func (*Context) Count ¶
Count returns the number of elements captured by the pattern which matched the handler.
func (*Context) DecodeJSON ¶
DecodeJSON creates a json.Decoder reading from the Context and calls Decode with the v argument. See also Context.Read for more information on transparent decompression.
func (*Context) Elapsed ¶
Elapsed returns the duration since this context started processing the request.
func (*Context) Error ¶
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 ¶
Errorf works like Context.Error, but formats the error message using fmt.Sprintf.
func (*Context) Execute ¶
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 ¶
Forbiddenf is equivalent to to Context.Errorf() with http.StatusForbidden as the error code.
func (*Context) FormValue ¶
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 interface{}) interface{}
Get implements gondola/kvs.Storage.Get
func (*Context) Go ¶
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 ¶
HandlerName returns the name of the handler which handled this context
func (*Context) IndexValue ¶
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 ¶
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) Logger ¶
Logger returns a Logger which allows logging mesages in several levels. See gondola/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 gondola/log.Interface methods unconditionally (i.e. don't check if the returned value is nil, it'll never be).
func (*Context) MustDecodeJSON ¶
func (c *Context) MustDecodeJSON(v interface{})
MustDecodeJSON is a shorthand for DecodeJSON which panics instead of returning an error.
func (*Context) MustExecute ¶
MustExecute works like Execute, but panics if there's an error
func (*Context) MustParseFormValue ¶
MustParseFormValue works like ParseFormValue but panics if there's an error.
func (*Context) MustParseIndexValue ¶
MustParseIndexValue works like ParseIndexValue but panics in case of error.
func (*Context) MustRedirectReverse ¶
MustRedirectReverse works like RedirectReverse, but panics if there's an error.
func (*Context) MustReverse ¶
MustReverse is a shorthand for Context.Reverse which panics instead of returning an error.
func (*Context) MustSendMail ¶
MustSendMail works like SendMail, but panics if there's an error.
func (*Context) MustSignIn ¶
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 ¶
NotFoundf is equivalent to Context.Errorf() with http.StatusNotFound as the error code.
func (*Context) Orm ¶
Orm is a shorthand for ctx.App().Orm(), but panics in case of error, rather than returning it.
func (*Context) ParamValue ¶
ParamValue returns the named captured parameter with the given name or an empty string if it does not exist.
func (*Context) ParseFormValue ¶
ParseFormValue tries to parse the named form value into the given arg. If the value is not present, a MissingParameterError is returned. If the value is present but it fails to parse, it returns an InvalidParameterError.
Supported types are: bool, u?int(8|16|32|64)? and float(32|64) Internally, ParseFormValue uses gondola/form/input to parse its arguments, so any type implementing gondola/form/input.Parser can be used too.
Note that arg is not altered the returned error is non-nil.
Some examples (with error handling omitted):
var f float32 ctx.ParseFormValue("quality", &f) var width uint ctx.ParseFormValue("width", &width)
func (*Context) ParseIndexValue ¶
ParseIndexValue uses the captured parameter at the given index and tries to parse it into the given argument. See Context.ParseFormValue for more details.
func (*Context) ParseParamValue ¶
ParseParamValue uses the named captured parameter with the given name and tries to parse it into the given argument. See Context.ParseFormValue for more details.
func (*Context) Provider ¶
func (c *Context) Provider() ContextProvider
Provider returns the Provider which the Context uses to retrieve its arguments.
func (*Context) Read ¶
Read implements the io.Reader interface, reading from the request body. If there's no available request (e.g. the context originated from a scheduled task), Read() will always return 0, io.EOF. If the request headers indicate that the body is compressed (via Content-Encoding header), Read will automatically decompress the data for "gzip" and "deflate". Note that request headers won't be altered and callers can always read the raw request body data using Context.R.Body.
func (*Context) Redirect ¶
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 ¶
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 ¶
RemoteAddress returns the remote IP without the port number.
func (*Context) 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 ¶
RequireFormValue works like FormValue, but panics with a MissingParameter error if the value is not present or empty.
func (*Context) RequireIndexValue ¶
RequireIndexValue works like IndexValue, but panics with a MissingParameter error if the value is not present or empty.
func (*Context) Reverse ¶
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 ¶
SendMail is a shorthand function for sending an email from a template. If the loaded gondola/template.Template.ContentType() returns a string containing "html", the gondola/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 ¶
ServedFromCache returns true if the request was served by a cache layer. See gondola/cache/layer for more information.
func (*Context) Set ¶
func (c *Context) Set(key, value interface{})
Set implements gondola/kvs.Storage.Set
func (*Context) SetStatusCode ¶
func (*Context) SignIn ¶
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 ¶
StatusCode returns the response status code. If no status code has been set yet, it returns the OK code (200).
func (*Context) TranslationTable ¶
func (*Context) URL ¶
URL return the absolute URL for the current request. Note that if your app is running behind a proxy, you might need to properly configure the App as well as the appropriate X-headers in your proxy and your app (X-Forwarded-For, X-Scheme, etc...).
func (*Context) 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) Websocket ¶
Websocket returns the *websocket.Conn assocciated with the current request. If the handler wasn't added with App.HandleWebsocket, this function will panic.
func (*Context) WebsocketURL ¶
WebsocketURL returns an absolute websocket URL from a relative URL (relative to the current request), adjusting also the protocol (e.g. http to ws and https to wss). Note that this function calls Context.URL(), so check its documentation to make sure the current request URL can be correctly determined.
func (*Context) WriteHeader ¶
type ContextFinalizer ¶
type ContextFinalizer func(*Context)
type ContextProcessor ¶
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 total number of arguments Count() int // Arg returns the argument at index idx or the // empty string if there's no such argument. // The last return value is used to disambiguate if // the parameter was provided but empty or not // provided at all. Arg(idx int) (string, bool) // Param returns the parameter named with the given // name or the empty string if there's no such parameter. // The last return value is used to disambiguate if // the parameter was provided but empty or not // provided at all. Param(name string) (string, bool) // ParamNames returns the names of the available parameters, // in the order they were specified. Non-named parameters // must be present in the returned slice as a empty string. ParamNames() []string }
ContextProvider represents the interface used by Context to retrieve the parameters received. Providers types which provide a context with its arguments and parameters must satisfy.
type DataHandler ¶
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 ¶
Error represents an error which, besides a message, has also an assocciated status code to be sent to the client.
type ErrorHandler ¶
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 gondola/app.App), executing commands (via gondola/commands) and tasks (via gondola/task).
func Anonymous ¶
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 ¶
HandlerFromHTTPHandler returns a Handler from an http.Handler.
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 ¶
Private returns a new Handler which adds the headers Vary: Cookie and Cache-Control: private.
func RedirectHandler ¶
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 ¶
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 ¶
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 ¶
TemplateHandler returns a handler which executes the given template with the given data.
type HandlerOption ¶
type HandlerOption func(HandlerOptions) HandlerOptions
A HandlerOption represents a function which receives a HandlerOptions, modifies and returns them. They're used in App.Handle() to set the options for a given handler.
func HostHandler ¶
func HostHandler(host string) HandlerOption
HostHandler sets the HandlerOptions.Host field. See HandlerOptions for more information.
func NamedHandler ¶
func NamedHandler(name string) HandlerOption
NamedHandler sets the HandlerOptions.Name field. See HandlerOptions for more information.
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 ¶
A Header represents the key-value pairs in an HTTP header. Header is also convertible to http.Header.
func (Header) Add ¶
Add adds the key, value pair to the header. It appends to any existing values associated with key.
type InvalidParameterError ¶
type InvalidParameterError struct { // The parameter index if it was requested // via its index (e.g. ParseIndexValue) Index int // The parameter name if it was requested via // form name or parameter name (e.g. ParseFormValue // or ParseParamValue). Name string // The type expected to be able to parse the value // into. Type reflect.Type // The underlying error. Might be nil. Err error }
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 (*InvalidParameterError) Error ¶
func (e *InvalidParameterError) Error() string
func (*InvalidParameterError) StatusCode ¶
func (e *InvalidParameterError) StatusCode() int
type LanguageHandler ¶
LanguageHandler is use to determine the language when serving a request. See App.SetLanguageHandler().
type MissingParameterError ¶
type MissingParameterError struct { // The parameter index if it was requested // via its index (e.g. ParseIndexValue) Index int // The parameter name if it was requested via // form name or parameter name (e.g. ParseFormValue // or ParseParamValue). Name string }
Indicates that a required parameter is mising. Its status code is 400.
func (*MissingParameterError) Error ¶
func (e *MissingParameterError) Error() string
func (*MissingParameterError) StatusCode ¶
func (e *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 gondola/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 ¶
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.
type TemplateProcessor ¶
type Transformer ¶
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).
Source Files ¶
- app.go
- auth.go
- config.go
- context.go
- context_errors.go
- discard.go
- errors.go
- errors_unix.go
- handler.go
- handlers.go
- header.go
- i18n.go
- kvs.go
- log.go
- log_std.go
- mail.go
- monitor.go
- namespace.go
- profile.go
- provider.go
- regexp.go
- replacer.go
- signals.go
- std.go
- template.go
- transformers.go
- user.go
- var.go
- websocket.go
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 pagination implements helper functions for request handlers which present results organized in numbered pages.
|
Package pagination implements helper functions for request handlers which present results organized in numbered pages. |
Package reusableapp contains types and functions for writing reusable Gondola apps.
|
Package reusableapp contains types and functions for writing reusable Gondola apps. |
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. |