Go学习笔记 - 简单的查询、编辑、保存 - 仅供学习

参考原文 Writing Web Applications - Go 编程语言  略做修改后得到如下内容。

文件目录:

edit.html内容:

<h1>编辑 {{.Title}}</h1>

<form action="/save/{{.Title}}" method="POST">
    <div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
    <div><input type="submit" value="保存"></div>
</form>

view.html内容:

<h1>{{.Title}}</h1>

<p>[<a href="/edit/{{.Title}}">编辑</a>]</p>

<div>{{printf "%s" .Body}}</div>

main.go内容:

package main
 
import (
	"fmt"
	"log"
	"net/http"
	"io/ioutil"
	"html/template"
	"regexp"
)
 
func main() {
	fmt.Printf("网站开始运行")
 
	http.HandleFunc("/view/", makeHandler(viewHandler))
	http.HandleFunc("/edit/", makeHandler(editHandler))
	http.HandleFunc("/save/", makeHandler(saveHandler))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

  
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}
	renderTemplate(w, p, "view")
}
 
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		p = &Page{Title: title}
  }
	renderTemplate(w, p, "edit")
  }
 
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
	body := r.FormValue("body")
	p := &Page{Title: title, Body: []byte(body)}
	if err := p.Save(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
  }
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
 
var templates = template.Must(template.ParseFiles("view.html", "edit.html"))

func renderTemplate(w http.ResponseWriter, p *Page, tmpl string) {
	err := templates.ExecuteTemplate(w, tmpl+".html", p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}


var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
 
type wikiHandler = func(http.ResponseWriter, *http.Request, string)
 
func makeHandler(handler wikiHandler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		subs := validPath.FindStringSubmatch(r.URL.Path)
		const cnt = 3
		if len(subs) < cnt {
			http.NotFound(w, r)
		}
		handler(w, r, subs[cnt-1])
	}
}

type Page struct {
   Title string // 博客标题
   Body  []byte // 博客内容
}
 
// 保存博客,这个示例是保存到本地文件
func (p *Page) Save() error {
   filename := p.Title + ".txt"
   return ioutil.WriteFile(filename, p.Body, 0600)
}
 
// 加载博客,示例是从文件加载
func loadPage(title string) (*Page, error) {
   filename := title + ".txt"
   body, err := ioutil.ReadFile(filename)
   if err != nil {
      return nil, err
   }
   return &Page{Title: title, Body: body}, nil
}

其他文件说明

main.exe的为go build main.go 后生成的可执行文件。

.txt的为保存的页面输入框输入的内容的数据文件。

页面可自行添加js/css等进行美化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值