最近、Go言語の勉強もしているので、少しづつメモのような形で投稿していこうと思います。
次回は簡単なチャットの作り方でも投稿する予定です。
Macへのインストール方法
Homebrewでインストールします。Homebrewを入れていない方は別途インストールしてください。
Go言語のインストール
brew install go
インストールできたか確認する
go version
ワークスペースの設定
ワークスペース(これからGoはここで動かします)と言うディレクトリを作成し、作成したディレクトリを$GOPATHに設定する。
export GOPATH=$HOME/go
コードを書く
main.go
package main
import (
"log"
"net/http"
"path/filepath"
"sync"
"text/template"
)
// templは1つのテンプレートを表します
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
// ServerHTTPは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() {
//ルート
http.Handle("/", &templateHandler{filename: "helloworld.html"})
//Webサーバを開始します
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
ServeHTTP
ServeHTTPメソッドを用意することで
http.Handleに登録出来るようにする
templates/helloworld.html
<html>
<head>
<title>Helloworld</title>
</head>
<body>
Hello world
</body>
</html>
実行する
go run main.go
http://localhost:8080にアクセスする