Go Lang Connect Postgres

Created At: 2023-04-25 07:05:31 Updated At: 2023-04-30 17:50:13

Here is the example how to connect Golang with Postgres database. There are a few steps for it. First you have to create database struct and create sqlx.DB  instance in the struct.

type Database struct{
	Client *sqlx.DB
}

Then we will create a new function name NewDatabase() which will read and save the local Postgres database related info in a variable. 

Inside NewDatabase() function, we use fmt.Sprintf() function to read the underlying database information from the OS.

connectionString := fmt.Sprintf(
		"host=%s port=%s user=%s dbname=%s password=%s sslmode=%s",
		os.Getenv("DB_HOST"), 
		os.Getenv("DB_PORT"), 
		os.Getenv("DB_USERNAME"), 
		os.Getenv("DB_TABLE"),
		os.Getenv("DB_PASSWORD"),
		os.Getenv("SSL_MODE"),
	)

Since the above function returns a lot of information, we will pass that info into sqlx.Connect() function.

This will deal with database connection and return an instance of the database connection. If there are no errors we will return database connection.

package db

import (
	"fmt"
	"os"
	"context"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

type Database struct{
	Client *sqlx.DB
}

func NewDatabase() (*Database, error) {
	connectionString := fmt.Sprintf(
		"host=%s port=%s user=%s dbname=%s password=%s sslmode=%s",
		os.Getenv("DB_HOST"), 
		os.Getenv("DB_PORT"), 
		os.Getenv("DB_USERNAME"), 
		os.Getenv("DB_TABLE"),
		os.Getenv("DB_PASSWORD"),
		os.Getenv("SSL_MODE"),
	)

	dbConn, err := sqlx.Connect("postgres", connectionString)

	if err != nil {
		return &Database{}, fmt.Errorf("error connecting to: %w", err)
	}
	return &Database{Client: dbConn}, nil
}

func (d *Database) Ping(ctx context.Context) error{
	return d.Client.DB.PingContext(ctx)
}

We also created a Ping() here, so that you can ping the database connection from a different package. Internally it uses PingContext(context).

Now inside main.go, inside main() function, you may call 

func main(){
  fmt.Println("Application start up")
	db, err := db.NewDatabase()
	if err != nil {
		fmt.Println("Error creating database")
	}
	if err := db.Ping(context.Background()); err != nil {
		return err
	}
	fmt.Println("successfully connected to database")
	return nil
}

Before you call that make sure you package db at the top.

See the log messages which states our connection is successful.

Comment

Add Reviews