-
Notifications
You must be signed in to change notification settings - Fork 8
Context
GeorgeNava edited this page Jul 16, 2011
·
4 revisions
As you can see, every view in your app receives an app.Context object and we will be explaining it in detail here.
function Blog(ctx app.Context){
/* do stuff with ctx */
}
Here is its structure:
type Context struct {
Method string // GET, POST, PUT, DELETE
Values []string // parsed pretty urls /path/1234/9876
Params map[string]string // parsed query string /path?name=george&sex=male
Form map[string]string // parsed all html fields after a form post
Request *http.Request // request object if needed
Response http.ResponseWriter // response writer if needed
User *UserType // appengine user for easy access
}
And here its functionality:
GetValue(key string) string // gets a value from the query string /path?name=george
DefValue(key string, def string) string // gets a default value if it does not exists in the query string
Print(txt string) // prints to the console
Write(txt string) // writes to the response writer. useful for pages in plain text
Show(name string) // renders a static page without any data associated
Render(name string, data interface{}) // renders a template parsed with some dynamic data
NotFound(txt string) // shows an error page for resources not found in the server
Redirect(url string) // redirects to any route
SetHeader(key string, val string) // sets headers to the http response
SetCookie(key string, val string, exp int64) // sets cookies to store in the browser
To capture a value in the submitted query string:
name := ctx.GetValue("name") // or
name := ctx.DefValue("name","Anonymous")
To show web pages from your templates:
ctx.Show("index") // no data
ctx.Render("blog",data) // with data
To redirect to the main page after a post:
ctx.Redirect("/")
As you can see, everything is easier with app.Context.