Go基礎(chǔ) - 6 模板應(yīng)用

模板應(yīng)用
package main

import (
    "html/template"
    "log"
    "net/http"
    "time"
)

type Person struct {
    Name string
    Age  int
}

func main() {

    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        //加載模板
        tpl, _ := template.ParseFiles("demo.html")
        //      tpl, err := template.ParseFiles("demo.html")
        //      if err != nil {
        //          log.Fatal(err)
        //          return
        //      }

        //執(zhí)行模板
        tpl.Execute(w, Person{Name: "test", Age: 18})
        //      err = tpl.Execute(w, Person{Name: "test", Age: 18})
        //      if err != nil {
        //          log.Fatal(err)
        //          return
        //      }

    })

    server := http.Server{
        Addr:        ":9090",         //監(jiān)聽地址和端口
        Handler:     mux,             //Handle
        ReadTimeout: 5 * time.Second, //讀取超時5s
    }

    //啟動監(jiān)聽
    server.ListenAndServe()
    //  err := server.ListenAndServe()
    //  if err != nil {
    //      log.Fatal(err)
    //  }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Name : {{.Name}}
    <br>
    Age  : {{.Age}}
</body>
</html>
Name : test 
Age : 18
相關(guān)閱讀
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容