You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GORM与Gin创建带关联对象时触发空指针Panic

GORM创建含关联对象的实体时触发空指针 panic

错误日志

2023/11/01 20:44:14 [Recovery] 2023/11/01 - 20:44:14 panic recovered:
POST /v1/product/products HTTP/1.1
Host: localhost:8080
Accept: */*
Content-Length: 589
Content-Type: application/json
User-Agent: curl/8.4.0


runtime error: invalid memory address or nil pointer dereference
/usr/lib/go/src/runtime/panic.go:261 (0x452d97)
        panicmem: panic(memoryError)
/usr/lib/go/src/runtime/signal_unix.go:861 (0x452d65)
        sigpanic: panicmem()
/home/grimm/go/pkg/mod/gorm.io/gorm@v1.25.5/finisher_api.go:18 (0x926e7c)
        (*DB).Create: if db.CreateBatchSize > 0 {
/home/grimm/Documents/beeskill/website/back_end/API_website/main.go:122 (0x99cfab)
        CreatingProduct: DB.Create(&data)
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 (0x8c9ad9)
        (*Context).Next: c.handlers[c.index](c)
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/recovery.go:102 (0x8c9ac7)
        CustomRecoveryWithWriter.func1: c.Next()
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 (0x8c8c7d)
        (*Context).Next: c.handlers[c.index](c)
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/logger.go:240 (0x8c8c4c)
        LoggerWithConfig.func1: c.Next()
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 (0x8c7d3a)
        (*Context).Next: c.handlers[c.index](c)
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/gin.go:620 (0x8c79cd)
        (*Engine).handleHTTPRequest: c.Next()
/home/grimm/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/gin.go:576 (0x8c74fc)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/lib/go/src/net/http/server.go:2938 (0x6a35ed)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/lib/go/src/net/http/server.go:2009 (0x69f4d3)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/lib/go/src/runtime/asm_amd64.s:1650 (0x46ed20)
        goexit: BYTE    $0x90   // NOP

代码实现

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type CategoryProduct struct {
    gorm.Model
    Title       string `json:"title" gorm:"not null"`
    Description string `json:"description"`
}

type CreateCategoryProduct struct {
    gorm.Model
    Title       string `json:"title" binding:"required"`
    Description string `json:"description" binding:"required"`
}

type PriceYearProduct struct {
    gorm.Model
    Price       float64 `json:"price" gorm:"not null"`
    Description string  `json:"description"`
}

type CreatePriceYearProduct struct {
    gorm.Model
    Price       float64 `json:"price" binding:"required"`
    Description string  `json:"description" binding:"required"`
}

type PriceMounthProduct struct {
    gorm.Model
    Price       float64 `json:"price" gorm:"not null"`
    Description string  `json:"description"`
}

type CreatePriceMounthProduct struct {
    gorm.Model
    Price       float64 `json:"price" binding:"required"`
    Description string  `json:"description" binding:"required"`
}

type Product struct {
    gorm.Model
    Name               string             `json:"name" gorm:"not null"`
    Description        string             `json:"description" gorm:"not null"`
    PriceMounthProduct PriceMounthProduct `json:"pricemounth"`
    PriceYearProduct   PriceYearProduct   `json:"priceyear"`
    CategoryProduct    CategoryProduct    `json:"category"`
}

type CreateProduct struct {
    gorm.Model
    Name               string             `json:"name" binding:"required"`
    Description        string             `json:"description" binding:"required"`
    PriceMounthProduct PriceMounthProduct `json:"pricemounth" binding:"required"`
    PriceYearProduct   PriceYearProduct   `json:"priceyear" binding:"required"`
    CategoryProduct    CategoryProduct    `json:"category" binding:"required"`
}

var DB *gorm.DB

func ConnectDatabase() {
    database, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("Failed to connect to database!")
    }
    err = database.AutoMigrate(&CategoryProduct{}, &PriceYearProduct{}, &PriceMounthProduct{})
    if err != nil {
        return
    }
    err = database.AutoMigrate(&Product{})
    if err != nil {
        return
    }
    DB = database
}

func CreatingProduct(c *gin.Context) {
    var input CreateProduct
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    data := Product{
        Name:               input.Name,
        Description:        input.Description,
        PriceYearProduct:   input.PriceYearProduct,
        PriceMounthProduct: input.PriceMounthProduct,
        CategoryProduct:    input.CategoryProduct,
    }
    DB.Create(&data)

    c.JSON(http.StatusOK, gin.H{"data": data})
}

func Routes() {
    router := gin.Default()
    v1 := router.Group("/v1")
    {
        product := v1.Group("/product")
        product.POST("/products", CreatingProduct)
    }
    if err := router.Run(":8080"); err != nil {
        return
    }
}

func main() {
    ConnectDatabase()
    Routes()
}

请求数据

Curl命令

curl http://localhost:8080/v1/product/products --request "POST" --header "Content-Type: application/json" --data @file.json

file.json内容

{
    "name": "airplane simulation",
    "description": "airplane simulation for everybody, childrens to adults.",
    "priceyear": {
      "price": 44.99,
      "description": "pay for a year to access on irplane simulation for everybody, childrens to adults."
    },
    "pricemounth": {
      "price": 4.99,
      "description": "pay for a mounth to access on irplane simulation for everybody, childrens to adults."
    },
    "category": {
      "title": "Airplane",
      "description": "Information cataegorized on airplane."
    }
}

解决方案

1. 修复DB空指针问题

空指针panic的直接原因是ConnectDatabase函数中,若AutoMigrate执行失败会直接return,导致全局变量DB未被赋值,始终为nil。修改ConnectDatabase,在AutoMigrate出错时panic,确保只有数据库初始化完全成功时才赋值DB:

func ConnectDatabase() {
    database, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("Failed to connect to database!")
    }
    err = database.AutoMigrate(&CategoryProduct{}, &PriceYearProduct{}, &PriceMounthProduct{}, &Product{})
    if err != nil {
        panic("Failed to auto migrate tables: " + err.Error())
    }
    DB = database
}

2. 修正关联关系定义

当前代码中Product结构体的关联字段是值类型,GORM会将其作为嵌入字段直接合并到products表中,而非创建独立的关联表。如果需要一对一关联,需将关联字段改为指针类型,并添加GORM关联标签(可选,GORM会自动生成外键):

type Product struct {
    gorm.Model
    Name               string                  `json:"name" gorm:"not null"`
    Description        string                  `json:"description" gorm:"not null"`
    PriceMounthProduct *PriceMounthProduct     `json:"pricemounth" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
    PriceYearProduct   *PriceYearProduct       `json:"priceyear" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
    CategoryProduct    *CategoryProduct        `json:"category" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

同时,CreateProduct结构体无需嵌入gorm.Model(创建时无需ID、时间戳等字段,由GORM自动生成),且关联字段需改为指针类型:

type CreateProduct struct {
    Name               string                  `json:"name" binding:"required"`
    Description        string                  `json:"description" binding:"required"`
    PriceMounthProduct *PriceMounthProduct     `json:"pricemounth" binding:"required"`
    PriceYearProduct   *PriceYearProduct       `json:"priceyear" binding:"required"`
    CategoryProduct    *CategoryProduct        `json:"category" binding:"required"`
}

3. 保存关联对象

修改CreatingProduct函数,增加错误处理,确保主对象和关联对象一起写入数据库:

func CreatingProduct(c *gin.Context) {
    var input CreateProduct
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    data := Product{
        Name:               input.Name,
        Description:        input.Description,
        PriceYearProduct:   input.PriceYearProduct,
        PriceMounthProduct: input.PriceMounthProduct,
        CategoryProduct:    input.CategoryProduct,
    }

    if err := DB.Create(&data).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"data": data})
}

内容的提问来源于stack exchange,提问作者Lucas Chtroude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 07:40:56