1 2 3 4 5 6 7 8 9 | import ( "log" "net/http" ) func main(){ http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/vagrant/go/src/github.com/me/sample/src")))) log.Fatal(http.ListenAndServe(":8080",nil)) } |
L /home/vagrant/go/src/github.com/me/sample/src にhtmlファイルを配置する
index.html
1 2 3 4 5 6 7 8 9 10 11 | <! DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > </ head > < body > Hello world </ body > </ html > |
$ go run server.go
ほう、Echo使わなくても表示できるやん
これを動的に表示したい
### 動的に表示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import ( "fmt" "log" "net/http" "time" ) func clockHandler(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, ` <!DOCTYPE html> <html> <body> It's %d o'clock now. </body> </html> `, time.Now().Hour()) } func main(){ http.HandleFunc("/clock/", clockHandler) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/vagrant/go/src/github.com/me/sample/src")))) log.Fatal(http.ListenAndServe(":8080",nil)) } |
Printfで渡してるだけやな
### データの渡し方
1 2 3 4 5 6 7 8 9 10 11 12 13 | func clockHandler(w http.ResponseWriter, r *http.Request){ t := template.Must(template.ParseFiles("/home/vagrant/go/src/github.com/me/sample/src/clock.html.tpl")) if err := t.ExecuteTemplate(w, "clock.html.tpl", time.Now()); err != nil { log.Fatal(err) } } func main(){ http.HandleFunc("/clock/", clockHandler) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/vagrant/go/src/github.com/me/sample/src")))) log.Fatal(http.ListenAndServe(":8080",nil)) } |
echoでのtemplateと書き方はそんなに変わらんな