From fad73f26de4ef5f532e5c1dc83319b8661c56978 Mon Sep 17 00:00:00 2001 From: Tomasz Polgrabia Date: Mon, 29 Jul 2024 23:14:42 +0200 Subject: [PATCH] Adding setup for postgres docker compose + connection from app. --- 2024/07/golang_demo1/docker_compose.yml | 11 +++++++++++ 2024/07/golang_demo1/go.mod | 14 ++++++++++++++ 2024/07/golang_demo1/main.go | 22 ++++++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 2024/07/golang_demo1/docker_compose.yml diff --git a/2024/07/golang_demo1/docker_compose.yml b/2024/07/golang_demo1/docker_compose.yml new file mode 100644 index 0000000..85b64f3 --- /dev/null +++ b/2024/07/golang_demo1/docker_compose.yml @@ -0,0 +1,11 @@ +services: + db: + image: postgres:11 + ports: + - '5432:5432' + volumes: + - '/opt/db_data:/var/lib/postgresql/data' + environment: + POSTGRES_PASSWORD: pass + POSTGRES_DB: repo + POSTGRES_USER: db_user \ No newline at end of file diff --git a/2024/07/golang_demo1/go.mod b/2024/07/golang_demo1/go.mod index a545d69..c9e95d1 100644 --- a/2024/07/golang_demo1/go.mod +++ b/2024/07/golang_demo1/go.mod @@ -1,3 +1,17 @@ module golang_demo1 go 1.22 + +require ( + github.com/go-pg/pg/v10 v10.13.0 // indirect + github.com/go-pg/zerochecker v0.2.0 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect + github.com/vmihailenco/bufpool v0.1.11 // indirect + github.com/vmihailenco/msgpack/v5 v5.3.4 // indirect + github.com/vmihailenco/tagparser v0.1.2 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + golang.org/x/crypto v0.21.0 // indirect + golang.org/x/sys v0.18.0 // indirect + mellium.im/sasl v0.3.1 // indirect +) diff --git a/2024/07/golang_demo1/main.go b/2024/07/golang_demo1/main.go index 03aeda4..61340d9 100644 --- a/2024/07/golang_demo1/main.go +++ b/2024/07/golang_demo1/main.go @@ -1,13 +1,35 @@ package main import ( + "context" "flag" "fmt" + "github.com/go-pg/pg/v10" "golang_demo1/handlers" "net/http" ) func main() { + var opt, errDb = pg.ParseURL("postgres://db_user:pass@localhost:5432/repo?sslmode=disable") + if errDb != nil { + panic("Failed to parse url: " + errDb.Error()) + } + var db = pg.Connect(opt) + + if db == nil { + panic("failed to connect to the database") + } + + defer func(db *pg.DB) { + _ = db.Close() + }(db) + + ctx := context.Background() + + if err := db.Ping(ctx); err != nil { + panic("Failed to ping: " + err.Error()) + } + portPtr := flag.Int("port", 8080, "port for webserver") flag.Parse() port := *portPtr