0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DevContainer@VSCode×Go(Gin)×Air×Delveでデバッグ環境構築

Last updated at Posted at 2025-02-14
go vscode

コンテナ開発環境(DevContainers@VSCode) × ホットリロード(air) × ステップインデバッグ(delve)の環境構築メモ

DevContainersならコンテナ内のローカルホストのデバッガポートに直接アタッチ出来るのでシンプルに構成可能できる。

アーキ概要

image 4.png

コンテナ

golang:1.22.11-alpine3.21

delve デバッガ

インストール

sh
go install github.com/go-delve/delve/cmd/dlv@latest

コマンドパレットのGo Install/Update ToolsからインストールでもOK
※VSCodeServer@コンテナにGoエクステンションが入っていること

Air ホットリロード

バイナリインストールと環境初期化

sh
go install github.com/air-verse/air@latest \
&& cd path/to/app_root
&& air init #=> ./.air.tomlが生成される

.air.tomlコンフィグをデバッグ向けに編集

.air.toml
[build]
  # ビルド設定
  cmd = "go build -gcflags=\"all=-N -l\" -o ./tmp/main ."
  # 起動設定
  # --logオプションで標準出力に詳細ログを出力
  full_bin = "dlv --headless=true --listen=:2345 --api-version=2 --accept-multiclient exec --continue ./tmp/main"

# その他はデフォルト

ノーマルビルドと比較してデバッグビルドは時間はかかるようになった

-gcflags="all=-N -l"

デバッガ(delve など)を使う場合、Go の最適化が入っていると変数の値が見えなくなったり、
関数がインライン化されてブレークポイントが期待通り動かなくなることがあるので、Go コンパイラの最適化を無効化するためのオプションを指定する

オプションについて

  • -N: 最適化を無効化してデバッグしやすくする
  • -l: インライン展開を無効化して関数のインライン化を防ぐ

full_bin = "dlv --headless=true --listen=:40000 --api-version=2 --accept-multiclient exec --continue ./tmp/main"

dlv execでビルドバイナリ./tmp/mainをデバッグ実行する

オプションについて

  • —headless=true により、CLI(ターミナル)ではなく、エディタや別のデバッガから接続できる
  • --listen=:2345により、ポート2345にデバッガを待機
  • --accept-multiclient により、複数のクライアント(VSCode, GoLand など)から同時に接続できる
  • --continue により、Delve 起動時に自動的にプログラムを実行(手動で continue を打たなくて済む)

VSCode

デバッグ構成はアタッチ式で

launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Attach Server",
            "type": "go",
            "request": "attach",
            "mode": "remote",
            "port": 2345,
            "host": "localhost",
            "showLog": true
        }
    ]
}

デバッグ

  1. アプリケーションディレクトリでairを実行する
sh
cd path/to/app_root && air
  1. VSCodeの実行とデバッグ > Attach Serverでアタッチ開始
  2. ブレークポイントを設定してhttpリクエストを入れたらブレークする
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?