Created
April 13, 2016 15:43
-
-
Save linxlad/5e4709c6a33a6c140cc40bfe89e90209 to your computer and use it in GitHub Desktop.
Example of rendering a template in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
. "fmt" | |
"net/http" | |
"html/template" | |
"log" | |
) | |
type User struct { | |
FirstName string | |
} | |
func render(w http.ResponseWriter, tmpl string, data map[string]interface{}){ | |
tmpl = Sprintf("tmpl/%s", tmpl) | |
t, err := template.ParseFiles(tmpl) | |
if err != nil{ | |
log.Print("template parsing error: ", err) | |
} | |
// We pass our data map to the template | |
err = t.Execute(w, data) | |
if err != nil{ | |
log.Print("template executing error: ", err) | |
} | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
u := User{ | |
FirstName: "Nathan", | |
} | |
render(w, "welcome.html", map[string]interface{} { | |
"FirstName": u.FirstName, | |
}) | |
} | |
func main() { | |
Println("Running server @ localhost:6800") | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":6800", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment