Labstack gorm example 1

From UVOO Tech Wiki
Jump to navigation Jump to search
package main

import (
    "github.com/google/uuid"
    "github.com/labstack/echo/v4"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

var db *gorm.DB

type Page struct {
    ID   uuid.UUID `gorm:"type:uuid;primaryKey"`
    Name string
}

func main() {
    // Initialize Echo
    e := echo.New()

    // Initialize GORM
    var err error
    db, err = gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
    if err != nil {
        e.Logger.Fatal(err)
    }

    // Auto-migrate the schema
    if err := db.AutoMigrate(&Page{}); err != nil {
        e.Logger.Fatal(err)
    }

    // Routes
    e.GET("/pages", getPages)
    e.POST("/pages", createPage)

    // Start server
    e.Logger.Fatal(e.Start(":8080"))
}

// Handler for GET /pages
func getPages(c echo.Context) error {
    // Retrieve all pages from the database
    var pages []Page
    if err := db.Find(&pages).Error; err != nil {
        return c.JSON(500, map[string]string{"error": "Failed to retrieve pages"})
    }
    return c.JSON(200, pages)
}

// Handler for POST /pages
func createPage(c echo.Context) error {
    // Bind request body to Page struct
    var page Page
    if err := c.Bind(&page); err != nil {
        return c.JSON(400, map[string]string{"error": "Invalid request body"})
    }

    // Generate UUID for the ID field
    page.ID = uuid.New()

    // Create new page record in the database
    if err := db.Create(&page).Error; err != nil {
        return c.JSON(500, map[string]string{"error": "Failed to create page"})
    }

    return c.JSON(201, page)
}