haruprojectの日記(技術モノ)

日々の技術的な取り組みアウトプット用

go言語でシンプルなwebサーバーとテンプレートを使うところまで

続き。

フォルダ構成

chat
  templates
      chat.html
  main.go

main.go

package main

import (
	"net/http"
	"log"
	"sync"
	"html/template"
	"path/filepath"
)

type templateHandler struct {
	once     sync.Once
	filename string
	templ    *template.Template
}

// ServeHTTPはHTTPリクエストを処理
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	t.once.Do(func() {
		t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
		t.templ.Execute(w, nil)
	})

}

func main() {
        // htmlベタ書きするとき
	//http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	//	w.Write([]byte("htmlコード"))
	//})

	http.Handle("/",&templateHandler{filename:"chat.html"})

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe", err)
	}

}


chat.html

<html>
<body>
    チャットしましょう!(テンプレートより)
</body>
</html>

起動して
http://localhost:8080 で確認。

おわり。

haruproject.hateblo.jp
haruproject.hateblo.jp
haruproject.hateblo.jp