PostgreSQL Example
This project demonstrates how to connect to a PostgreSQL database in a Go application using the Fiber framework.
Prerequisites
Ensure you have the following installed:
- Golang
- Fiber package
- PostgreSQL
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git
cd recipes/postgresql -
Install dependencies:
go get
-
Set up your PostgreSQL database and update the connection string in the code.
Running the Application
-
Start the application:
go run main.go
-
Access the application at
http://localhost:3000
.
Example
Here is an example of how to connect to a PostgreSQL database in a Fiber application:
package main
import (
"database/sql"
"log"
"github.com/gofiber/fiber/v2"
_ "github.com/lib/pq"
)
func main() {
// Database connection
connStr := "user=username dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Fiber instance
app := fiber.New()
// Routes
app.Get("/", func(c *fiber.Ctx) error {
var greeting string
err := db.QueryRow("SELECT 'Hello, World!'").Scan(&greeting)
if err != nil {
return err
}
return c.SendString(greeting)
})
// Start server
log.Fatal(app.Listen(":3000"))
}