go to data rendering html page 02

Rendering to the browser page

// the rendering data to the browser 
Package Penalty for main 

Import ( 
	"fmt" 
	"text / Template" 
	"NET / HTTP" 
) 

// define global template variables 
var mytemplate * template.Template 

of the type the User struct { 
	the Name String 
	Role String 
} 

FUNC the init () { 
	var ERR error 
	MyTemplate, ERR = template.ParseFiles ( "./ test01.html") 
	! = nil {IF ERR 
		fmt.Println ( "the parse File failed, error:", ERR) 
	} 

} 


FUNC dealTest1 (HTTP W .ResponseWriter, R & lt http.Request *) { 

	U1: = {the User 
		"ADMIN", 
		"administrator", 
	} 

	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 page:

  

<!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>

  Open service, the browser and enter localhost: 8080 / test

  

 

Guess you like

Origin www.cnblogs.com/zhangxiaoj/p/11306443.html