Complete BLoC with Clean Architecture (group chat) Discount !! E-commerce App With Backend Source Code Video and Voice Chatting App Firebase Chatting App Source Code Complete Gym App BLoC State Management Source Code Complete Study App Buy Ticket Booking App Source Code Buy Travel App With Backend Source Code Complete Chat App Udemy Course Special Offer Discount !! Online Learning Course App (BLoC) Online Learning Course App (Riverpod) Online Learning Course App (Getx) Discount !! Shopping App (Provider) Cool Flutter Game Flutter Nodejs Chat App Flutter Nodejs Api And Firebase Chat App Riverpod Task Management App
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.