Go Template學(xué)習(xí)2

創(chuàng)建一個(gè)web應(yīng)用

使用html/template創(chuàng)建一個(gè)簡(jiǎn)單的web應(yīng)用

工程文件結(jié)構(gòu)如下:


webapp.png

使用到的包

// webapp
package main

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

    "github.com/gorilla/mux"
)

數(shù)據(jù)模型

type Note struct {
    Title       string
    Description string
    CreateOn    time.Time
}

main函數(shù)

func main() {
    r := mux.NewRouter().StrictSlash(false)
    fs := http.FileServer(http.Dir("public"))
    r.Handle("/public/", fs)
    r.HandleFunc("/", getNotes)
    r.HandleFunc("/notes/add", addNote)
    r.HandleFunc("/notes/save", saveNote)
    r.HandleFunc("/notes/edit/{id}", editNote)
    r.HandleFunc("/notes/update/{id}", updateNote)
    r.HandleFunc("/notes/delete/{id}", deleteNote)

    server := &http.Server{
        Addr:    ":9090",
        Handler: r,
    }
    log.Println("Listening...")
    server.ListenAndServe()
}

views 和 模板文件


//base.html
{{define "base"}}
<html>
  <head>{{template "head" .}}</head>
  <body>{{template "body" .}}</body>
</html>
{{end}}

  • 初始頁(yè)面的模板
    定義好的模板文件需要經(jīng)過解析才能執(zhí)行.解析文件只需要執(zhí)行一次.執(zhí)行的文件不需要每次都解析,這里的文件會(huì)被解析并且保存到一個(gè)字典中,以備后面調(diào)用.有三個(gè)HTML文件會(huì)被生成,所以map保存三個(gè)元素.定義好的模板會(huì)在init函數(shù)中使用Must方法解析.
var templates map[string]*template.Template

func init() {
    if templates == nil {
        templates = make(map[string]*template.Template)
    }

    templates["index"] = template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
    templates["add"] = template.Must(template.ParseFiles("templates/add.html", "templates/base.html"))
    templates["edit"] = template.Must(template.ParseFiles("templates/edit.html", "templates/base.html"))
}

//渲染模板的方法
func renderTemplate(w http.ResponseWriter, name string, template string, viewModel interface{}) {
    tmpl, ok := templates[name]
    if !ok {
        http.Error(w, "The template does not exist.", http.StatusInternalServerError)
    }
    err := tmpl.ExecuteTemplate(w, template, viewModel)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }

}

  • 渲染index頁(yè)面
//index.html
{{define "head"}}<title>Index</title>{{end}}

{{define "body"}}
<h1>Notes List</h1>
<p>
  <a href="/notes/add">Add Note</a>
</p>

<div>
    <table>
        <tr>
            <th>Title</th>
            <th>Description</th>
            <th>Create On</th>
            <th>Actions</th>
        </tr>
        {{range $key,$value := .}}

        <tr>
            <td>{{$value.Title}}</td>
            <td>{{$value.Description}}</td>
            <td>{{$value.CreateOn}}</td>
            <td>
                <a href="/notes/edit/{{$key}}" > Edit</a>
                <a href="/notes/delete/{{$key}}" > Delete</a>
            </td>
        </tr>
        {{end}}
    </table>
</div>

{{end}}

在base.html定義好的模板名稱:head和body,當(dāng)index.html文件執(zhí)行,元素是Note結(jié)構(gòu)體的map會(huì)被傳遞.range 操作用來(lái)枚舉map對(duì)象.在range操作下,兩個(gè)定義好的變量key,value會(huì)被引用.一個(gè)range操作必須要用{{end}}來(lái)結(jié)束.

當(dāng)我們?cè)L問路由 "/",會(huì)調(diào)用getNotes的請(qǐng)求handler,index頁(yè)面會(huì)被渲染到瀏覽器,

func getNotes(w http.ResponseWriter, r *http.Request) {
    renderTemplate(w, "index", "base", noteStore)
}

  • 渲染add添加頁(yè)面
//add.html
{{define "head"}}<title>Add Note</title>{{end}}

{{define "body"}}
<h1>Add Note</h1>
<form action="/notes/save" method="post">
  <p>Title:<br>
      <input type="text" name="title" />
  </p>
  <p>Description:<br>
      <textarea rows="4" cols="50" name="description"> </textarea>
  </p>
  <p>
      <input type="submit" value="submit" />
  </p>
</form>

{{end}}

//添加Note時(shí)的handler

func saveNote(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    title := r.PostFormValue("title")
    desc := r.PostFormValue("description")
    note := Note{title, desc, time.Now()}
    id++

    k := strconv.Itoa(id)
    noteStore[k] = note
    http.Redirect(w, r, "/", 302)
}

  • 渲染Edit編輯頁(yè)面
//edit.html

{{define "head"}}
<title>Edite Note</title>
{{end}}

{{define "body"}}
<h1>Edit Note</h1>

<form action="/notes/update/{{.Id}}" method="post">
  <p>Title:<br>
      <input type="text" name="title" value="{{.Note.Title}}"/>
  </p>
  <p>Description:<br>
      <textarea rows="4" cols="50" name="description">{{.Note.Description}}</textarea>
  </p>
  <p>
      <input type="submit" value="submit" />
  </p>
</form>
{{end}}

