From 8740f890da1dfb3259cf82944211979652bf777e Mon Sep 17 00:00:00 2001 From: Bel LaPointe <153096461+breel-render@users.noreply.github.com> Date: Tue, 9 Dec 2025 15:48:23 -0700 Subject: [PATCH] go template --- .gitignore | 1 + cmd/.template/main.go | 45 +++++++++++++++++++++++++++++++++++++++++++ cmd/generate.go | 3 +++ src/with/pg.go | 5 ++++- 4 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 cmd/.template/main.go create mode 100644 cmd/generate.go diff --git a/.gitignore b/.gitignore index 5559324..a628a74 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ /cmd/pg-lo-demo/pg-lo-demo /cmd/pg-pulse/pg-pulse /cmd/pg-walspam/pg-walspam +/cmd/pg-template diff --git a/cmd/.template/main.go b/cmd/.template/main.go new file mode 100644 index 0000000..87a6987 --- /dev/null +++ b/cmd/.template/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "context" + "database/sql" + "flag" + "log" + "os" + "time" + + "pg/src/with" + + _ "github.com/lib/pq" +) + +func main() { + if err := with.Context(run); err != nil { + panic(err) + } +} + +func run(ctx context.Context) error { + fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError) + c := fs.String("c", "postgresql://pulsegres:pulsegres@localhost:15432", "conn string") + if err := fs.Parse(os.Args[1:]); err != nil { + panic(err) + } + + return with.PSQL(ctx, *c, func(pg *sql.DB) error { + go with.Every(ctx, 5*time.Second, func() { + row := pg.QueryRowContext(ctx, `SELECT 1`) + var n int + if err := row.Err(); err != nil { + log.Println("query err:", err) + } else if err := row.Scan(&n); err != nil { + log.Println("scan err:", err) + } else { + log.Println("ping...") + } + }) + + <-ctx.Done() + return nil + }) +} diff --git a/cmd/generate.go b/cmd/generate.go new file mode 100644 index 0000000..8589502 --- /dev/null +++ b/cmd/generate.go @@ -0,0 +1,3 @@ +package main + +//go:generate sh -c "if ! [ -d ./pg-template ]; then cp -r ./.template ./pg-template; fi" diff --git a/src/with/pg.go b/src/with/pg.go index 0a43611..222dcf5 100644 --- a/src/with/pg.go +++ b/src/with/pg.go @@ -42,7 +42,10 @@ func PSQL(ctx context.Context, conn string, foo func(db *sql.DB) error) error { if ok { return } - case <-time.After(time.Second * 5): + } + select { + case <-ctx.Done(): + case <-time.After(time.Second): } } }()