GoでHTTPサーバしてHTMLに変数バインド

ロースペックでも開発は可能

hello.html

  • vi hello.htmlで以下作成
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>{{.Title}}</title>
  </head>
  <body>
    {{.Title}} {{.Count}} count
  </body>
</html>

hello.go

  • vi hello.goで以下作成
package main

import (
  "net/http"
  "text/template"
)

type Page struct {
  Title string
  Count int
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
  page := Page{"Hello World.", 1}
  tmpl, err := template.ParseFiles("hello.html") // ParseFilesを使う
  if err != nil {
    panic(err)
  }

  err = tmpl.Execute(w, page)
  if err != nil {
    panic(err)
  }
}

func main() {
  http.HandleFunc("/", viewHandler) // hello
  http.ListenAndServe(":8080", nil)
}

確認

go run hello.go
open http://localhost:8080