跳到主要内容

GORM 与 PostgreSQL 示例

Github StackBlitz

本项目演示了如何使用 Fiber 框架结合 GORM 和 PostgreSQL 设置 Go 应用程序。

先决条件

确保已安装以下软件

设置

  1. 克隆仓库

    git clone https://github.com/gofiber/recipes.git
    cd recipes/gorm-postgres
  2. 安装依赖项

    go get
  3. 设置 PostgreSQL 并创建数据库

    createdb mydb
  4. 如有必要,更新代码中的数据库连接字符串。

运行应用程序

  1. 启动应用程序

    go run main.go
  2. 访问应用程序,地址为 http://localhost:3000

示例

以下是使用 GORM 和 PostgreSQL 的 Fiber 应用程序的 main.go 示例文件

package main

import (
"log"
"github.com/gofiber/fiber/v2"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"size:255"`
Email string `gorm:"uniqueIndex"`
}

func main() {
dsn := "host=localhost user=youruser password=yourpassword dbname=mydb port=5432 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}

db.AutoMigrate(&User{})

app := fiber.New()

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, GORM with PostgreSQL!")
})

app.Post("/users", func(c *fiber.Ctx) error {
user := new(User)
if err := c.BodyParser(user); err != nil {
return c.Status(400).SendString(err.Error())
}
db.Create(user)
return c.JSON(user)
})

log.Fatal(app.Listen(":3000"))
}

参考资料