//edit handler
func editNote(w http.ResponseWriter, r *http.Request) {
    var viewModel EditeNote
    vars := mux.Vars(r)
    k := vars["id"]

    if note, ok := noteStore[k]; ok {
        viewModel = EditeNote{note, k}
    } else {
        http.Error(w, "Could not find the resource to edit,", http.StatusBadRequest)
    }

    renderTemplate(w, "edit", "base", viewModel)
}

//更新Note的handler
func updateNote(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    k := vars["id"]
    var noteToUpd Note
    if note, ok := noteStore[k]; ok {
        r.ParseForm()
        noteToUpd.Title = r.PostFormValue("title")
        noteToUpd.Description = r.PostFormValue("description")
        noteToUpd.CreateOn = note.CreateOn
        delete(noteStore, k)
        noteStore[k] = noteToUpd

    } else {
        http.Error(w, "Could not find the resource to edit,", http.StatusBadRequest)
    }
    http.Redirect(w, r, "/", 302)
}

webapp.go代碼

// webapp
package main

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

    "github.com/gorilla/mux"
)

type Note struct {
    Title       string
    Description string
    CreateOn    time.Time
}

type EditeNote struct {
    Note
    Id string
}

var noteStore = make(map[string]Note)
var id = 0
var templates map[string]*template.Template

func init() {
    if templates == nil {
        templates = make(map[string]*template.Template)
    }

    templates["index"] = template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
    templates["add"] = template.Must(template.ParseFiles("templates/add.html", "templates/base.html"))
    templates["edit"] = template.Must(template.ParseFiles("templates/edit.html", "templates/base.html"))
}

func renderTemplate(w http.ResponseWriter, name string, template string, viewModel interface{}) {
    tmpl, ok := templates[name]
    if !ok {
        http.Error(w, "The template does not exist.", http.StatusInternalServerError)
    }
    err := tmpl.ExecuteTemplate(w, template, viewModel)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }

}

func getNotes(w http.ResponseWriter, r *http.Request) {
    renderTemplate(w, "index", "base", noteStore)
}

func addNote(w http.ResponseWriter, r *http.Request) {
    renderTemplate(w, "add", "base", nil)
}

func saveNote(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    title := r.PostFormValue("title")
    desc := r.PostFormValue("description")
    note := Note{title, desc, time.Now()}
    id++

    k := strconv.Itoa(id)
    noteStore[k] = note
    http.Redirect(w, r, "/", 302)
}

func editNote(w http.ResponseWriter, r *http.Request) {
    var viewModel EditeNote
    vars := mux.Vars(r)
    k := vars["id"]

    if note, ok := noteStore[k]; ok {
        viewModel = EditeNote{note, k}
    } else {
        http.Error(w, "Could not find the resource to edit,", http.StatusBadRequest)
    }

    renderTemplate(w, "edit", "base", viewModel)
}

func updateNote(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    k := vars["id"]
    var noteToUpd Note
    if note, ok := noteStore[k]; ok {
        r.ParseForm()
        noteToUpd.Title = r.PostFormValue("title")
        noteToUpd.Description = r.PostFormValue("description")
        noteToUpd.CreateOn = note.CreateOn
        delete(noteStore, k)
        noteStore[k] = noteToUpd

    } else {
        http.Error(w, "Could not find the resource to edit,", http.StatusBadRequest)
    }
    http.Redirect(w, r, "/", 302)
}

func deleteNote(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)

    k := vars["id"]
    if _, ok := noteStore[k]; ok {
        delete(noteStore, k)
    } else {
        http.Error(w, "Could not find the resource to edit,", http.StatusBadRequest)
    }

    http.Redirect(w, r, "/", 302)
}

func main() {
    r := mux.NewRouter().StrictSlash(false)
    fs := http.FileServer(http.Dir("public"))
    r.Handle("/public/", fs)
    r.HandleFunc("/", getNotes)
    r.HandleFunc("/notes/add", addNote)
    r.HandleFunc("/notes/save", saveNote)
    r.HandleFunc("/notes/edit/{id}", editNote)
    r.HandleFunc("/notes/update/{id}", updateNote)
    r.HandleFunc("/notes/delete/{id}", deleteNote)

    server := &http.Server{
        Addr:    ":9090",
        Handler: r,
    }
    log.Println("Listening...")
    server.ListenAndServe()
}


  • 小結(jié):
    在這個(gè)簡(jiǎn)單的例子,完整的使用Go的標(biāo)準(zhǔn)庫(kù)創(chuàng)建了一個(gè)簡(jiǎn)單的web應(yīng)用,動(dòng)態(tài)數(shù)據(jù)渲染用戶的界面.模板解析數(shù)據(jù)保存到一個(gè)字典中,這樣可以輕松的獲取到解析好的模板,在需要的時(shí)候.可以避免每次執(zhí)行都解析模板,提升程序性能.

一些運(yùn)行的截圖:

![add2.png](http://upload-images.jianshu.io/upload_images/621082-659da0d146bebb96.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
get1.png
get2.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 4. Web集成 4.1. Web提供的全局變量 Web集成模塊向模板提供web標(biāo)準(zhǔn)的變量,做如下說明 reque...
    西漠閱讀 4,756評(píng)論 0 0
  • Beetl2.7.16中文文檔 Beetl作者:李家智 <xiandafu@126.com> 1. 什么是Beet...
    西漠閱讀 2,842評(píng)論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,551評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 34,673評(píng)論 18 399
  • 1 有一年,我和老板在珠海過關(guān)去澳門的時(shí)候,被一個(gè)乞丐扯住了。乞丐身強(qiáng)力壯,一副不給...
    九龍人生閱讀 404評(píng)論 0 8

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