這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
使用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}}