May 15, 2021 Revel
The controller method must return a
revel.Result
which handles response results, has an interface defined as follows:
type Result interface {
Apply(req *Request, resp *Response)
}
revel.Controller
the following methods to process response results:
In addition, developers can customize the level. Result.
Each built-in Result has a default status code and content type that can be modified by simply setting related properties:
func (c App) Action() revel.Result {
c.Response.Status = http.StatusTeapot
c.Response.ContentType = "application/dishware"
return c.Render()
}
Controller rendering method (e.g. "Controller.Action"),
mvc.Controller.Render
does two things:
If it is not successful (for example, no template was found), ErrorResult will be returned.
This allows developers to write:
func (c MyApp) Action() revel.Result {
myValue := calculateValue()
return c.Render(myValue)
}
Refer to the variable "myValue" in the template. This is usually more convenient than building a clear map, because in many cases the data will be treated as a local variable.
Note: R evel determines which template to use by calling the controller method name, looking for the parameter name. Therefore, c.Render() can only be called by operation.
An application can
RenderJson
or
RenderXml
and transfer any type of variable (usually a struct). R
evel uses
json.Marshal
or
xml.Marshal
serializes variables.
If
app.conf
profile
results.pretty=true
it will be serialized using
MarshalIndent
to produce nice indentations for ease of use.
A secondary function is used to generate redirects. It can be used in two ways:
return c.Redirect(Hotels.Settings)
This form is useful because it provides a degree of route type security and independence (automatically generating URLs).
return c.Redirect("/hotels/%d/settings", hotelId)
It is usually used to transmit parameters.
It returns a 302 (temporary redirect) status code.
Here is an example of adding simple results.
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))
}
Use it in a controller method:
func (c *App) Action() revel.Result {
return Html("<html><body>Hello World</body></html>")
}
Each Result sets a default status code, and you can reset the default status code:
func (c *App) CreateEntity() revel.Result {
c.Response.Status = 201
return c.Render()
}