0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go言語のインストールからHello worldまで

0
Last updated at Posted at 2018-01-20

最近、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にアクセスする

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?