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 InvalidParameterType(name string, typ reflect.Type)
- func KindNotFound(kind string)
- func MissingParameter(name string)
- func NotFound()
- func SignOutHandler(ctx *Context)
- type App
- func (app *App) AddContextFinalizer(cf ContextFinalizer)
- func (app *App) AddContextProcessor(cp ContextProcessor)
- func (app *App) AddHook(hook *template.Hook)
- func (app *App) AddRecoverHandler(rh RecoverHandler)
- 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, error)
- func (app *App) Clone() *App
- 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 string) interface{}
- func (app *App) Handle(pattern string, handler Handler)
- func (app *App) HandleAssets(prefix string, dir string)
- func (app *App) HandleNamed(pattern string, handler Handler, name string)
- func (app *App) HandleOptions(pattern string, handler Handler, opts *HandlerOptions)
- func (app *App) Include(prefix 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) MustListenAndServe()
- 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, 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 string, 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) SetName(name string)
- 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 Cache
- 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
- func (c *Context) Cached() bool
- func (c *Context) Close()
- func (c *Context) Cookies() *cookies.Cookies
- func (c *Context) Count() int
- 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 string) 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) 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
- func (c *Context) ParamValue(name string) string
- func (c *Context) ParseFormValue(name string, arg interface{}) bool
- func (c *Context) ParseIndexValue(idx int, arg interface{}) bool
- func (c *Context) ParseParamValue(name string, arg interface{}) bool
- 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 string, value interface{})
- func (c *Context) SetHeader(key string, value string)
- 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) 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 HandlerInfo
- type HandlerOptions
- type Header
- type InvalidParameterTypeError
- type LanguageHandler
- type MissingParameterError
- type NotFoundError
- type Orm
- type RecoverHandler
- type Template
- type TemplateProcessor
- type Transformer
- type User
- type UserFunc
Constants ¶
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" )
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 gnd.la/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("gnd.la/app/cookies.salt") )
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 InvalidParameterType ¶
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 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) 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 ¶
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 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 ¶
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 ¶
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 ¶
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) 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) HandleNamed ¶
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) 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) MustListenAndServe ¶
func (app *App) MustListenAndServe()
MustListenAndServe works like ListenAndServe, but panics if there's an error
func (*App) MustReverse ¶
MustReverse calls Reverse and panics if it finds an error. See Reverse for further details.
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 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 ¶
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 gnd.la/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 ¶
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 ¶
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 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) 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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
Count returns the number of elements captured by the pattern which matched the handler.
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) 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 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 ¶
MustExecute works like Execute, but panics if there's an error
func (*Context) MustParseFormValue ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 raises a MissingParameter error if the value is not present or empty.
func (*Context) RequireIndexValue ¶
RequireIndexValue works like IndexValue, but raises 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 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 ¶
ServedFromCache returns true if the request was served by a cache layer. See gnd.la/cache/layer for more information.
func (*Context) Set ¶
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) 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 the headers haven't been written yet, it returns 0
func (*Context) TranslationTable ¶
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) 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 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 }
ContextProvider represents the interface which 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 gnd.la/app.App), executing commands (via gnd.la/commands) and tasks (via gnd.la/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 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 ¶
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 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 ¶
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 Orm ¶
Orm is just a very thin wrapper around orm.Orm, which disables the Close method when running in production mode, since the App is always reusing the same ORM instance.
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 ¶
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
- app_assets.go
- auth.go
- cache.go
- config.go
- context.go
- context_errors.go
- discard.go
- errors.go
- errors_unix.go
- handler.go
- handlers.go
- header.go
- i18n.go
- log.go
- log_std.go
- mail.go
- monitor.go
- namespace.go
- orm.go
- profile.go
- provider.go
- regexp.go
- replacer.go
- std.go
- template.go
- transformers.go
- user.go
- var.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 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. |