Skip to content

Instantly share code, notes, and snippets.

@linxlad
Created April 13, 2016 15:43
Show Gist options
  • Save linxlad/5e4709c6a33a6c140cc40bfe89e90209 to your computer and use it in GitHub Desktop.
Save linxlad/5e4709c6a33a6c140cc40bfe89e90209 to your computer and use it in GitHub Desktop.
Example of rendering a template in Go.
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