Skip to content

Latest commit

 

History

History
91 lines (67 loc) · 2.1 KB

README.md

File metadata and controls

91 lines (67 loc) · 2.1 KB
title keywords description
PostgreSQL
postgresql
Connecting to a PostgreSQL database.

PostgreSQL Example

Github StackBlitz

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

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/postgresql
  2. Install dependencies:

    go get
  3. Set up your PostgreSQL database and update the connection string in the code.

Running the Application

  1. Start the application:

    go run main.go
  2. 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"))
}

References