创建一个web应用
使用html/template创建一个简单的web应用
工程文件结构如下:
webapp.png
使用到的包
// 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
}
main函数
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}}
- 初始页面的模板
定义好的模板文件需要经过解析才能执行.解析文件只需要执行一次.执行的文件不需要每次都解析,这里的文件会被解析并且保存到一个字典中,以备后面调用.有三个HTML文件会被生成,所以map保存三个元素.定义好的模板会在init函数中使用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页面
//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,当index.html文件执行,元素是Note结构体的map会被传递.range 操作用来枚举map对象.在range操作下,两个定义好的变量key,value会被引用.一个range操作必须要用{{end}}来结束.
当我们访问路由 "/",会调用getNotes的请求handler,index页面会被渲染到浏览器,
func getNotes(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "index", "base", noteStore)
}
- 渲染add添加页面
//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时的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编辑页面
//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()
}
- 小结:
在这个简单的例子,完整的使用Go的标准库创建了一个简单的web应用,动态数据渲染用户的界面.模板解析数据保存到一个字典中,这样可以轻松的获取到解析好的模板,在需要的时候.可以避免每次执行都解析模板,提升程序性能.
一些运行的截图:
![add2.png](https://img.haomeiwen.com/i621082/659da0d146bebb96.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) get1.png get2.png
网友评论