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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值