在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
渲染到浏览器页面 //把数据渲染到浏览器 package main import ( "fmt" "text/template" "net/http" ) //定义全局的模板变量 var mytemplate *template.Template type User struct { Name string Role string } func init () { var err error mytemplate, err = template.ParseFiles("./test01.html") if err != nil { fmt.Println("parse file failed, error:", err) } } func dealTest1 (w http.ResponseWriter, r *http.Request) { u1 := User{ "admin", "管理员", } err := mytemplate.Execute(w, u1) if err != nil{ fmt.Println("excute failed, error:", err) } } func main () { //设置路由 http.HandleFunc("/test1", dealTest1) err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println("listen server failed, error:", err) return } } hmtl页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>用户名:{{.Name}},角色{{.Role}}</h1> </body> </html> 开启服务,然后在浏览器输入localhost:8080/test
|
请发表评论