LoginSignup
28
22

More than 3 years have passed since last update.

Docker + Go + Gin の開発環境を準備する 2020/02

Last updated at Posted at 2020-02-02

Go + Gin で Web API を構築する際の開発環境を準備します。
Gin の クイックスタートが動作するところまでの備忘録です。

以下の記事を書いたのが2018年5月と、時間が経ってしまいました。
https://qiita.com/kkeisuke/items/7cd4d5834386666faab3
この間に Go Modules が出てきたりと変化がありましたので、
改めて書き直しました。

構成

リポジトリ

本記事の成果物です。
https://github.com/kkeisuke/docker-go-gin

kkeisuke/docker-go-gin の部分は適時、読み替えてください。

Dockerfile

Dockerfile
# ベースとなるイメージ
FROM golang:1.13.7-buster

# プロジェクトルートに移動する
WORKDIR /go/src/github.com/kkeisuke/docker-go-gin

# Air インストール
RUN curl -fLo /go/bin/air https://git.io/linux_air \
  && chmod +x /go/bin/air

# コンテナ実行時のデフォルトを設定する
# ライブリロードを実行する
CMD air

docker-compose.yml

docker-compose.yml
version: '3'

services:
  api:
    build:
      context: .
    volumes:
      - .:/go/src/github.com/kkeisuke/docker-go-gin
    ports:
      - 3001:3001
    tty:
      true

.air.conf

ライブリロードだと realize が有名かと思いますが、
近ごろ以下のような issue も見られるようになりました。
https://github.com/oxequa/realize/issues/259

そこで、今回はスター数、開発頻度を考慮して Air を使用しています。

.air.conf の中身は air_example.conf が公開されていますので、
そちらをコピペしています。適時、編集してください。

go.mod

go mod init で作成しました。
Air で build されるタイミングで、gin が追記され、ダウンロードされます。

go.mod
module github.com/kkeisuke/docker-go-gin

go 1.13

require github.com/gin-gonic/gin v1.5.0

main.go

クイックスタートをコピペしてポート指定しています。

main.go
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "ping",
        })
    })
    // ポートを設定しています。
    r.Run(":3001")
}

出力結果

これで、以下のようにブラウザからアクセスできます。

image.png

28
22
2

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
28
22