GO语言学习:动态Web

时间:2022-05-04
本文章向大家介绍GO语言学习:动态Web,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用Golang中的模板template来实现在HTML中动态Web.

1.网络端口监听操作:

Web动态页面要使用http.HandleFunc()而不是http.Handle()

主函数实现代码如下:

func main() {
	http.HandleFunc("/info", infoHandler)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}

2. 模板template的使用:

首先要做HTML中插入字段供Golang使用。Golang的模板通过{{.}}来包含渲染时被替换的字段,{{.}}表示当前的对象,这个和java或者C++中的this类似,如果要访问当前对象的字段通过{{.data}},但是需要注意一点:这个字段必须是导出的(字段字母必须是大写的),否则在渲染的时候会报错。

golang实例代码:

<span style="font-size:12px;">type Infromation struct{
	Name string
}</span>

HTML代码:

switch.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Switch</title>
</head>
<body>
<h1>name is: {{.Name}}</h1>
<form method="post" action="/info">
	<p>Switch Key:<input type="submit" name="switch" value="switch" /></p>
</form>
</body>
</html>

3. 对页面进行响应、

首先生成模板

func ParseFiles(filenames ...string) (*Template, error)

然后填入字段并实现模板

func (t *Template) Execute(wr io.Writer, data interface{}) error

在函数中第二个参数data填入要实现的字段。

相关代码如下

func infoHandler(w http.ResponseWriter, r *http.Request) {
	info := new(Infromation)
	if r.Method == "GET" {
		info.Name = "A"
		t, err := template.ParseFiles("switch.html")
		if err != nil {
			http.Error(w, err.Error(),http.StatusInternalServerError)
			return
		}
			t.Execute(w, info)
			return
	} 
	if r.Method == "POST" {
	  fmt.Println("click")
		info.Name = "B"
		t, err := template.ParseFiles("switch.html")
		if err != nil {
			http.Error(w, err.Error(),http.StatusInternalServerError)
			return
		}
			t.Execute(w, info)
		return
	}
}