Connessione a PostgreSQL in Fiber

Mattepuffo's logo
Connessione a PostgreSQL in Fiber

Connessione a PostgreSQL in Fiber

In questo articolo vediamo come connetterci ad un db PostgreSQL in Fiber.

Faremo una sola rotta per l'interrogazione di una tabella.

Prima di tutto installiamo il necessario:

go get github.com/gofiber/fiber/v2
go get github.com/lib/pq

La tabella che interroghiamo (utenti) ha solo due campi; inoltre faremo solo una query, giusto per fare un test veloce:

package main

import (
	"database/sql"
	"fmt"
	"os"

	"github.com/gofiber/fiber/v2"
	_ "github.com/lib/pq"
)

type Utente struct {
	ID    int    `json:"id"`
	Email string `json:"email"`
}

var db *sql.DB

func main() {
	connStr := "user=postgres password=9211 dbname=postgres host=localhost port=5432 sslmode=disable"

	var err error
	db, err = sql.Open("postgres", connStr)

	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}

	if err := db.Ping(); err != nil {
		fmt.Println(err)
		os.Exit(0)
	}

	app := fiber.New()

	app.Get("/utenti", func(c *fiber.Ctx) error {
		rows, err := db.Query("SELECT id, email FROM utenti")
		if err != nil {
			return c.Status(500).SendString("Errore query: " + err.Error())
		}

		defer rows.Close()

		var utenti []Utente

		for rows.Next() {
			var u Utente
			if err := rows.Scan(&u.ID, &u.Email); err != nil {
				return c.Status(500).SendString("Errore lettura dati")
			}
			utenti = append(utenti, u)
		}

		return c.JSON(utenti)
	})

	app.Listen(":3000")
}

Enjoy!


Condividi

Commentami!