Contents
前提条件と準備
| 項目 | 推奨環境 |
|---|---|
| OS | Windows 10/11、macOS 13 以上、Ubuntu 22.04 以降(他の Linux ディストリビューションでも同様) |
| 管理者権限 | インストールやパス設定に必要です |
| ネットワーク | Go の公式バイナリと GitHub にアクセスできること(プロキシが必要な場合は後述) |
| エディタ | Visual Studio Code(以下 VS Code)または JetBrains GoLand、Vim/Neovim いずれか |
Tip
Windows ユーザーは PowerShell または Git Bash、macOS・Linux はbash/zshがデフォルトで利用できます。
Go 本体のインストール
1. OS 別インストール手順
| OS | 手順 |
|---|---|
| Windows | 1. https://go.dev/dl/ から go1.22.x.windows-amd64.msi をダウンロード2. MSI ファイルを実行し、ウィザードに従う(デフォルトでシステム環境変数 PATH に自動追加) |
| macOS | 1. Homebrew がインストール済みなら brew install go@1.22 2. Homebrew を使わない場合は公式サイトから .pkg ファイルを取得し、インストーラを実行 |
| Linux (Ubuntu/Debian 系) | bash\nwget https://go.dev/dl/go1.22.linux-amd64.tar.gz -O /tmp/go.tar.gz\nsudo tar -C /usr/local -xzf /tmp/go.tar.gz\necho 'export PATH=$PATH:/usr/local/go/bin' >> ~/.profile\nsource ~/.profile\n |
ポイント
公式バイナリは OS とアーキテクチャに最適化されており、追加の依存関係が不要です。
2. インストール確認
ターミナル(PowerShell/iTerm2 等)で次を実行し、バージョン情報が表示されたら完了です。
|
1 2 |
go version # 例: go version go1.22 linux/amd64 |
エディタ/IDE の推奨設定
VS Code(最もポピュラーな選択肢)
| 設定項目 | 推奨値 / 拡張機能 |
|---|---|
| 拡張機能 | Go(Microsoft)Error Lens(インラインエラーハイライト) |
| フォーマッタ | "go.formatTool": "gofmt" |
| 保存時自動整形 | "editor.formatOnSave": true |
| デバッグ構成 | launch.json に type: "go" を設定(拡張機能が自動生成) |
VS Code 用 settings.json 例
|
1 2 3 4 5 6 7 8 9 10 |
{ "go.useLanguageServer": true, "go.formatTool": "gofmt", "editor.formatOnSave": true, "[go]": { "editor.defaultFormatter": "golang.go" }, "errorLens.enabled": true } |
GoLand(IDE が好きな人向け)
- 初回起動時に「Go SDK を自動検出」させるか、手動で /usr/local/go (macOS/Linux)/
C:\Program Files\Go(Windows)を指定。 File → Settings → Editor → Code Style → Goで gofmt と同一のスタイルに設定すれば、保存時に自動整形されます。
Vim / Neovim
|
1 2 3 4 5 6 7 |
" vim-plug の例 Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' } " 基本的な設定(.vimrc または init.vim) let g:go_fmt_command = "gofmt" autocmd FileType go setlocal noexpandtab shiftwidth=4 softtabstop=4 |
Tip
:GoInstallBinariesで LSP、デバッグアダプタ、テストランナーなど必要なツールを一括インストールできます。
Go モジュール(go.mod)と依存ライブラリ管理
1. プロジェクト作成とモジュール初期化
|
1 2 3 |
mkdir ~/projects/todo-api && cd $_ go mod init github.com/yourname/todo-api # GitHub のリポジトリ URL がベストプラクティス |
go.mod の雛形は自動生成され、次のようになります。
|
1 2 3 4 |
module github.com/yourname/todo-api go 1.22 |
2. ライブラリ追加とバージョン固定
|
1 2 3 4 5 6 7 8 9 |
# HTTP マルチプレクサ go get github.com/gorilla/mux@v1.8.0 # CLI フレームワーク(後述のサンプルで使用) go get github.com/spf13/cobra@v1.7.0 # Web スクレイパー go get github.com/gocolly/colly/v2@v2.1.0 |
実行後、go.mod と go.sum が自動更新されます。
3. 依存関係の整理コマンド
| コマンド | 説明 |
|---|---|
go mod tidy |
未使用パッケージを削除し、必要なものだけを require に残す |
go mod download |
すべての依存モジュールをローカルキャッシュへ事前取得(CI の高速化に有効) |
go list -m all |
現在使用中の全モジュールとバージョンを一覧表示 |
ベストプラクティス
go.modとgo.sumは必ずリポジトリへコミットし、チーム全員が同一のビルド結果になるようにします。
プライベート GitHub リポジトリへの初回 push
1. SSH キー方式(推奨)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# ① 鍵ペア生成(未所持の場合) ssh-keygen -t ed25519 -C "your.email@example.com" # → デフォルトパス ~/.ssh/id_ed25519 に保存。パスフレーズは任意 # ② 公開鍵を GitHub に登録 # Settings → SSH and GPG keys → New SSH key に内容 (cat ~/.ssh/id_ed25519.pub) を貼り付け # ③ リポジトリ作成 & push git init git add . git commit -m "Initial commit" git remote add origin git@github.com:yourname/todo-api.git git branch -M main git push -u origin main |
2. HTTPS + Personal Access Token(PAT)方式
- GitHub の Settings → Developer settings → Personal access tokens で
repoスコープを持つトークンを作成。 - リモート URL を HTTPS に変更し、push 時にユーザー名と PAT を入力。
|
1 2 3 |
git remote set-url origin https://github.com/yourname/todo-api.git git push -u origin main # ユーザー名は GitHub ID、パスワード欄に PAT を貼り付け |
注意
2024 年 5 月以降、GitHub は基本認証(ユーザー名+パスワード)を廃止しました。必ず PAT または SSH 鍵を使用してください。
3. 社内プロキシ環境への対処
|
1 2 3 4 5 6 7 |
# Git 用プロキシ設定(HTTPS のみ例示) git config --global http.proxy http://proxy.example.com:8080 git config --global https.proxy http://proxy.example.com:8080 # Go 用プロキシ設定 export GOPROXY=https://proxy.golang.org,direct # 企業独自ミラーがあれば URL を置き換える |
これらの環境変数は ~/.bashrc(Linux/macOS)や ~/.zshrc、PowerShell の $PROFILE に追記すると永続化できます。
初心者向けサンプルプロジェクト 3 選
以下の3つは 「コード量が少なく、異なる Go の領域を網羅」 できるように設計しています。全体で約 200 行程度なので、すぐに手元で動作確認できます。
1. 小規模 REST API(TODO 管理)
概要
- エンドポイント:
GET /todosとPOST /todos - 使用ライブラリ: 標準パッケージ + gorilla/mux
ディレクトリ構成
|
1 2 3 4 |
todo-api/ ├─ go.mod └─ main.go |
コード (main.go)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package main import ( "encoding/json" "log" "net/http" "github.com/gorilla/mux" ) // Todo は API が扱うデータ構造です。 type Todo struct { ID string `json:"id"` Text string `json:"text"` } // メモリ上の簡易ストア(実運用では DB に置き換える) var store = map[string]Todo{} // GET /todos func getTodos(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(store) } // POST /todos (JSON ボディ: { "id":"1","text":"Buy milk" }) func createTodo(w http.ResponseWriter, r *http.Request) { var t Todo if err := json.NewDecoder(r.Body).Decode(&t); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } store[t.ID] = t w.WriteHeader(http.StatusCreated) } // エントリーポイント func main() { r := mux.NewRouter() r.HandleFunc("/todos", getTodos).Methods(http.MethodGet) r.HandleFunc("/todos", createTodo).Methods(http.MethodPost) log.Println("🚀 server listening on :8080") if err := http.ListenAndServe(":8080", r); err != nil { log.Fatalf("server error: %v", err) } } |
実行手順
|
1 2 3 4 5 6 |
go run main.go # → http://localhost:8080/todos が利用可能に curl -X POST -d '{"id":"1","text":"Buy milk"}' \ -H "Content-Type: application/json" \ http://localhost:8080/todos curl http://localhost:8080/todos | jq . |
2. CLI ツール(TODO 管理)
概要
todo add <text>で項目追加、todo listで一覧表示- フレームワーク: cobra
ディレクトリ構成
|
1 2 3 4 5 6 7 8 |
todo-cli/ ├─ cmd/ │ ├─ root.go │ ├─ add.go │ └─ list.go ├─ go.mod └─ main.go |
主要コード抜粋
cmd/root.go
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package cmd import ( "fmt" "os" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "todo", Short: "シンプルな TODO CLI", } // Execute は main から呼び出され、コマンドツリー全体を実行します。 func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } |
cmd/add.go
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package cmd import ( "fmt" "github.com/spf13/cobra" ) var addCmd = &cobra.Command{ Use: "add [text]", Short: "TODO を追加する", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Printf("✅ Added TODO: %s\n", args[0]) // 本番ではファイルやデータベースに永続化します }, } func init() { rootCmd.AddCommand(addCmd) } |
cmd/list.go
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package cmd import ( "fmt" "github.com/spf13/cobra" ) var listCmd = &cobra.Command{ Use: "list", Short: "TODO を一覧表示する", Run: func(cmd *cobra.Command, args []string) { fmt.Println("🗒️ 現在の TODO はまだ実装されていません") }, } func init() { rootCmd.AddCommand(listCmd) } |
main.go
|
1 2 3 4 5 6 |
package main import "yourname/todo-cli/cmd" func main() { cmd.Execute() } |
ビルド & 実行
|
1 2 3 4 |
go build -o todo . ./todo add "Read Go documentation" ./todo list |
3. Web スクレイパー(Hacker News のタイトル取得)
概要
- ライブラリ: colly
- 対象サイト:
https://news.ycombinator.com/
コード (scraper.go)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package main import ( "fmt" "log" "github.com/gocolly/colly/v2" ) func main() { c := colly.NewCollector( colly.AllowedDomains("news.ycombinator.com"), ) c.OnHTML(".storylink", func(e *colly.HTMLElement) { fmt.Println(e.Text) }) c.OnRequest(func(r *colly.Request) { log.Printf("Visiting %s\n", r.URL.String()) }) if err := c.Visit("https://news.ycombinator.com/"); err != nil { log.Fatalf("visit error: %v", err) } } |
実行
|
1 2 |
go run scraper.go # → 最新ニュースのタイトルが標準出力に列挙されます |
テスト・ビルド・Docker コンテナ化の基本フロー
1. ユニットテストの書き方(REST API の例)
main_test.go
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package main import ( "net/http" "net/http/httptest" "testing" "github.com/gorilla/mux" ) func TestGetTodos_EmptyStore(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, "/todos", nil) rec := httptest.NewRecorder() r := mux.NewRouter() r.HandleFunc("/todos", getTodos).Methods(http.MethodGet) r.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected %d, got %d", http.StatusOK, rec.Code) } expected := "{}\n" if rec.Body.String() != expected { t.Errorf("unexpected body: want %q, got %q", expected, rec.Body.String()) } } |
実行コマンド
|
1 2 |
go test ./... # パッケージ配下すべてのテストを走らせる |
2. マルチステージ Dockerfile(本番イメージは 8 MB 程度)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# ---------- Build stage ---------- FROM golang:1.22-alpine AS builder WORKDIR /src # モジュールキャッシュを先に取得してビルド高速化 COPY go.mod go.sum ./ RUN go mod download # ソースコード全体をコピー COPY . . # 静的リンクでバイナリ生成 RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ go build -ldflags="-s -w" -o /app/todo-api ./main.go # ---------- Runtime stage ---------- FROM alpine:3.18 WORKDIR /root/ COPY --from=builder /app/todo-api . EXPOSE 8080 ENTRYPOINT ["./todo-api"] |
ビルド & 起動手順
|
1 2 3 4 |
docker build -t yourname/todo-api:1.0 . docker run -p 8080:8080 yourname/todo-api:1.0 curl http://localhost:8080/todos # → {"..."} が返るはず |
ポイント
CGO_ENABLED=0にすると C のリンクが排除され、最小サイズのバイナリが得られます。
次のステップ:データベース・gRPC・CI‑CD
| 項目 | 学習教材例 |
|---|---|
| SQL データベース | database/sql + github.com/lib/pq(PostgreSQL)で CRUD 実装。トランザクションや接続プールの扱いを学ぶ |
| NoSQL (MongoDB) | go.mongodb.org/mongo-driver でドキュメント指向ストレージに挑戦 |
| gRPC | protoc-gen-go と google.golang.org/grpc を使って「ユーザー情報取得」サービスを作成。IDL の設計感覚が身につく |
| CI/CD(GitHub Actions) | .github/workflows/go.yml に go test, docker build, docker push を定義し、プッシュ時に自動デプロイを体験 |
GitHub Actions の最小構成例
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
name: Go CI on: push: branches: [ main ] jobs: build-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v4 with: go-version: '1.22' - name: Run tests run: go test ./... - name: Build Docker image env: IMAGE_TAG: ghcr.io/${{ github.repository }}:${{ github.sha }} run: | docker build -t $IMAGE_TAG . echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin docker push $IMAGE_TAG |
まとめ
| 項目 | キーアクション |
|---|---|
| 環境構築 | Go 1.22 の公式バイナリをインストールし、VS Code(または好みの IDE)に Go 拡張と自動整形設定を追加 |
| モジュール管理 | go.mod と go.sum をプロジェクト直下に置き、go get / go mod tidy で依存関係を明示化 |
| GitHub 連携 | SSH キー(または PAT)だけでプライベートリポジトリへ安全に push |
| ハンズオン実装 | REST API・CLI ツール・Web スクレイパーの3例で、HTTP、コマンドライン、HTML パースを体感 |
| テスト & Docker | go test で単体テストを書き、マルチステージ Dockerfile で本番サイズ最小化 |
| 次フェーズ | データベース・gRPC・CI/CD に挑戦し、実務レベルのスキルへ拡張 |
これらの手順をすべてこなせば、「Go 初心者が自信を持って本格開発に移行できる」土台が完成します。ぜひローカル環境で動かしながら、次はデータベースや gRPC へとステップアップしてください。
Happy coding! 🚀