/some/index.html HTTP/1.1 • Request headers • Empty line • Message body (optional) • Status line HTTP/1.1 200 OK • Response headers • Empty line • Message body (optional)
! func main() {! router := httprouter.New() ! router.GET("/:name", hello) ! http.ListenAndServe(":8080", router)! }! ! func hello(w http.ResponseWriter, r *http.Request, p httprouter.Params) {! fmt.Fprintf(w, "Hello World, %s!", p.ByName("name"))! }! Not part of standard Go libraries
data driven templates for HTML • Actions (data evaluations or control structure) -‐ delimited by {{ and }} • Arguments -‐ values/variables in the template
data driven templates for HTML • Actions (data evaluations or control structure) -‐ delimited by {{ and }} • Arguments -‐ values/variables in the template • Pass variables to template, accessible through the ‘dot’ {{ . }}
data driven templates for HTML • Actions (data evaluations or control structure) -‐ delimited by {{ and }} • Arguments -‐ values/variables in the template • Pass variables to template, accessible through the ‘dot’ {{ . }} • Can define variables (start with $)
the template 2. Allocate the template (in the route) using New() 3. Create the template by parsing one or more files using Parse(), ParseFiles() or ParseGlob()
the template 2. Allocate the template (in the route) using New() 3. Create the template by parsing one or more files using Parse(), ParseFiles() or ParseGlob() 4. Execute the template, passing the output writer and the argument (or nil if none)
}! ! func main() {! t := template.New("t2")! t = template.Must(t.ParseGlob("*.html")) ! presso := Presentation{! Title: "Write Web Applications with Go",! Author: "Chang Sau Sheong",! }! t.Execute(writer, presso)! }!
! // Test package function that adds a new user! func TestAddUser(t *testing.T) {! addUser("Sau Sheong", "[email protected]", "password")! if val, ok := users["[email protected]"]; !ok {! t.Errorf("Cannot add user")! } else {! if val.Name != "Sau Sheong" {! t.Errorf("User name is wrong")! }! }! }
package names from main to the application name (in this case it is sausheong-pixelate) • Change the main() function to init() • Change from http.ListenAndServe() to http.Handle(mux) 61
a pixelated version • TodayReader A faster, simpler Today (newspaper) reader • GoAuthServ Simple authentication service • Polyglot Multi-‐language web framework