Documentation ¶
Index ¶
- Constants
- Variables
- func Bind(params *Params, name string, typ reflect.Type) reflect.Value
- func BindFile(fileHeader *multipart.FileHeader, typ reflect.Type) reflect.Value
- func BindValue(val string, typ reflect.Type) reflect.Value
- func CheckInit()
- func ContainsString(list []string, target string) bool
- func ContentTypeByFilename(filename string) string
- func DirExists(filename string) bool
- func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string
- func FindMethod(recvType reflect.Type, funcVal *reflect.Value) *reflect.Method
- func FirstNonEmpty(strs ...string) string
- func Init(mode, importPath, srcPath string)
- func InterceptFunc(intc InterceptorFunc, when InterceptTime, target interface{})
- func InterceptMethod(intc InterceptorMethod, when InterceptTime)
- func LoadMimeConfig()
- func Message(locale, message string, args ...interface{}) string
- func MessageLanguages() []string
- func MustReadLines(filename string) []string
- func NotFound(req *Request, resp *Response, msg string)
- func OnAppStart(f func())
- func ParseKeyValueCookie(val string, cb func(key, val string))
- func ReadLines(filename string) ([]string, error)
- func RegisterController(c interface{}, methods []*MethodType)
- func RegisterPlugin(p Plugin)
- func RenderError(req *Request, resp *Response, err error)
- func ResolveContentType(req *http.Request) string
- func ResolveFormat(req *http.Request) string
- func ReverseUrl(args ...interface{}) string
- func Run(port int)
- func Sign(message string) string
- type AcceptLanguage
- type AcceptLanguages
- type ActionDefinition
- type Auditor
- type BinaryResult
- type Binder
- type ContentDisposition
- type Controller
- func (c *Controller) FlashParams()
- func (c *Controller) Forbidden(msg string, objs ...interface{}) Result
- func (c *Controller) Invoke(appControllerPtr reflect.Value, method reflect.Value, ...)
- func (c *Controller) Message(message string, args ...interface{}) (value string)
- func (c *Controller) NotFound(msg string, objs ...interface{}) Result
- func (c *Controller) Redirect(val interface{}, args ...interface{}) Result
- func (c *Controller) Render(extraRenderArgs ...interface{}) Result
- func (c *Controller) RenderError(err error) Result
- func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result
- func (c *Controller) RenderJson(o interface{}) Result
- func (c *Controller) RenderTemplate(templatePath string) Result
- func (c *Controller) RenderText(text string, objs ...interface{}) Result
- func (c *Controller) RenderXml(o interface{}) Result
- func (c *Controller) SetCookie(cookie *http.Cookie)
- func (c *Controller) Todo() Result
- type ControllerType
- type DiscerningListener
- type Email
- type EmptyPlugin
- type Error
- type ErrorResult
- type ExecutableTemplate
- type Field
- type Flash
- type FlashPlugin
- type GoTemplate
- type I18nPlugin
- type InterceptTarget
- type InterceptTime
- type Interception
- type InterceptorFunc
- type InterceptorMethod
- type InterceptorPlugin
- type Length
- type Listener
- type Match
- type Max
- type MaxSize
- type MergedConfig
- func (c *MergedConfig) Bool(option string) (result, found bool)
- func (c *MergedConfig) BoolDefault(option string, dfault bool) bool
- func (c *MergedConfig) HasSection(section string) bool
- func (c *MergedConfig) Int(option string) (result int, found bool)
- func (c *MergedConfig) IntDefault(option string, dfault int) int
- func (c *MergedConfig) Options(prefix string) []string
- func (c *MergedConfig) SetOption(name, value string)
- func (c *MergedConfig) SetSection(section string)
- func (c *MergedConfig) String(option string) (result string, found bool)
- func (c *MergedConfig) StringDefault(option, dfault string) string
- type MethodArg
- type MethodType
- type Min
- type MinSize
- type Module
- type Params
- type PlaintextErrorResult
- type Plugin
- type PluginCollection
- func (plugins PluginCollection) AfterRequest(c *Controller)
- func (plugins PluginCollection) BeforeRequest(c *Controller)
- func (plugins PluginCollection) Finally(c *Controller)
- func (plugins PluginCollection) OnAppStart()
- func (plugins PluginCollection) OnException(c *Controller, err interface{})
- func (plugins PluginCollection) OnRoutesLoaded(router *Router)
- type PluginNotifier
- type Range
- type RedirectToActionResult
- type RedirectToUrlResult
- type RenderHtmlResult
- type RenderJsonResult
- type RenderTemplateResult
- type RenderTextResult
- type RenderXmlResult
- type Request
- type Required
- type Response
- type Result
- type Route
- type RouteMatch
- type Router
- type Session
- type SessionPlugin
- type StartupPlugin
- type Template
- type TemplateLoader
- type TestSuite
- func (t *TestSuite) Assert(exp bool)
- func (t *TestSuite) AssertContentType(contentType string)
- func (t *TestSuite) AssertHeader(name, value string)
- func (t *TestSuite) AssertNotFound()
- func (t *TestSuite) AssertOk()
- func (t *TestSuite) AssertStatus(status int)
- func (t *TestSuite) Assertf(exp bool, formatStr string, args ...interface{})
- func (t *TestSuite) BaseUrl() string
- func (t *TestSuite) Get(path string)
- func (t *TestSuite) MakeRequest(req *http.Request)
- func (t *TestSuite) Post(path string, contentType string, reader io.Reader)
- func (t *TestSuite) PostForm(path string, data url.Values)
- type Validation
- func (v *Validation) Check(obj interface{}, checks ...Validator) *ValidationResult
- func (v *Validation) Clear()
- func (v *Validation) Email(str string) *ValidationResult
- func (v *Validation) Error(message string, args ...interface{}) *ValidationResult
- func (v *Validation) ErrorMap() map[string]*ValidationError
- func (v *Validation) HasErrors() bool
- func (v *Validation) Keep()
- func (v *Validation) Length(obj interface{}, n int) *ValidationResult
- func (v *Validation) Match(str string, regex *regexp.Regexp) *ValidationResult
- func (v *Validation) Max(n int, max int) *ValidationResult
- func (v *Validation) MaxSize(obj interface{}, max int) *ValidationResult
- func (v *Validation) Min(n int, min int) *ValidationResult
- func (v *Validation) MinSize(obj interface{}, min int) *ValidationResult
- func (v *Validation) Range(n, min, max int) *ValidationResult
- func (v *Validation) Required(obj interface{}) *ValidationResult
- type ValidationError
- type ValidationPlugin
- type ValidationResult
- type Validator
- type Watcher
Constants ¶
const ( DEFAULT_DATE_FORMAT = "2006-01-02" DEFAULT_DATETIME_FORMAT = "2006-01-02 15:04" )
The SQL standard time formats are build in. Simply add the pattern to recognize to the TimeFormats variable, like this:
func init() { revel.TimeFormats = append(revel.TimeFormats, "01/02/2006") }
const (
CurrentLocaleRenderArg = "currentLocale" // The key for the current locale render arg value
)
const DefaultFileContentType = "application/octet-stream"
const (
REVEL_IMPORT_PATH = "github.com/pyanfield/revel"
)
const (
SESSION_ID_KEY = "_ID"
)
Variables ¶
var ( // These are the lookups to find a Binder for any type of data. // The most specific binder found will be used (Type before Kind) TypeBinders = make(map[reflect.Type]Binder) KindBinders = make(map[reflect.Kind]Binder) // Applications can add custom time formats to this array, and they will be // automatically attempted when binding a time.Time. TimeFormats = []string{} DateFormat string DateTimeFormat string )
var ( // App details AppName string // e.g. "sample" BasePath string // e.g. "/Users/robfig/gocode/src/corp/sample" AppPath string // e.g. "/Users/robfig/gocode/src/corp/sample/app" ViewsPath string // e.g. "/Users/robfig/gocode/src/corp/sample/app/views" ImportPath string // e.g. "corp/sample" SourcePath string // e.g. "/Users/robfig/gocode/src" Config *MergedConfig RunMode string // Application-defined (by default, "dev" or "prod") // Revel installation details RevelPath string // e.g. "/Users/robfig/gocode/src/revel" // Where to look for templates and configuration. // Ordered by priority. (Earlier paths take precedence over later paths.) // 定义了 template 和 configuration 文件的位置 // 按照优先级排序 (早先的 paths 优先于 后来的 paths) CodePaths []string ConfPaths []string TemplatePaths []string Modules []Module // Server config. // // Alert: This is how the app is configured, which may be different from // the current process reality. For example, if the app is configured for // port 9000, HttpPort will always be 9000, even though in dev mode it is // run on a random port and proxied. HttpPort int // e.g. 9000 HttpAddr string // e.g. "", "127.0.0.1" // All cookies dropped by the framework begin with this prefix. CookiePrefix string // Loggers // 定义了默认的 logger 信息的格式, 以""为开头,然后是日期,时间,和文件名及行数 // 格式可以参见使用命令行启动你的app,如: revel run hello_revel DEFAULT = log.New(os.Stderr, "-----------", log.Ldate|log.Ltime|log.Lshortfile) TRACE = DEFAULT INFO = DEFAULT WARN = DEFAULT ERROR = DEFAULT Initialized bool )
var ( MainRouter *Router MainTemplateLoader *TemplateLoader MainWatcher *Watcher Server *http.Server )
var ( // The functions available for use in the templates. TemplateFuncs = map[string]interface{}{ "url": ReverseUrl, "eq": func(a, b interface{}) bool { return a == b }, "set": func(renderArgs map[string]interface{}, key string, value interface{}) template.HTML { renderArgs[key] = value return template.HTML("") }, "append": func(renderArgs map[string]interface{}, key string, value interface{}) template.HTML { if renderArgs[key] == nil { renderArgs[key] = []interface{}{value} } else { renderArgs[key] = append(renderArgs[key].([]interface{}), value) } return template.HTML("") }, "field": NewField, "option": func(f *Field, val, label string) template.HTML { selected := "" if f.Flash() == val { selected = " selected" } return template.HTML(fmt.Sprintf(`<option value="%s"%s>%s</option>`, html.EscapeString(val), selected, html.EscapeString(label))) }, "radio": func(f *Field, val string) template.HTML { checked := "" if f.Flash() == val { checked = " checked" } return template.HTML(fmt.Sprintf(`<input type="radio" name="%s" value="%s"%s>`, html.EscapeString(f.Name), html.EscapeString(val), checked)) }, "pad": func(str string, width int) template.HTML { if len(str) >= width { return template.HTML(html.EscapeString(str)) } return template.HTML(html.EscapeString(str) + strings.Repeat(" ", width-len(str))) }, "errorClass": func(name string, renderArgs map[string]interface{}) template.HTML { errorMap, ok := renderArgs["errors"].(map[string]*ValidationError) if !ok { WARN.Println("Called 'errorClass' without 'errors' in the render args.") return template.HTML("") } valError, ok := errorMap[name] if !ok || valError == nil { return template.HTML("") } return template.HTML(ERROR_CLASS) }, "msg": func(renderArgs map[string]interface{}, message string, args ...interface{}) template.HTML { return template.HTML(Message(renderArgs[CurrentLocaleRenderArg].(string), message, args...)) }, "nl2br": func(text string) template.HTML { return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1)) }, "raw": func(text string) template.HTML { return template.HTML(text) }, "pluralize": func(items interface{}, pluralOverrides ...string) string { singular, plural := "", "s" if len(pluralOverrides) >= 1 { singular = pluralOverrides[0] if len(pluralOverrides) == 2 { plural = pluralOverrides[1] } } switch v := reflect.ValueOf(items); v.Kind() { case reflect.Int: if items.(int) != 1 { return plural } case reflect.Slice: if v.Len() != 1 { return plural } default: ERROR.Println("pluralize: unexpected type: ", v) } return singular }, "date": func(date time.Time) string { return date.Format(DateFormat) }, "datetime": func(date time.Time) string { return date.Format(DateTimeFormat) }, } // Applications may register custom functions to use in templates. // Here is an example: // func init() { // revel.TemplateFuncs["eq"] = func(a, b interface{}) bool { return a == b } // } Funcs = TemplateFuncs )
var DefaultValidationKeys map[string]map[int]string
Register default validation keys for all calls to Controller.Validation.Func(). Map from (package).func => (line => name of first arg to Validation func) E.g. "myapp/controllers.helper" or "myapp/controllers.(*Application).Action" This is set on initialization in the generated main.go file.
var ERROR_CLASS = "hasError"
var TestSuites []interface{} // Array of structs that embed TestSuite
Functions ¶
func Bind ¶
Parse the value string into a real Go value. Returns 0 values when things can not be parsed. http://robfig.github.com/revel/manual/binding.html Note: Only ordered slices should be used when binding a slice of structs for struct : Note: Properties must be exported in order to be bound.
func ContainsString ¶
func ContentTypeByFilename ¶
Returns a MIME content type based on the filename's extension. If no appropriate one is found, returns "application/octet-stream" by default. Additionally, specifies the charset as UTF-8 for text/* types.
func ExecuteTemplate ¶
func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string
Execute a template and returns the result as a string.
func FindMethod ¶
Return the reflect.Method, given a Receiver type and Func value.
func FirstNonEmpty ¶
func Init ¶
func Init(mode, importPath, srcPath string)
Init initializes Revel -- it provides paths for getting around the app.
Params:
mode - the run mode, which determines which app.conf settings are used. importPath - the Go import path of the application. srcPath - the path to the source directory, containing Revel and the app. If not specified (""), then a functioning Go installation is required.
func InterceptFunc ¶
func InterceptFunc(intc InterceptorFunc, when InterceptTime, target interface{})
Install a general interceptor. This can be applied to any Controller. It must have the signature of:
func example(c *revel.Controller) revel.Result
func InterceptMethod ¶
func InterceptMethod(intc InterceptorMethod, when InterceptTime)
Install an interceptor method that applies to its own Controller.
func (c AppController) example() revel.Result func (c *AppController) example() revel.Result
func Message ¶
Perform a message look-up for the given locale and message using the given arguments.
When either an unknown locale or message is detected, a specially formatted string is returned.
func MessageLanguages ¶
func MessageLanguages() []string
Return all currently loaded message languages.
func MustReadLines ¶
Reads the lines of the given file. Panics in the case of error.
func NotFound ¶
This function is useful if there is no relevant Controller available. It writes the 404 response immediately.
func OnAppStart ¶
func OnAppStart(f func())
A simple hook to run code on startup without having to implement a plugin.
func ParseKeyValueCookie ¶
Takes the raw (escaped) cookie value and parses out key values.
func RegisterController ¶
func RegisterController(c interface{}, methods []*MethodType)
Register a Controller and its Methods with Revel.
func RegisterPlugin ¶
func RegisterPlugin(p Plugin)
func RenderError ¶
func ResolveContentType ¶
Get the content type. e.g. From "multipart/form-data; boundary=--" to "multipart/form-data" If none is specified, returns "text/html" by default.
func ResolveFormat ¶
Resolve the accept request header.
func ReverseUrl ¶
func ReverseUrl(args ...interface{}) string
Return a url capable of invoking a given controller method: "Application.ShowApp 123" => "/app/123"
Types ¶
type AcceptLanguage ¶
A single language from the Accept-Language HTTP header.
type AcceptLanguages ¶
type AcceptLanguages []AcceptLanguage
A collection of sortable AcceptLanguage instances.
func ResolveAcceptLanguage ¶
func ResolveAcceptLanguage(req *http.Request) AcceptLanguages
Resolve the Accept-Language header value.
The results are sorted using the quality defined in the header for each language range with the most qualified language range as the first element in the slice.
See the HTTP header fields specification (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4) for more details.
func (AcceptLanguages) Len ¶
func (al AcceptLanguages) Len() int
func (AcceptLanguages) Less ¶
func (al AcceptLanguages) Less(i, j int) bool
func (AcceptLanguages) String ¶
func (al AcceptLanguages) String() string
func (AcceptLanguages) Swap ¶
func (al AcceptLanguages) Swap(i, j int)
type ActionDefinition ¶
func (*ActionDefinition) String ¶
func (a *ActionDefinition) String() string
type Auditor ¶
type Auditor interface {
OnRefresh(listener Listener)
}
Auditor gets notified each time a listener gets refreshed.
type BinaryResult ¶
type BinaryResult struct { ReadSeeker io.ReadSeeker Name string Length int64 Delivery ContentDisposition ModTime time.Time }
func (*BinaryResult) Apply ¶
func (r *BinaryResult) Apply(req *Request, resp *Response)
type Binder ¶
A Binder translates between string parameters and Go data structures.
Here is an example.
Request:
url?id=123&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=rob
Action:
Example.Action(id int, ol []int, ul []string, user User)
Calls:
Binder(params, "id", int): 123 Binder(params, "ol", []int): {1, 2} Binder(params, "ul", []string): {"str", "array"} Binder(params, "user", User): User{Name:"rob"}
Note that only exported struct fields may be bound.
type ContentDisposition ¶
type ContentDisposition string
var ( Attachment ContentDisposition = "attachment" Inline ContentDisposition = "inline" )
type Controller ¶
type Controller struct { Name string // The controller name, e.g. "Application" Type *ControllerType // A description of the controller type. MethodType *MethodType // A description of the invoked action type. AppController interface{} // The controller that was instantiated. Action string // The full action name, e.g. "Application.Index" Request *Request Response *Response Result Result Flash Flash // User cookie, cleared after 1 request. Session Session // Session, stored in cookie, signed. Params *Params // Parameters from URL and form (including multipart). Args map[string]interface{} // Per-request scratch space. RenderArgs map[string]interface{} // Args passed to the template. Validation *Validation // Data validation helpers Txn *sql.Tx // Nil by default, but may be used by the app / plugins }
在自己实现的controller struct 里面,第一个就是要包含的类型必须是这个 revel.Controller
For example:
type AppController struct{ *revel.Controller }
func NewAppController ¶
func NewController ¶
func NewController(req *Request, resp *Response, ct *ControllerType) *Controller
func (*Controller) FlashParams ¶
func (c *Controller) FlashParams()
func (*Controller) Forbidden ¶
func (c *Controller) Forbidden(msg string, objs ...interface{}) Result
func (*Controller) Invoke ¶
func (c *Controller) Invoke(appControllerPtr reflect.Value, method reflect.Value, methodArgs []reflect.Value)
Invoke the given method, save headers/cookies to the response, and apply the result. (e.g. render a template to the response)
func (*Controller) Message ¶
func (c *Controller) Message(message string, args ...interface{}) (value string)
Perform a message lookup for the given message name using the given arguments using the current language defined for this controller.
The current language is set by the i18n plugin.
func (*Controller) NotFound ¶
func (c *Controller) NotFound(msg string, objs ...interface{}) Result
func (*Controller) Redirect ¶
func (c *Controller) Redirect(val interface{}, args ...interface{}) Result
Redirect to an action or to a URL.
c.Redirect(Controller.Action) c.Redirect("/controller/action") c.Redirect("/controller/%d/action", id)
It return a 302 (Temporary Redirect) status code.
func (*Controller) Render ¶
func (c *Controller) Render(extraRenderArgs ...interface{}) Result
Render a template corresponding to the calling Controller method. Arguments will be added to c.RenderArgs prior to rendering the template. They are keyed on their local identifier.
For example:
func (c Users) ShowUser(id int) revel.Result { user := loadUser(id) return c.Render(user) }
This action will render views/Users/ShowUser.html, passing in an extra key-value "user": (User).
if unsuccessful (e.g. It could not find the template), it returns an ErrorResult instead. Note: Revel looks at the calling method name to determine the Template path and to look up the argument names. Therefore, c.Render() may only be called from Actions.
func (*Controller) RenderError ¶
func (c *Controller) RenderError(err error) Result
func (*Controller) RenderFile ¶
func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result
Return a file, either displayed inline or downloaded as an attachment. The name and size are taken from the file info.
func (*Controller) RenderJson ¶
func (c *Controller) RenderJson(o interface{}) Result
Uses encoding/json.Marshal to return JSON to the client. Will serialie it using json.Marshal
func (*Controller) RenderTemplate ¶
func (c *Controller) RenderTemplate(templatePath string) Result
A less magical way to render a template. Renders the given template, using the current RenderArgs.
func (*Controller) RenderText ¶
func (c *Controller) RenderText(text string, objs ...interface{}) Result
Render plaintext in response, printf style.
func (*Controller) RenderXml ¶
func (c *Controller) RenderXml(o interface{}) Result
Uses encoding/xml.Marshal to return XML to the client. Will serialie it using xml.Marshal
func (*Controller) SetCookie ¶
func (c *Controller) SetCookie(cookie *http.Cookie)
func (*Controller) Todo ¶
func (c *Controller) Todo() Result
Render a "todo" indicating that the action isn't done yet. return a stub response (500)
type ControllerType ¶
type ControllerType struct { Type reflect.Type Methods []*MethodType }
func LookupControllerType ¶
func LookupControllerType(name string) *ControllerType
func (*ControllerType) Method ¶
func (ct *ControllerType) Method(name string) *MethodType
Searches for a given exported method (case insensitive)
type DiscerningListener ¶
type DiscerningListener interface { Listener WatchDir(info os.FileInfo) bool WatchFile(basename string) bool }
DiscerningListener allows the receiver to selectively watch files.
type EmptyPlugin ¶
type EmptyPlugin struct{}
To define a Plugin of your own, declare a type that embeds revel.EmptyPlugin, and override just the methods that you want. Then register it with revel.RegisterPlugin.
type DbPlugin struct { revel.EmptyPlugin } func (p DbPlugin) OnAppStart() { ... } func init() { revel.RegisterPlugin(DbPlugin{}) }
Revel will invoke all methods on the single instance provided to RegisterPlugin, so ensure that the methods are threadsafe. It provides default (empty) implementations for all the required methods.
func (EmptyPlugin) AfterRequest ¶
func (p EmptyPlugin) AfterRequest(c *Controller)
func (EmptyPlugin) BeforeRequest ¶
func (p EmptyPlugin) BeforeRequest(c *Controller)
func (EmptyPlugin) Finally ¶
func (p EmptyPlugin) Finally(c *Controller)
func (EmptyPlugin) OnAppStart ¶
func (p EmptyPlugin) OnAppStart()
func (EmptyPlugin) OnException ¶
func (p EmptyPlugin) OnException(c *Controller, err interface{})
func (EmptyPlugin) OnRoutesLoaded ¶
func (p EmptyPlugin) OnRoutesLoaded(router *Router)
type Error ¶
type Error struct { SourceType string // The type of source that failed to build. Title, Path, Description string // Description of the error, as presented to the user. Line, Column int // Where the error was encountered. SourceLines []string // The entire source file, split into lines. Stack string // The raw stack trace string from debug.Stack(). MetaError string // Error that occurred producing the error page. }
An error description, used as an argument to the error template.
func NewErrorFromPanic ¶
func NewErrorFromPanic(err interface{}) *Error
Find the deepest stack from in uesr code and provide a code listing of that, on the line that eventually triggered the panic. Returns nil if no relevant stack frame can be found.
func (*Error) ContextSource ¶
func (e *Error) ContextSource() []sourceLine
Returns a snippet of the source around where the error occurred.
type ErrorResult ¶
This result handles all kinds of error codes (500, 404, ..). It renders the relevant error page (errors/CODE.format, e.g. errors/500.json). If RunMode is "dev", this results in a friendly error page.
func (ErrorResult) Apply ¶
func (r ErrorResult) Apply(req *Request, resp *Response)
type ExecutableTemplate ¶
Add some more methods to the default Template.
type Field ¶
type Field struct { Name string Error *ValidationError // contains filtered or unexported fields }
Field represents a data fieid that may be collected in a web form.
func NewField ¶
A helper for input fields. Given a field name, it returns a struct containing the following members: Id: the field name, converted to be suitable as a HTML element ID. Name: the field name Value: the value of the field in the current RenderArgs Flash: the flashed value of the field. Error: the error message, if any is associated with this field. ErrorClass: the raw string “hasError”, if there was an error, else ””.
{{with $field := field "booking.CheckInDate" .}} <p class="{{$field.ErrorClass}}"> <strong>Check In Date:</strong> <input type="text" size="10" name="{{$field.Name}}" class="datepicker" value="{{$field.Flash}}"> * <span class="error">{{$field.Error}}</span> </p> {{end}}
func (*Field) ErrorClass ¶
Return ERROR_CLASS if this field has a validation error, else empty string.
func (*Field) FlashArray ¶
Returned the flashed value of this field as a list.
type Flash ¶
Flash represents a cookie that gets overwritten on each request. It allows data to be stored across one page at a time. This is commonly used to implement success or error messages. e.g. the Post/Redirect/Get pattern: http://en.wikipedia.org/wiki/Post/Redirect/Get
type FlashPlugin ¶
type FlashPlugin struct{ EmptyPlugin }
func (FlashPlugin) AfterRequest ¶
func (p FlashPlugin) AfterRequest(c *Controller)
func (FlashPlugin) BeforeRequest ¶
func (p FlashPlugin) BeforeRequest(c *Controller)
type GoTemplate ¶
Adapter for Go Templates.
func (GoTemplate) Content ¶
func (gotmpl GoTemplate) Content() []string
type I18nPlugin ¶
type I18nPlugin struct {
EmptyPlugin
}
func (I18nPlugin) BeforeRequest ¶
func (p I18nPlugin) BeforeRequest(c *Controller)
func (I18nPlugin) OnAppStart ¶
func (p I18nPlugin) OnAppStart()
type InterceptTime ¶
type InterceptTime int
const ( BEFORE InterceptTime = iota AFTER PANIC FINALLY )
type Interception ¶
type Interception struct { When InterceptTime // contains filtered or unexported fields }
type InterceptorFunc ¶
type InterceptorFunc func(*Controller) Result
An "interceptor" is functionality invoked by the framework BEFORE or AFTER an action.
An interceptor may optionally return a Result (instead of nil). Depending on when the interceptor was invoked, the response is different: 1. BEFORE: No further interceptors are invoked, and neither is the action. 2. AFTER: Further interceptors are still run. In all cases, any returned Result will take the place of any existing Result.
In the BEFORE case, that returned Result is guaranteed to be final, while in the AFTER case it is possible that a further interceptor could emit its own Result.
Interceptors are called in the order that they are added.
***
Two types of interceptors are provided: Funcs and Methods
Func Interceptors may apply to any / all Controllers.
func example(*revel.Controller) revel.Result
Method Interceptors are provided so that properties can be set on application controllers.
func (c AppController) example() revel.Result func (c *AppController) example() revel.Result
type InterceptorMethod ¶
type InterceptorMethod interface{}
type InterceptorPlugin ¶
type InterceptorPlugin struct {
EmptyPlugin
}
func (InterceptorPlugin) AfterRequest ¶
func (p InterceptorPlugin) AfterRequest(c *Controller)
func (InterceptorPlugin) BeforeRequest ¶
func (p InterceptorPlugin) BeforeRequest(c *Controller)
func (InterceptorPlugin) Finally ¶
func (p InterceptorPlugin) Finally(c *Controller)
func (InterceptorPlugin) OnException ¶
func (p InterceptorPlugin) OnException(c *Controller, err interface{})
type Length ¶
type Length struct {
N int
}
Requires an array or string to be exactly a given length.
func (Length) DefaultMessage ¶
func (Length) IsSatisfied ¶
type Listener ¶
type Listener interface { // Refresh is invoked by the watcher on relevant filesystem events. // If the listener returns an error, it is served to the user on the current request. Refresh() *Error }
Listener is an interface for receivers of filesystem events.
type Match ¶
Requires a string to match a given regex.
func (Match) DefaultMessage ¶
func (Match) IsSatisfied ¶
type MaxSize ¶
type MaxSize struct {
Max int
}
Requires an array or string to be at most a given length.
func (MaxSize) DefaultMessage ¶
func (MaxSize) IsSatisfied ¶
type MergedConfig ¶
type MergedConfig struct {
// contains filtered or unexported fields
}
This handles the parsing of app.conf It has a "preferred" section that is checked first for option queries. If the preferred section does not have the option, the DEFAULT section is checked fallback.
func LoadConfig ¶
func LoadConfig(confName string) (*MergedConfig, error)
func (*MergedConfig) Bool ¶
func (c *MergedConfig) Bool(option string) (result, found bool)
func (*MergedConfig) BoolDefault ¶
func (c *MergedConfig) BoolDefault(option string, dfault bool) bool
func (*MergedConfig) HasSection ¶
func (c *MergedConfig) HasSection(section string) bool
func (*MergedConfig) IntDefault ¶
func (c *MergedConfig) IntDefault(option string, dfault int) int
func (*MergedConfig) Options ¶
func (c *MergedConfig) Options(prefix string) []string
Options returns all configuration option keys. If a prefix is provided, then that is applied as a filter.
func (*MergedConfig) SetOption ¶
func (c *MergedConfig) SetOption(name, value string)
func (*MergedConfig) SetSection ¶
func (c *MergedConfig) SetSection(section string)
func (*MergedConfig) String ¶
func (c *MergedConfig) String(option string) (result string, found bool)
func (*MergedConfig) StringDefault ¶
func (c *MergedConfig) StringDefault(option, dfault string) string
type MethodType ¶
type MinSize ¶
type MinSize struct {
Min int
}
Requires an array or string to be at least a given length.
func (MinSize) DefaultMessage ¶
func (MinSize) IsSatisfied ¶
type Params ¶
type Params struct { url.Values Files map[string][]*multipart.FileHeader // contains filtered or unexported fields }
func ParseParams ¶
type PlaintextErrorResult ¶
type PlaintextErrorResult struct {
Error error
}
func (PlaintextErrorResult) Apply ¶
func (r PlaintextErrorResult) Apply(req *Request, resp *Response)
This method is used when the template loader or error template is not available.
type Plugin ¶
type Plugin interface { // Called on server startup (and on each code reload). OnAppStart() // Called after the router has finished configuration. OnRoutesLoaded(router *Router) // Called before every request. BeforeRequest(c *Controller) // Called after every non-panicking request, before the Result has been applied. AfterRequest(c *Controller) // Called when a panic exits an action, with the recovered error value. OnException(c *Controller, err interface{}) // Called after every request (panic or not), after the Result has been applied. Finally(c *Controller) }
An plugin that allows the user to inject behavior at various points in the request cycle.
type PluginCollection ¶
type PluginCollection []Plugin
func (PluginCollection) AfterRequest ¶
func (plugins PluginCollection) AfterRequest(c *Controller)
func (PluginCollection) BeforeRequest ¶
func (plugins PluginCollection) BeforeRequest(c *Controller)
func (PluginCollection) Finally ¶
func (plugins PluginCollection) Finally(c *Controller)
func (PluginCollection) OnAppStart ¶
func (plugins PluginCollection) OnAppStart()
func (PluginCollection) OnException ¶
func (plugins PluginCollection) OnException(c *Controller, err interface{})
func (PluginCollection) OnRoutesLoaded ¶
func (plugins PluginCollection) OnRoutesLoaded(router *Router)
type PluginNotifier ¶
type PluginNotifier struct {
// contains filtered or unexported fields
}
The PluginNotifier glues the watcher and the plugin collection together. It audits refreshes and invokes the appropriate method to inform the plugins.
func (PluginNotifier) OnRefresh ¶
func (pn PluginNotifier) OnRefresh(l Listener)
type Range ¶
Requires an integer to be within Min, Max inclusive.
func (Range) DefaultMessage ¶
func (Range) IsSatisfied ¶
type RedirectToActionResult ¶
type RedirectToActionResult struct {
// contains filtered or unexported fields
}
func (*RedirectToActionResult) Apply ¶
func (r *RedirectToActionResult) Apply(req *Request, resp *Response)
type RedirectToUrlResult ¶
type RedirectToUrlResult struct {
// contains filtered or unexported fields
}
func (*RedirectToUrlResult) Apply ¶
func (r *RedirectToUrlResult) Apply(req *Request, resp *Response)
type RenderHtmlResult ¶
type RenderHtmlResult struct {
// contains filtered or unexported fields
}
func (RenderHtmlResult) Apply ¶
func (r RenderHtmlResult) Apply(req *Request, resp *Response)
type RenderJsonResult ¶
type RenderJsonResult struct {
// contains filtered or unexported fields
}
func (RenderJsonResult) Apply ¶
func (r RenderJsonResult) Apply(req *Request, resp *Response)
type RenderTemplateResult ¶
Action methods return this result to request a template be rendered.
func (*RenderTemplateResult) Apply ¶
func (r *RenderTemplateResult) Apply(req *Request, resp *Response)
type RenderTextResult ¶
type RenderTextResult struct {
// contains filtered or unexported fields
}
func (RenderTextResult) Apply ¶
func (r RenderTextResult) Apply(req *Request, resp *Response)
type RenderXmlResult ¶
type RenderXmlResult struct {
// contains filtered or unexported fields
}
func (RenderXmlResult) Apply ¶
func (r RenderXmlResult) Apply(req *Request, resp *Response)
type Request ¶
type Request struct { *http.Request ContentType string Format string // "html", "xml", "json", or "text" AcceptLanguages AcceptLanguages Locale string }
func NewRequest ¶
type Required ¶
type Required struct{}
func (Required) DefaultMessage ¶
func (Required) IsSatisfied ¶
type Response ¶
type Response struct { Status int ContentType string Out http.ResponseWriter }
func NewResponse ¶
func NewResponse(w http.ResponseWriter) *Response
func (*Response) WriteHeader ¶
Write the header (for now, just the status code). The status may be set directly by the application (c.Response.Status = 501). if it isn't, then fall back to the provided status code.
type Result ¶
Actions must return a revel.Result, which handles the response generation. Each built-in Result has a default Status Code and Content Type. To override those defaults, simply set those properties on the response:
func (c Application) Action() revel.Result { // Each Result will set a status code by default. // You can override the default status code by setting one yourself: // c.Response.Status = 201 c.Response.Status = http.StatusTeapot c.Response.ContentType = "application/dishware" return c.Render() }
Here is an example of adding your own Result. Create this type:
type Html string func (r Html) Apply(req *Request, resp *Response) { resp.WriteHeader(http.StatusOK, "text/html") resp.Out.Write([]byte(r)) }
Then use it in an action:
func (c *Application) Action() revel.Result { return Html("<html><body>Hello World</body></html>") }
type Route ¶
type Route struct { Method string // e.g. GET Path string // e.g. /app/{id} Action string // e.g. Application.ShowApp FixedParams []string // e.g. "arg1","arg2","arg3" (CSV formatting) // contains filtered or unexported fields }
type RouteMatch ¶
type Router ¶
type Router struct { Routes []*Route // contains filtered or unexported fields }
func (*Router) Refresh ¶
Refresh re-reads the routes file and re-calculates the routing table. Returns an error if a specified action could not be found.
type Session ¶
All data must be serialized to a string fot storage All data may be viewed by the user (it is not encrypted), but it is safe from modification A signed cookie (and thus limited to 4kb in size). Restriction: Keys may not have a colon in them.
type SessionPlugin ¶
type SessionPlugin struct{ EmptyPlugin }
func (SessionPlugin) AfterRequest ¶
func (p SessionPlugin) AfterRequest(c *Controller)
func (SessionPlugin) BeforeRequest ¶
func (p SessionPlugin) BeforeRequest(c *Controller)
type StartupPlugin ¶
type StartupPlugin struct {
EmptyPlugin
}
func (StartupPlugin) OnAppStart ¶
func (p StartupPlugin) OnAppStart()
type Template ¶
type Template interface { Name() string Content() []string Render(wr io.Writer, arg interface{}) error }
Revel executes the template using the RenderArgs data map. Aside from application-provided data, Revel provides the following entries: - “errors” - the map returned by Validation.ErrorMap - “flash” - the data flashed by the previous request.
type TemplateLoader ¶
type TemplateLoader struct {
// contains filtered or unexported fields
}
This object handles loading and parsing of templates. Everything below the application's views directory is treated as a template.
func NewTemplateLoader ¶
func NewTemplateLoader(paths []string) *TemplateLoader
func (*TemplateLoader) Refresh ¶
func (loader *TemplateLoader) Refresh() *Error
This scans the views directory and parses all templates as Go Templates. If a template fails to parse, the error is set on the loader. (It's awkward to refresh a single Go Template)
func (*TemplateLoader) Template ¶
func (loader *TemplateLoader) Template(name string) (Template, error)
Return the Template with the given name. The name is the template's path relative to a template loader root.
An Error is returned if there was any problem with any of the templates. (In this case, if a template is returned, it may still be usable.)
func (*TemplateLoader) WatchFile ¶
func (loader *TemplateLoader) WatchFile(basename string) bool
type TestSuite ¶
A test suite is any struct that embeds revel.TestSuite
type ApplicationTest struct { revel.TestSuite }
Before() and After() are invoked before and after every test method, if present.
func NewTestSuite ¶
func NewTestSuite() TestSuite
NewTestSuite returns an initialized TestSuite ready for use. It is invoked by the test harness to initialize the embedded field in application tests.
func (*TestSuite) AssertContentType ¶
func (*TestSuite) AssertHeader ¶
func (*TestSuite) AssertNotFound ¶
func (t *TestSuite) AssertNotFound()
func (*TestSuite) AssertStatus ¶
func (*TestSuite) BaseUrl ¶
Return the base URL of the server, e.g. "http://127.0.0.1:8557"
func (*TestSuite) Get ¶
Issue a GET request to the given path and store the result in Request and RequestBody.
func (*TestSuite) MakeRequest ¶
Issue any request and read the response. If successful, the caller may examine the Response and ResponseBody properties.
type Validation ¶
type Validation struct { Errors []*ValidationError // contains filtered or unexported fields }
A Validation context manages data validation and error messages.
func (*Validation) Check ¶
func (v *Validation) Check(obj interface{}, checks ...Validator) *ValidationResult
Apply a group of validators to a field, in order, and return the ValidationResult from the first one that fails, or the last one that succeeds.
func (*Validation) Clear ¶
func (v *Validation) Clear()
func (*Validation) Email ¶
func (v *Validation) Email(str string) *ValidationResult
func (*Validation) Error ¶
func (v *Validation) Error(message string, args ...interface{}) *ValidationResult
Add an error to the validation context.
func (*Validation) ErrorMap ¶
func (v *Validation) ErrorMap() map[string]*ValidationError
Return the errors mapped by key. If there are multiple validation errors associated with a single key, the first one "wins". (Typically the first validation will be the more basic).
func (*Validation) HasErrors ¶
func (v *Validation) HasErrors() bool
如果 validation context 非空的话就返回 true 以此来判断是否有 validation error 发生
func (*Validation) Keep ¶
func (v *Validation) Keep()
Tell Revel to serialize the ValidationErrors to the Flash cookie. Controller.FlashParams() --> Controller.Redirect(Action)
func (*Validation) Length ¶
func (v *Validation) Length(obj interface{}, n int) *ValidationResult
func (*Validation) Match ¶
func (v *Validation) Match(str string, regex *regexp.Regexp) *ValidationResult
func (*Validation) Max ¶
func (v *Validation) Max(n int, max int) *ValidationResult
func (*Validation) MaxSize ¶
func (v *Validation) MaxSize(obj interface{}, max int) *ValidationResult
func (*Validation) Min ¶
func (v *Validation) Min(n int, min int) *ValidationResult
func (*Validation) MinSize ¶
func (v *Validation) MinSize(obj interface{}, min int) *ValidationResult
func (*Validation) Range ¶
func (v *Validation) Range(n, min, max int) *ValidationResult
func (*Validation) Required ¶
func (v *Validation) Required(obj interface{}) *ValidationResult
Test that the argument is non-nil and non-empty (if string or list)
type ValidationError ¶
type ValidationError struct {
Message, Key string
}
type ValidationPlugin ¶
type ValidationPlugin struct{ EmptyPlugin }
func (ValidationPlugin) AfterRequest ¶
func (p ValidationPlugin) AfterRequest(c *Controller)
func (ValidationPlugin) BeforeRequest ¶
func (p ValidationPlugin) BeforeRequest(c *Controller)
type ValidationResult ¶
type ValidationResult struct { Error *ValidationError Ok bool }
A ValidationResult is returned from every validation method. It provides an indication of success, and a pointer to the Error (if any). Each evaluation returns a ValidationResult. Failed ValidationResults are stored in the Validation context.
func (*ValidationResult) Key ¶
func (r *ValidationResult) Key(key string) *ValidationResult
func (*ValidationResult) Message ¶
func (r *ValidationResult) Message(message string, args ...interface{}) *ValidationResult
type Watcher ¶
type Watcher struct {
// contains filtered or unexported fields
}
Watcher allows listeners to register to be notified of changes under a given directory.
func NewWatcher ¶
func NewWatcher() *Watcher
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
The command line tool for running Revel apps.
|
The command line tool for running Revel apps. |
modules
|
|
db/app
This plugin provides a database transaction to the application.
|
This plugin provides a database transaction to the application. |
jobs/app/jobs
A job runner for executing scheduled or ad-hoc tasks asynchronously from HTTP requests.
|
A job runner for executing scheduled or ad-hoc tasks asynchronously from HTTP requests. |
samples
|
|
skeleton
|
|