LoginSignup
2
5

More than 3 years have passed since last update.

3分で準備するGo言語 ローカル環境

Last updated at Posted at 2019-07-23

とにかくさくっとGo言語の環境を準備したかったので、次回必要なときのために備忘録としてまとめました。
go言語を使用してlocalでgo&html等のweb開発環境を構築するための手順です。
なお、環境はmacでHomebrewが入っている状態を前提としています。

goenvのインストール

Homebrewを使ってインストールします。
こまめなupdateも忘れずに。

brew update
brew install goenv

環境変数適用

.bash_profileにgoenvの定義を追加、反映します。

echo 'eval "$(goenv init -)"' >> ~/.bash_profile
source ~/.bash_profile

また、goを使用するために必要なパスの定義も予め行っておきます。

vi ~/.bash_profile
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$PATH
export PORT=8080

goのインストール

まずインストール可能なバージョンの一覧を見ます

goenv install -l

以下のような形で出力されるので、無難そうな最新のメジャーバージョンを選択。

Available versions:

  1.2.2
  1.3.0
  1.3.1
  ~~
  1.11.0
  1.11beta2
  1.11.4
  1.12beta1

インストール実行

goenv install 1.11.0

globalに使用するgolangのバージョンを定義

これでgo言語を利用できる環境が整いました。

goenv global 1.11.0
goenv version

さっそく書いてみよう

フォルダとファイルを以下のように作成

# プロジェクト用のフォルダを作成
mkdir ~/Desktop/GoApp
cd  ~/Desktop/GoApp 

# メイン用のGoファイル
touch main.go

# viewとして使うためのhtmlファイル用のフォルダを作成
mkdir views
cd views
touch index.html
main.go
package main

import (
    "os"
    "log"
    "net/http"
)

func main() {
    http.Handle("/", http.FileServer(http.Dir("views")))
    log.Fatal(http.ListenAndServe(":" + os.Getenv("PORT")), nil))
}

http.Handle ハンドラの登録を行う
http.FileServer 静的ファイルを返してハンドラを生成
http.Dir 静的ファイルを配置したディレクトリの読みこみ
log.Fatal ログを記録
http.ListenAndServer 第一引数でポート、第二引数nilでhttp.Handleに登録したハンドラを仕様 
os.Getenv 環境変数からPORTを取得(上で定義した8080が取得される)

index.html
<html>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

実行する

go run main.go

http://localhost:8080 でローカル環境で動作している状態が確認できる

ビルドする

特に必要はないが、ビルドする場合は以下

go build main.go
2
5
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
2
5