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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
試しに debug print してみた
結果は
ということなので once はデフォルト値による初期化、templ は値を入れてないので nil になっている、のような解釈ができそうな結果になった。後者のほうが自然な挙動に見えるが、違いはどこにあるのだろうか