Created
October 24, 2021 08:32
-
-
Save hassaku63/247a081e61564e8c85749e2365166d6d to your computer and use it in GitHub Desktop.
sample http server using template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
struct に所属した関数って要はメソッドでしょう?とざっくり理解してチュートリアルを飛ばしてきたが、ここの前提理解が違っているような気がしてきた
暗黙にデフォルト値で初期化しているだけなのかもしれない -> Once, Template
試しに 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
疑問点)
https://gist.github.com/hassaku63/247a081e61564e8c85749e2365166d6d#file-main-go-L39-L42
Once
もTemplate
も単なる型なので、templateHander の初期化時にfilename
しか渡さなくても問題なく動く理由がちょっとわからない。once はどこで初期化されたのか。