golang 构建web应用

lb7758zx · · 1217 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

1、介绍

涵盖内容:
  • 为载入和保存方法创建一个数据结构体
  • 引用http包来创建一个web应用
  • 引用template包来处理HTML模板
  • 引用regexp包来验证用户的输入
  • 引用 闭包操作
可能涉及到的知识:
  • 设计经验
  • 明白基础的web技术(HTTP,HTML)
  • 一些UNIX命令行知识
2、
你要有一个可以运行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)
}
复制代码

运行测试:

$ go run  wiki.go

在地址栏输入地址:http://localhost:8080/view/aNewPage




有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:lb7758zx

查看原文:golang 构建web应用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1217 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传