Skip to content

Instantly share code, notes, and snippets.

@hassaku63
Created October 24, 2021 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hassaku63/247a081e61564e8c85749e2365166d6d to your computer and use it in GitHub Desktop.
Save hassaku63/247a081e61564e8c85749e2365166d6d to your computer and use it in GitHub Desktop.
sample http server using template
package main
import (
"log"
"net/http"
"sync"
"text/template"
"path/filepath"
)
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p := filepath.Join("templates", t.filename)
log.Println("filepath: ", p)
t.once.Do(func() {
// template.Must - エラー処理を省けるらしい?
t.templ = template.Must(template.ParseFiles(p))
})
t.templ.Execute(w, nil) // 本来は戻り値をチェックすべき. err をつけるべき? それとも panic?
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head>
<title>chat</title>
</head>
<body>
body
</body>
</html>`))
}
func main() {
t := templateHandler{filename: "index.html"}
// handlers
http.HandleFunc("/", handler)
http.Handle("/render", &t)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndSreve:", err)
}
}
@hassaku63
Copy link
Author

hassaku63 commented Oct 24, 2021

疑問点)

https://gist.github.com/hassaku63/247a081e61564e8c85749e2365166d6d#file-main-go-L39-L42

OnceTemplate も単なる型なので、templateHander の初期化時に filename しか渡さなくても問題なく動く理由がちょっとわからない。once はどこで初期化されたのか。

@hassaku63
Copy link
Author

hassaku63 commented Oct 24, 2021

struct に所属した関数って要はメソッドでしょう?とざっくり理解してチュートリアルを飛ばしてきたが、ここの前提理解が違っているような気がしてきた

暗黙にデフォルト値で初期化しているだけなのかもしれない -> Once, Template

@hassaku63
Copy link
Author

hassaku63 commented Oct 24, 2021

試しに debug print してみた

log.Println("once:", t.once, "\nfilename: ",t.filename, "\ntempl:", t.templ)

結果は

2021/10/24 09:06:22 once: {0 {0 0}} 
filename:  index.html 
templ: <nil>

ということなので once はデフォルト値による初期化、templ は値を入れてないので nil になっている、のような解釈ができそうな結果になった。後者のほうが自然な挙動に見えるが、違いはどこにあるのだろうか

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment