温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Go语言怎样写Web应用程序

发布时间:2021-11-17 16:00:04 来源:亿速云 阅读:154 作者:柒染 栏目:web开发

这期内容当中小编将会给大家带来有关Go语言怎样写Web应用程序,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

从这里开始

你要有一个可以运行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

<h2>Editing {{.Title |html}}</h2>  <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

  1. <h2>{{.Title |html}}</h2> 

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

  3. <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 lenlenPath = 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

效果图:

Go语言怎样写Web应用程序
Go语言怎样写Web应用程序

上述就是小编为大家分享的Go语言怎样写Web应用程序了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI