こんにちは。KOUKIです。とある企業でWeb開発業務に従事しています。
Youtubeで、Go言語とPostgresを使ったプログラミング例が紹介されていたので、記事にしました。
今回は開発環境の構築のみです。
セットアップ
開発環境は、Docker上で行います。
1 2 3 4 5 6 7 8 9 10 11 |
mkdir golang-with-postgres cd golang-with-postgres touch main.go touch docker-compose.yml mkdir docker mkdir docker/golang mkdir docker/postgres touch docker/golang/Dockerfile touch docker/postgres/Dockerfile go mod init golang-with-postgres go get github.com/lib/pq |
DBのスキーマー設定
dbdiagramを使うとDBのスキーマーを可視化できます。Simple bankという名前で、以下の設定を行なっています。

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 |
// Creating tables Table accounts as A { id bigserial [pk] owner varchar [not null] balance bigint [not null] currency varchar [not null] created_at timestamptz [not null, default: `now()`] indexes { owner } } Table entries { id bigserial [pk] account_id bigint [ref: > A.id, not null] amount bigint [not null, note: 'can be negative or positive'] created_at timestamptz [not null, default: `now()`] indexes { account_id } } Table transfers { id bigserial [pk] from_account_id bigint [ref: > A.id, not null] to_account_id bigint [ref: > A.id, not null] amount bigint [not null, note: 'must be positive'] created_at timestamptz [not null, default: `now()`] indexes { from_account_id to_account_id (from_account_id, to_account_id) } } |

このスキーマーはダウンロードすることができます。Export -> Import XXXX

ダウンロードしたファイルは、「Simple bank.sql」という名前でdocker/postgres配下に格納してください。
Docker環境構築
golang
golangのDockerfileの設定を行います。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
FROM golang:1.15-alpine3.12 RUN apk update && \ apk upgrade && \ apk add git RUN go get github.com/cespare/reflex ENV CGO_ENABLED=0 WORKDIR /go/src/app COPY go.mod go.sum main.go ./ RUN go mod download |
postgres
postgresのDockerfileの設定を行います。
1 2 3 4 |
FROM postgres:12-alpine COPY ./docker/postgres/*.sql /docker-entrypoint-initdb.d/ |
「docker-entrypoint-initdb.d」フォルダ配下にsqlファイルを設置しておくとコンテナ作成時に、sqlを実行してくれます。かなり便利です。
docker-compose.yml
docker-compose.ymlの設定を行います。
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 |
version: '3' services: api: build: context: . dockerfile: ./docker/golang/Dockerfile ports: - "8080:8080" depends_on: - postgres container_name: api volumes: - .:/go/src/app/ command: > sh -c "reflex -s -r '\.go$$' go run main.go" postgres: build: context: . dockerfile: ./docker/postgres/Dockerfile environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=secret - POSTGRES_DB=simplebank ports: - "5432:5432" container_name: postgres postgres-gui: image: donnex/pgweb command: -s --bind=0.0.0.0 --listen=8080 --url postgresql://postgres:secret@postgres/simplebank?sslmode=disable links: - postgres:postgres ports: - "9232:8080" depends_on: - postgres |
postgresのenvironmentに設定されている環境変数の説明は、ここを見るといいと思います。
これもコンテナ作成時に作成するデータの情報になります。
接続用の簡易サーバー
Postgresへの接続確認用のコードを用意します。
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
// main.go package main import ( "database/sql" "fmt" "log" "net/http" "time" _ "github.com/lib/pq" ) var db *sql.DB const ( // postgres接続情報 conn = "host=postgres port=5432 user=postgres password=secret dbname=simplebank sslmode=disable" ) func logFatal(err error) { if err != nil { log.Fatal(err) } } // めっちゃ重い処理 func slowQuery() error { _, err := db.Exec("SELECT pg_sleep(5)") return err } func slowHandler(w http.ResponseWriter, req *http.Request) { start := time.Now() err := slowQuery() if err != nil { log.Printf("Error: %s\n", err.Error()) return } fmt.Fprintln(w, "OK") fmt.Printf("slowHandler took: %v\n", time.Since(start)) } func main() { var err error // postgresに接続 db, err = sql.Open("postgres", conn) logFatal(err) // 応答確認 err = db.Ping() logFatal(err) // serverの基本設定 srv := http.Server{ Addr: ":8080", WriteTimeout: 2 * time.Second, Handler: http.HandlerFunc(slowHandler), } // serverスタート log.Println("Start Http Server...") log.Fatal(srv.ListenAndServe()) } |
あとで実装を変更すると思いますが、ひとまず以下のコマンドで、Dockerコンテナを起動しましょう。
1 2 3 4 5 6 |
$ docker-compose up Recreating postgres ... done Recreating api ... done Attaching to postgres, api ... api | [00] 2020/12/22 02:45:31 Start Http Server... |
「Start Http Server…」と表示されたので、PostgreSQLには接続できました。
次回
PostgreSQLのマイグレーションについて学習しましょう。
[…] Go言語とPostgreSQLで遊ぼう!~環境構築編~ […]