🦁
Go とローカル開発
対象
すぐローカル構築して、こんな効率良い Go 開発がしたい人向けです
目標
1 枚の Dockerfile
で 2 つの API をライブリロード起動します
構成
.
├── backend
│ ├── auth
│ │ └── main.go
│ └── payment
│ └── main.go
└── local
├── Dockerfile
└── docker-compose.yaml
Go
コード - 最小限の API を用意します
backend/auth/main.go
backend/auth/main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "this is auth\n")
})
http.ListenAndServe(":8080", nil)
}
backend/payment/main.go
backend/payment/main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "this is payment\n")
})
http.ListenAndServe(":8080", nil)
}
Docker
コード - local/Dockerfile
ライブリロードの Air を Docker 上で導入していきます
local/Dockerfile
FROM golang:1.18.3-alpine3.16 as builder
WORKDIR /go
RUN apk --no-cache add curl && \
curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s && \
mv ./bin/air /bin/air
FROM golang:1.18.3-alpine3.16 as runner
COPY /bin/air /bin/air
local/docker-compose.yaml
上記の Dockerfile
で 2 つのコンテナを定義してください
local/docker-compose.yaml
version: "3.8"
services:
# ---
auth:
container_name: auth
working_dir: /go/auth
image: go-local
ports:
- 8080:8080
build:
context: .
dockerfile: Dockerfile
volumes:
- ../backend/auth:/go/auth
restart: always
command: bash -c "air"
# ---
payment:
container_name: payment
working_dir: /go/payment
image: go-local
ports:
- 8081:8080
build:
context: .
dockerfile: Dockerfile
volumes:
- ../backend/payment:/go/payment
restart: always
command: bash -c "air"
起動
起動と確認をしましょう、起動できましたか?
shell
$ docker-compose -f local/docker-compose.yaml up
$ curl localhost:8080 && curl localhost:8081
this is auth api
this is payment api
Zenn 書きやすくていい感じです!今後も続けていきます。
次回
ローカルでドメインを利用した開発をしたい場合、是非参考にしてください。
Discussion