前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言写Web 应用程序

Go语言写Web 应用程序

作者头像
李海彬
发布2018-03-19 16:44:58
8360
发布2018-03-19 16:44:58
举报
文章被收录于专栏:Golang语言社区

绍涵盖内容:

  • 为载入和保存方法创建一个数据结构体
  • 引用http包来创建一个web应用
  • 引用template包来处理HTML模板
  • 引用regexp包来验证用户的输入
  • 引用 闭包操作

可能涉及到的知识:

  • 设计经验
  • 明白基础的web技术(HTTP,HTML)
  • 一些UNIX命令行知识

从这里开始 你要有一个可以运行Go语言的计算机或虚拟机,怎么样安装Go,请参考安装Go教程。首先创建一个目录,在目录下创建一个wiki.go文件,用你喜欢的编辑器打开并输入以下内容:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. )

复制代码

这fmt,ioutil和os都是go语言的标准库,一会我将增加其他方法和更多的包。数据结构让我们声明一个数据结构,这个结构主要包含两个字段,一个是标题,一个是内容。

  1. type Page struct {
  2. Title string
  3. Body []byte
  4. }

复制代码

接下来,我们给Page 这个结构体写个保存方法,代码如下:

  1. func (p *Page) save() os.Error {
  2. filename := p.Title + ".txt"
  3. return ioutil.WriteFile(filename, p.Body, 0600)
  4. }

复制代码

这个方法的签名是:接收一个Page结构体指针,返回一个os.Error错误。在一下的代码中还是用了http包和模板包,具体内容参考具体代码,再这里就不详细贴出来了。下面是模板内容,把他们放到wiki.go同一目录下。编辑页面 模板eidt.html

  1. <h1>Editing {{.Title |html}}</h1>
  2. <form action="/save/{{.Title |html}}" method="POST">
  3. <div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body |html}}</textarea></div>
  4. <div><input type="submit" value="Save"></div>
  5. </form>

复制代码

查看页面模板view.html

  1. <h1>{{.Title |html}}</h1>
  2. <p>[<a href="/edit/{{.Title |html}}">edit</a>]</p>
  3. <div>{{printf "%s" .Body |html}}</div>

完整代码:

package main

import (

"http"

"io/ioutil"

"os"

"regexp"

"template"

)

type Page struct {

Title string

Body []byte

}

func (p *Page) save() os.Error {

filename := p.Title + ".txt"

return ioutil.WriteFile(filename, p.Body, 0600)

}

func loadPage(title string) (*Page, os.Error) {

filename := title + ".txt"

body, err := ioutil.ReadFile(filename)

if err != nil {

return nil, err

}

return &Page{Title: title, Body: body}, 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, "view", p)

}

func editHandler(w http.ResponseWriter, r *http.Request, title string) {

p, err := loadPage(title)

if err != nil {

p = &Page{Title: title}

}

renderTemplate(w, "edit", p)

}

func saveHandler(w http.ResponseWriter, r *http.Request, title string) {

body := r.FormValue("body")

p := &Page{Title: title, Body: []byte(body)}

err := p.save()

if err != nil {

http.Error(w, err.String(), http.StatusInternalServerError)

return

}

http.Redirect(w, r, "/view/"+title, http.StatusFound)

}

var templates = make(map[string]*template.Template)

func init() {

for _, tmpl := range []string{"edit", "view"} {

t := template.Must(template.ParseFile(tmpl + ".html"))

templates[tmpl] = t

}

}

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {

err := templates[tmpl].Execute(w, p)

if err != nil {

http.Error(w, err.String(), http.StatusInternalServerError)

}

}

const lenPath = len("/view/")

var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$")

func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {

return func(w http.ResponseWriter, r *http.Request) {

title := r.URL.Path[lenPath:]

if !titleValidator.MatchString(title) {

http.NotFound(w, r)

return

}

fn(w, r, title)

}

}

func main() {

http.HandleFunc("/view/", makeHandler(viewHandler))

http.HandleFunc("/edit/", makeHandler(editHandler))

http.HandleFunc("/save/", makeHandler(saveHandler))

http.ListenAndServe(":8080", nil)

}

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2016-01-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档