GO語言學習:動態Web

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.