-
Notifications
You must be signed in to change notification settings - Fork 6
/
template.go
43 lines (35 loc) · 1.01 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Parsing HTML from Template using golang web-server
// Visit: http://127.0.0.1:8080
package main
import (
"html/template"
"net/http"
"path"
)
type Data struct {
Name string
}
// Default Request Handler
func defaultHandler(w http.ResponseWriter, r *http.Request) {
data := Data{"World!"}
fp := path.Join("templates", "index.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Pass template to http.ResponseWriter.
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// To buffer from template to string instead use:
//buf := new(bytes.Buffer)
//if err := tmpl.Execute(buf, data); err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
//}
//templateString := buf.String()
}
func main() {
http.HandleFunc("/", defaultHandler)
http.ListenAndServe(":8080", nil)
}