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

Go项目调用Gorm插入License时触发nil指针解引用错误

解决Go+Gorm操作PostgreSQL时的nil指针引用错误

错误原因

  • 每次调用config.NewConfig()都会生成全新的Config实例,该实例的Repo字段未被初始化(NewConfig()仅设置了WebPort),直接访问Repo.InsertLicense会触发nil指针解引用错误。
  • 额外问题:Repository模块中使用全局db变量,而非结构体自身的Conn字段,虽然不是本次错误的直接原因,但容易引发其他潜在状态混乱问题。

修复方案

1. 使用全局初始化完成的Config实例

不要每次调用NewConfig()创建新实例,而是在项目启动时初始化一个全局Config,并完成Repo的配置:

// 全局Config实例,在项目启动阶段初始化
var appConfig *config.Config

func init() {
    appConfig = config.NewConfig()
    // 先初始化PostgreSQL连接conn(此处省略conn的创建逻辑)
    appConfig.SetupPostgresRepository(conn)
}

func generateAvailableLicenses() {
    license := entity.License{
        Key:         generateRandomLicenseKey(),
        IsUsed:      entity.AVAILABLE,
        CreatedAt:   time.Now().Format("2006-01-02"),
        ExpiresAt:   time.Now().AddDate(0, 0, 1).Format("2006-01-02"),
        CompanyId:   "1",
        CompanyName: "Company 1",
        TeamId:      "1",
        TeamName:    "Team 1",
    }
    availableLicenses = append(availableLicenses, license)

    // 使用全局已初始化的Config实例
    appConfig.Repo.InsertLicense(license)
}

2. 规范Repository的数据库连接使用

移除冗余的全局db变量,直接使用结构体自身的Conn字段,避免全局变量引发的状态混乱:

type PostgresRepository struct {
    Conn *gorm.DB
}

// 移除全局var db *gorm.DB

func NewPostgresRepository(pool *gorm.DB) *PostgresRepository {
    return &PostgresRepository{
        Conn: pool,
    }
}

func (u *PostgresRepository) InsertLicense(license entity.License) error {
    // 使用结构体自身的Conn字段
    result := u.Conn.Create(&license)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:54:16