利用golang的net/http包可以很方便的实现一个web server应用,而配合 html/template 包可以实现类似于python jinja2格式的变量调用。这里就列出两个示例学习html/template模板。

一、利用模板打印当前时间

1、homepage.html模板文件

其内容如下:

<pre data-language="HTML">```markup
# more homepage.html

<html>
<head>
<title>My Page -- www.361way.com</title>
</head>
<body>
<p>The date today is {{.Date}}</p>
<p>And the time is {{.Time}}</p>
</body>
</html>

#### 2、homepage.go运行文件

```go
# more homepage.go
/*
code from www.361way.com <itybku@139.com>
desc:打印当前时间
*/
package main
import (
  "html/template"
  "log"
  "net/http"
  "time"
)
type PageVariables struct {
        Date         string
        Time         string
}
func main() {
        http.HandleFunc("/", HomePage)
        log.Fatal(http.ListenAndServe(":3000", nil))
}
func HomePage(w http.ResponseWriter, r *http.Request){
    now := time.Now() // find the time right now
    HomePageVars := PageVariables{ //store the date and time in a struct
      Date: now.Format("2006-01-02"),
      Time: now.Format("15:04:05"),
    }
    t, err := template.ParseFiles("homepage.html") //parse the html file homepage.html
    if err != nil { // if there is an error
          log.Print("template parsing error: ", err) // log it
        }
    err = t.Execute(w, HomePageVars) //execute the template and pass it the HomePageVars struct to fill in the gaps
    if err != nil { // if there is an error
          log.Print("template executing error: ", err) //log it
        }
}

注意,上面时间格式调用的时候有个坑,上面的format必须是2006-01-02 15:04:05这个日期和时间点,这个是不能修改成其他的,这点和其他语言有区别。这个神秘的时间据说是golang在google内部诞生的日子。如果改成其他时间,输出的时间格式会不准确。

注:这个也很好记口诀:12345—1月2号,下午3点04分05秒

二、选择框

这里第二个示例要做的是做两个选择框,选中什么,页面就交互的反馈给你什么。

1、select.html模板文件

<pre data-language="HTML">```markup
# cat select.html

<html>
<head>
<script type='text/javascript' src='https://ajax.lug.ustc.edu.cn/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<title>{{.PageTitle}}</title>
</head>
<script type='text/javascript'>
 $(document).ready(function() {
   $('input[name=animalselect]').change(function(){
     $('form').submit();
   });
});
</script>
<body>
  {{with $1:=.PageRadioButtons}}
  <p> Which do you prefer</p>
    <form action="/selected" method="post">
         {{range $1}}
           <input type="radio" name={{.Name}} value={{.Value}} {{if .IsDisabled}} disabled=true {{end}} {{if .IsChecked}}checked{{end}}> {{.Text}}
         {{end}}
    </form>
  {{end}}
  {{with $2:=.Answer}}
    <p>Your answer is {{$2}}</p>
  {{end}}
</body>
</html>

#### 2、select.go文件

其内容如下:

```go
# more select.go
/*
code from www.361way.com <itybku@139.com>
desc: webserver 选择框
*/
package main
import (
  "net/http"
  "log"
  "html/template"
)
type RadioButton struct {
        Name       string
        Value      string
        IsDisabled bool
        IsChecked  bool
        Text       string
}
type PageVariables struct {
  PageTitle        string
  PageRadioButtons []RadioButton
  Answer           string
}
func main() {
  http.HandleFunc("/", DisplayRadioButtons)
  http.HandleFunc("/selected", UserSelected)
  log.Fatal(http.ListenAndServe(":3000", nil))
}
func DisplayRadioButtons(w http.ResponseWriter, r *http.Request){
 // Display some radio buttons to the user
   Title := "Which do you prefer?"
   MyRadioButtons := []RadioButton{
     RadioButton{"animalselect", "cats", false, false, "Cats"},
     RadioButton{"animalselect", "dogs", false, false, "Dogs"},
   }
  MyPageVariables := PageVariables{
    PageTitle: Title,
    PageRadioButtons : MyRadioButtons,
    }
   t, err := template.ParseFiles("select.html") //parse the html file homepage.html
   if err != nil { // if there is an error
     log.Print("template parsing error: ", err) // log it
   }
   err = t.Execute(w, MyPageVariables) //execute the template and pass it the HomePageVars struct to fill in the gaps
   if err != nil { // if there is an error
     log.Print("template executing error: ", err) //log it
   }
}
func UserSelected(w http.ResponseWriter, r *http.Request){
  r.ParseForm()
  // r.Form is now either
  // map[animalselect:[cats]] OR
  // map[animalselect:[dogs]]
 // so get the animal which has been selected
  youranimal := r.Form.Get("animalselect")
  Title := "Your preferred animal"
  MyPageVariables := PageVariables{
    PageTitle: Title,
    Answer : youranimal,
    }
 // generate page by passing page variables into template
    t, err := template.ParseFiles("select.html") //parse the html file homepage.html
    if err != nil { // if there is an error
      log.Print("template parsing error: ", err) // log it
    }
    err = t.Execute(w, MyPageVariables) //execute the template and pass it the HomePageVars struct to fill in the gaps
    if err != nil { // if there is an error
      log.Print("template executing error: ", err) //log it
    }
}