给定这样的目录结构:
example/ main.go data/hi.html
例子/ main.go
package mainimport ( "html/template" "log" "net/http" "os")var tmpl *template.Templatefunc init() { data, err := Asset("data/hi.html") if err != nil { log.Fatal(err) } tmpl = template.Must(template.New("tmpl").Parse(string(data)))}func main() { // print to stdout tmpl.Execute(os.Stdout, map[string]string{"Name": "James"}) http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { tmpl.Execute(w, map[string]string{"Name": "James"}) }) log.Fatal(http.ListenAndServe(":8000", nil))}
示例/数据/hi.html
<h1>Hi, {{.Name}}</h1>
像这样运行:
go-bindata data && go build && ./example
控制台输出:
<h1>Hi, James</h1>
HTTP输出:
嗨,詹姆斯欢迎分享,转载请注明来源:内存溢出
评论列表(0条)