分享
  1. 首页
  2. 文章

Web Design With GoLang:Simple http server

我加入简书的路程 · · 983 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

var tpl *template.Template
func init() {
 tpl = template.Must(template.ParseGlob("C:\\Users\\cat\\go\\src\\awesomeProject\\ch05_web\\public\\templates\\*.gohtml"))
}
  • 初始化变量tpl,类型是 *template.Template。
    -Init函数,执行Must函数和ParseGlob,执行载入模式,将模板已语法糖的形式载入。
    -到此为止,tpl已经成为了一个 HTML document fragment.一个文档片段接口。
func main() {
 http.HandleFunc("/", idx)
 http.HandleFunc("/about", abt)
 http.HandleFunc("/contact", cntct)
 http.HandleFunc("/apply", aply)
 http.Handle("/favicon.ico",http.NotFoundHandler())
 http.ListenAndServe(":8080", nil)
}

-服务器main函数代码


func idx(w http.ResponseWriter, r *http.Request) {
 pd := pageData{
 Title:"主页",
 }
 err := tpl.ExecuteTemplate(w, "index.gohtml", pd)
 if err != nil {
 log.Println("LOGGER",err)
 http.Error(w,"Internal Server Error",http.StatusInternalServerError)
 return
 }
 fmt.Println(r.URL.Path)
 fmt.Println("we got here")
}
  • 初始化pageData,将html中的Title字段设定为主页
  • 将之前初始化的tpl使用ExecuteTemplate方法加载模板
// ExecuteTemplate applies the template associated with t that has the given
// name to the specified data object and writes the output to wr.
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
// A template may be executed safely in parallel, although if parallel
// executions share a Writer the output may be interleaved.
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
 tmpl, err := t.lookupAndEscapeTemplate(name)
 if err != nil {
 return err
 }
 return tmpl.text.Execute(wr, data)
}

一下几个处理器函数和Idx处理器是相同的,因此只放出代码不做执行。

 func abt(w http.ResponseWriter, r *http.Request) {
 pd := pageData{
 Title:"关于s",
 }
 err := tpl.ExecuteTemplate(w, "about.gohtml", pd)
 if err != nil {
 log.Println(err)
 http.Error(w,"Internal Server Error",http.StatusInternalServerError)
 return
 }
 fmt.Println(r.URL.Path)
 fmt.Println("we got here")
}
func cntct(w http.ResponseWriter, r *http.Request) {
 pd := pageData{
 Title:"联系我",
 }
 err := tpl.ExecuteTemplate(w, "contact.gohtml", pd)
 if err != nil {
 log.Println(err)
 http.Error(w,"Internal Server Error",http.StatusInternalServerError)
 return
 }
 fmt.Println(r.URL.Path)
 fmt.Println("we got here")
}
func aply(w http.ResponseWriter, r *http.Request) {
 var first string
 pd := pageData{
 Title:"提交",
 }
 if r.Method == "POST" {
 first = r.FormValue("fname")
 pd.FirstName = first
 }
 err := tpl.ExecuteTemplate(w, "apply.gohtml",pd)
 if err != nil {
 log.Println(err)
 http.Error(w,"Internal Server Error",http.StatusInternalServerError)
 return
 }
 fmt.Println(r.URL.Path)
 fmt.Println("we got here")
}

最后一个处理器aply中,有一个新的string变量first。如果处理器收到一个"POST",那么就将form提供的变量fname传递给first。并将pageData的FirstName赋值。最后将得到的pd重新使用模板引擎加载到html文件中去。

模板

about.gohtml

{{template "header" .}}
<h1>关于</h1>
{{template "nav-main"}}
{{template "footer"}}

apply.gohtml

{{template "header" .}}
<h1>提交</h1>
{{template "nav-main"}}
{{if .FirstName}}
 你的名字是 {{.FirstName }}
{{end}}
<form action="/apply" method="post">
 <label for="fnm">姓名</label>
 <input type="text" name="fname" id="fnm">
 <input type="submit">
</form>
{{template "footer"}}

contact.gohtml

{{template "header" .}}
<h1>联系我</h1>
{{template "nav-main"}}
{{template "footer"}}

includes-hdr-ftr.gohtml

{{define "header"}}
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 {{if .FirstName}}
 <title>{{.FirstName}}</title>
 {{else}}
 <title>{{.Title}}</title>
 {{end}}
 </head>
 <body>
 <link rel="stylesheet" href="/public/css/main.css">
{{end}}
{{define "footer"}}
 </body>
 </html>
{{end}}

include-nav-main.gohtml

{{define "nav-main"}}
 <nav>
 <ul>
 <li><a href="/index">主页</a> </li>
 <Li><a href="/about">关于我</a> </Li>
 <li><a href="/contact">联系我</a> </li>
 <li><a href="/apply">提交</a> </li>
 </ul>
 </nav>
{{end}}

index.gohtml


{{template "header".}}
<h1>主页</h1>
{{template "nav-main"}}
<form action="/apply" method="post">
 <input type="text" name="fname">
 <input type="submit" name="fname" id="fnm">
</form>
{{template "footer"}}

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

本文来自:简书

感谢作者:我加入简书的路程

查看原文:Web Design With GoLang:Simple http server

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

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

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