🐕

私的なGo x Cloud Runの開発環境構築メモ

2023/11/20に公開
  • gh repo createする
  • go mod init github.com/xxxx/xxxxする
  • touch go.sumする
  • Dockefileを作る: vim Dockerfile.dev
    ※ マルチステージビルドでやりようあると思うが、ホットリロードするairも入れたいときにうまく動かなかったので取り急ぎ。
    ※koはCloud Runのデプロイツール。
    https://zenn.dev/articles/53ccc1da7ac78d/edit
ARG GO_VERSION=1.21.4
FROM golang:${GO_VERSION}
RUN apt-get update && apt-get install --no-install-recommends -y vim curl
RUN go install github.com/cosmtrek/air@latest
RUN go install github.com/google/ko@latest
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
  • .air.tomlを作る
root = "."
tmp_dir = "tmp"

[build]
cmd = "go build -o ./tmp/main ./main.go"
bin = "tmp/main"
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
include_ext = ["go", "html"]
exclude_dir = ["tmp"]
include_dir = []
exclude_file = []
exclude_regex = ["_test\\.go"]
exclude_unchanged = true
follow_symlink = true
log = "air.log"
delay = 500 # ms
stop_on_error = true
send_interrupt = false
kill_delay = 500 # ms
args_bin = ["hello", "world"]

[log]
time = false

[color]
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
clean_on_exit = true
  • 疎通用でmain.go作る
package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", handler)

	port := 8080
	fmt.Printf("Server listening on :%d...\n", port)
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	if err != nil {
		fmt.Println("Error:", err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, Go Server!")
}
  • Dev Containerを立ち上げる

  • インストールでgoogle-cloud-cli/cURL/vimを入れておく
  • Reopen in Containerでいい感じに開発環境を構築もらう
  • devcontainer.jsonにairを追加
    ※featuresで参照しているリポジトリは問題ないのか要調査
{
	"name": "test pj",
	"build": {
		"context": "..",
		"dockerfile": "../Dockerfile.dev"
	},
	"postCreateCommand": "air"
}

~Fin~

Discussion