Go语言写Web 应用程序

时间:2022-05-05
本文章向大家介绍Go语言写Web 应用程序,主要内容包括介绍、从这里开始、编辑页面 模板eidt.html、查看页面模板view.html、完整代码:wiki.go、运行测试:、效果图:、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

介绍

涵盖内容:

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

可能涉及到的知识:

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

从这里开始

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

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)
这fmt,ioutil和os都是go语言的标准库,一会我将增加其他方法和更多的包。
数据结构
让我们声明一个数据结构,这个结构主要包含两个字段,一个是标题,一个是内容。
type Page struct {
    Title    string
    Body    []byte
}
接下来,我们给Page 这个结构体写个保存方法,代码如下:
func (p *Page) save() os.Error {
    filename := p.Title + ".txt"
    return ioutil.WriteFile(filename, p.Body, 0600)
}
这个方法的签名是:接收一个Page结构体指针,返回一个os.Error错误。
在一下的代码中还是用了http包和模板包,具体内容参考具体代码,再这里就不详细贴出来了。下面是模板内容,把他们放到wiki.go同一目录下。

编辑页面 模板eidt.html

<h1>Editing {{.Title |html}}</h1>

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

查看页面模板view.html

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

<p>[<a href="/edit/{{.Title |html}}">edit</a>]</p>

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

完整代码:wiki.go

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)
}

运行测试:

$ 8g wiki.go
$ 8l wiki.8
$ ./8.out
在地址栏输入地址:http://localhost:8080/view/aNewPage

效果图: