Skip to content

Instantly share code, notes, and snippets.

@sndnvaps
Last active December 15, 2015 07:19
Show Gist options
  • Save sndnvaps/5222556 to your computer and use it in GitHub Desktop.
Save sndnvaps/5222556 to your computer and use it in GitHub Desktop.

标题:

Go语言写Web应用程序{修改版}

go语言写Web应用程序,涵盖内容:为载入和保存方法创建一个数据结构体,引用http包来创建一个web应用,引用template包来处理HTML模板,引用regexp包来验证用户的输入,引用闭包操作。

介绍

涵盖内容:

◆ 为载入和保存方法创建一个数据结构体

◆ 引用http包来创建一个web应用

◆ 引用template包来处理HTML模板

◆ 引用regexp包来验证用户的输入

◆ 引用 闭包操作

可能涉及到的知识:

◆ 设计经验

◆ 明白基础的web技术(HTTP,HTML)

◆ 一些UNIX命令行知识

从这里开始

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

  
package main

import (

	//	"http"
	"net/http"
	"io/ioutil"
//	"os"
	"regexp"
	//   "template"
	"html/template"
)
 

这ioutil是go语言的标准库

数据结构

让我们声明一个数据结构,这个结构主要包含两个字段,一个是标题,一个是内容。

   
   type Page struct {  
   Title    string 
    Body    []byte 
} 

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


func (p *Page) save() error {  
   filename := p.Title + ".txt"    
 return ioutil.WriteFile(filename, p.Body, 0600) 
} 

这个方法的签名是:接收一个Page结构体指针,返回一个error错误。

在一下的代码中还是用了http包和模板包,具体内容参考具体代码,再这里就不详细贴出来了。下面是模板内容,把他们放到wiki.go同一目录下。

编辑页面 模板eidt.html

```

Editing {{.Title |html}}

<textarea name="body" rows="20" cols="80">{{printf "%s" .Body |html}}</textarea>
```

查看页面模板view.html

```

{{.Title |html}}

[edit]

{{printf "%s" .Body |html}}
```

完整代码:wiki.go


//最后由os.Args[0]进行的修改。
//修改了import 的函数包
// http -> net/http
// template -> html/template
// remove os package 

package main

import (

//	"http"
"net/http"
"io/ioutil"

// "os" "regexp" // "template" "html/template" )

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 }

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.Error(), http.StatusInternalServerError) //修改err.Strings() -> err.Error() 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.ParseFiles(tmpl + ".html")) // 修改template.ParseFile -> template.ParseFiles 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.Error(), http.StatusInternalServerError) //修改err.Strings() -> err.Error() } }

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

原文链接

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment