Created
December 30, 2019 15:42
-
-
Save seandavi/c6b675291e76c786f54375765acb052d to your computer and use it in GitHub Desktop.
basic go postgres and logging example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module monitor | |
go 1.13 | |
require ( | |
github.com/jackc/pgx/v4 v4.1.2 | |
github.com/jinzhu/gorm v1.9.11 | |
github.com/joho/godotenv v1.3.0 | |
go.uber.org/zap v1.13.0 | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is for fun. | |
package main | |
import ( | |
"context" | |
"fmt" | |
"os" | |
"time" | |
"github.com/jackc/pgx/v4" | |
"github.com/joho/godotenv" | |
"go.uber.org/zap" | |
) | |
// The Queue struct represents a table in the database. | |
// | |
// It is meant to be used with gorm. | |
type Queue struct { | |
ID uint `gorm:"primary_key"` | |
Message string | |
Status string | |
Inserted time.Time | |
} | |
func (Queue) TableName() string { | |
return "queue" | |
} | |
func main() { | |
devlog, _ := zap.NewProduction() | |
sugar := devlog.Sugar() | |
defer sugar.Sync() | |
sugar.Infow("failed to fetch URL", | |
"url", "http://example.com", | |
"attempt", 3, | |
"backoff", time.Second, | |
) | |
err := godotenv.Load() | |
if err != nil { | |
sugar.Infow("failed to find .env file") | |
} | |
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) | |
if err != nil { | |
sugar.Infof("Unable to connection to database: %v\n", err) | |
os.Exit(1) | |
} | |
defer conn.Close(context.Background()) | |
rows, err := conn.Query(context.Background(), | |
"select status, count(*) as count "+ | |
"from queue where status is not NULL "+ | |
"group by status") | |
if err != nil { | |
sugar.Fatal(err) | |
} | |
// rows.Close is called by rows.Next when all rows are read | |
// or an error occurs in Next or Scan. So it may optionally be | |
// omitted if nothing in the rows.Next loop can panic. It is | |
// safe to close rows multiple times. | |
defer rows.Close() | |
// rows.Next() prepares the next row for scanning. | |
// Scanning simply loads the row contents into the | |
// prepared variables, passed as pointers. | |
var count uint | |
var status string | |
for rows.Next() { | |
err = rows.Scan(&status, &count) | |
fmt.Printf("%20s%15d\n", status, count) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment