Темплейты
package main
import (
"fmt"
"html/template"
"net/http"
)
type Data struct {
Name string
Hobbies []string
}
var tpl = `<h1>Hello from: {{ .Name }}</h1>
<hr>
<h3>Your hobbies are:</h3>
{{$Hobbies := .Hobbies }}
{{range $i, $hobby := $Hobbies}}
<h4>Item [{{ $i }}]: {{ $hobby }}</h4>
{{end}}
<hr>
<p>Пример использования</p>
`
func main() {
http.HandleFunc("/", foo)
fmt.Println("Listening on port: 8082....")
http.ListenAndServe("localhost:8082", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
data := &Data{"Ваши хоби", []string{"snowboarding", "programming","Чтение","Прочие","Красфорд"}}
// step1
tmpl, err := template.New("tpl").Parse(tpl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// step2
if err := tmpl.Execute(w, *data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}