Web Design With GoLang:Simple http server

栏目: Go · 发布时间: 6年前

内容简介:-服务器main函数代码一下几个处理器函数和Idx处理器是相同的,因此只放出代码不做执行。最后一个处理器aply中,有一个新的string变量first。如果处理器收到一个"POST",那么就将form提供的变量fname传递给first。并将pageData的FirstName赋值。最后将得到的pd重新使用模板引擎加载到html文件中去。
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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算机组成(第 6 版)

计算机组成(第 6 版)

Andrew S. Tanenbaum、Todd Austin / 刘卫东、宋佳兴 / 机械工业出版社 / 2014-8-19 / CNY 99.00

本书采用结构化方法来介绍计算机系统,书的内容完全建立在“计算机是由层次结构组成的,每层完成规定的功能”这一概念之上。作者对本版进行了彻底的更新,以反映当今最重要的计算机技术以及计算机组成和体系结构方面的最新进展。书中详细讨论了数字逻辑层、微体系结构层、指令系统层、操作系统层和汇编语言层,并涵盖了并行体系结构的内容,而且每一章结尾都配有丰富的习题。本书适合作为计算机专业本科生计算机组成与结构课程的教......一起来看看 《计算机组成(第 6 版)》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

SHA 加密
SHA 加密

SHA 加密工具