当前位置:首页 > 文章列表 > Golang > Go问答 > Gorm 如何支持枚举值

Gorm 如何支持枚举值

来源:stackoverflow 2024-02-16 15:39:23 0浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《Gorm 如何支持枚举值》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

大家好,我是 go 和 gorm 的新手,我正在使用 postgres 构建一个简单的 web 服务,我在让我的模型支持枚举值时遇到了问题,经过一些研究,我找到了一种方法来做到这一点。但我开始遇到新的错误,在在线研究资源后我似乎无法修复这些错误。

每当我尝试从数据库中获取用户时,我都会收到此错误:

panic: interface conversion: interface {} is string, not []uint8
 
 -> userservice/models.(*roleallowed).scan
 ->   /users/cipher/work/frontendlabs/shopvending/userservice/models/user.model.go:22

    database/sql.convertassignrows
      /usr/local/go/src/database/sql/convert.go:385
    database/sql.convertassignrows
      /usr/local/go/src/database/sql/convert.go:428
    database/sql.(*rows).scan
      /usr/local/go/src/database/sql/sql.go:3287
    gorm.io/gorm.(*db).scanintostruct
      /users/cipher/go/pkg/mod/gorm.io/[email protected]/scan.go:67
    gorm.io/gorm.scan
      /users/cipher/go/pkg/mod/gorm.io/[email protected]/scan.go:293
    gorm.io/gorm/callbacks.query
      /users/cipher/go/pkg/mod/gorm.io/[email protected]/callbacks/query.go:26
    gorm.io/gorm.(*processor).execute
      /users/cipher/go/pkg/mod/gorm.io/[email protected]/callbacks.go:130
    gorm.io/gorm.(*db).first
      /users/cipher/go/pkg/mod/gorm.io/[email protected]/finisher_api.go:129
    userservice/services.userservice.finduserbyemail
      /users/cipher/work/frontendlabs/shopvending/userservice/services/user.service.go:25
    userservice/handlers.manuallogin
      /users/cipher/work/frontendlabs/shopvending/userservice/handlers/auth.handler.go:24
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5.(*mux).routehttp
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:442
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5.(*mux).servehttp
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:71
    github.com/go-chi/chi/v5.(*mux).mount.func1
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:314
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5.(*mux).routehttp
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:442
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5/middleware.timeout.func1.1
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/timeout.go:45
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    userservice/middlewares.commonmiddleware.func1
      /users/cipher/work/frontendlabs/shopvending/userservice/middlewares/contenttype.go:8
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5/middleware.recoverer.func1
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/recoverer.go:38
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5/middleware.requestlogger.func1.1
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/logger.go:57
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5/middleware.realip.func1
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/realip.go:35
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5/middleware.requestid.func1
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/request_id.go:76
    net/http.handlerfunc.servehttp
      /usr/local/go/src/net/http/server.go:2109
    github.com/go-chi/chi/v5.(*mux).servehttp
      /users/cipher/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:88
    net/http.serverhandler.servehttp
      /usr/local/go/src/net/http/server.go:2947
    net/http.(*conn).serve
      /usr/local/go/src/net/http/server.go:1991
    created by net/http.(*server).serve
      /usr/local/go/src/net/http/server.go:3102

我尝试将字节转换为字符串,但仍然收到错误。

我的用户服务文件:

package services

import (
    "github.com/sirupsen/logrus"
    "userservice/database"
    "userservice/dto"
    "userservice/models"
)

type userservice struct{}

//func (u userservice) finduserbyid(id int) *models.user {
//  user := u.user
//  if err := database.instance.where("id = ?", id).first(&user); err != nil {
//      logrus.errorf("can not find user with id %d", id)
//      return nil
//
//  }
//  return user
//
//}

func (u userservice) finduserbyemail(email string) *models.user {
    var user models.user
    if err := database.instance.where("email = ?", email).first(&user); err.error != nil {
        logrus.errorf("can not find user with email %s", err.error)
        return nil

    }
    return &user

}

func (u userservice) createuser(newuser dto.createnewuserdto) *models.user {
    createnewuser := models.user{
        email:    newuser.email,
        password: newuser.password,
    }
    createnewuser.hashpassword(createnewuser.password)
    err := database.instance.create(&createnewuser)
    if err.error != nil {
        logrus.errorf("error saving food to the database: %s", err.error)
        return nil
    }

    return &createnewuser

}

问题是当我由于某种原因调用“finduserbyemail”时它无法序列化。

它一直有效,直到我引入枚举值集成。现在我收到上面的错误。

我的用户模型文件:

package models

import (
    "database/sql/driver"
    "golang.org/x/crypto/bcrypt"
    "gorm.io/gorm"
    "time"
)

type RoleAllowed string

const (
    admin   RoleAllowed = "admin"
    seller  RoleAllowed = "seller"
    rider   RoleAllowed = "rider"
    regular RoleAllowed = "regular"
)

func (st *RoleAllowed) Scan(value interface{}) error {
    *st = RoleAllowed(value.([]byte))
    return nil
}

func (st RoleAllowed) Value() (driver.Value, error) {
    return string(st), nil
}

type StatusAllowed string

const (
    suspended StatusAllowed = "suspended"
    active    StatusAllowed = "active"
    inactive  StatusAllowed = "inactive"
)

func (st *StatusAllowed) Scan(value interface{}) error {
    *st = StatusAllowed(value.([]byte))
    return nil
}

func (st StatusAllowed) Value() (driver.Value, error) {
    return string(st), nil
}

type User struct {
    ID              uint           `json:"id" gorm:"type:bigserial;primaryKey;autoIncrement"`
    Email           string         `json:"email" gorm:"type:varchar(255);unique;not null"`
    Password        string         `json:"password" gorm:"type:varchar(255);unique;not null""`
    OTPCode         int            `json:"otp_code"`
    Role            RoleAllowed    `json:"role" gorm:"type:role_allowed;default:'regular'"`
    Status          StatusAllowed  `json:"status" gorm:"type:status_allowed;default:'active'"`
    IsEmailVerified bool           `json:"isEmailVerified" gorm:"default:false"`
    OTPExpireTime   time.Time      `json:"otp_expire_time"`
    CreatedAt       time.Time      `json:"createdAt"`
    UpdatedAt       time.Time      `json:"updatedAt"`
    DeletedAt       gorm.DeletedAt `gorm:"index"`
}

func (u *User) HashPassword(password string) error {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    if err != nil {
        return err
    }
    u.Password = string(bytes)
    return nil
}

func (u *User) CheckPasswordHash(password string) error {
    err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
    if err != nil {
        return err
    }
    return nil
}

请帮忙解决此问题?


正确答案


我编辑了下面的代码

package models

import (
    "database/sql/driver"
    "golang.org/x/crypto/bcrypt"
    "gorm.io/gorm"
    "time"
)

type RoleAllowed string

const (
    admin   RoleAllowed = "admin"
    seller  RoleAllowed = "seller"
    rider   RoleAllowed = "rider"
    regular RoleAllowed = "regular"
)

func (st *RoleAllowed) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        *st = RoleAllowed(b)
    }
    return nil
}

func (st RoleAllowed) Value() (driver.Value, error) {
    return string(st), nil
}

type StatusAllowed string

const (
    suspended StatusAllowed = "suspended"
    active    StatusAllowed = "active"
    inactive  StatusAllowed = "inactive"
)

func (st *StatusAllowed) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        *st = StatusAllowed(b)
    }
    return nil
}

func (st StatusAllowed) Value() (driver.Value, error) {
    return string(st), nil
}

type User struct {
    ID              uint           `json:"id" gorm:"type:bigserial;primaryKey;autoIncrement"`
    Email           string         `json:"email" gorm:"type:varchar(255);unique;not null"`
    Password        string         `json:"password" gorm:"type:varchar(255);unique;not null""`
    OTPCode         int            `json:"otp_code"`
    Role            RoleAllowed    `json:"role" gorm:"type:role_allowed;default:'regular'"`
    Status          StatusAllowed  `json:"status" gorm:"type:status_allowed;default:'active'"`
    IsEmailVerified bool           `json:"isEmailVerified" gorm:"default:false"`
    OTPExpireTime   time.Time      `json:"otp_expire_time"`
    CreatedAt       time.Time      `json:"createdAt"`
    UpdatedAt       time.Time      `json:"updatedAt"`
    DeletedAt       gorm.DeletedAt `gorm:"index"`
}

func (u *User) HashPassword(password string) error {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    if err != nil {
        return err
    }
    u.Password = string(bytes)
    return nil
}

func (u *User) CheckPasswordHash(password string) error {
    err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
    if err != nil {
        return err
    }
    return nil
}

我必须检查类型,然后分配我需要的正确值。谢谢@mkopriva

本篇关于《Gorm 如何支持枚举值》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
将 JSON 数据中的浮点数转换为整数时,进行字节解码将 JSON 数据中的浮点数转换为整数时,进行字节解码
上一篇
将 JSON 数据中的浮点数转换为整数时,进行字节解码
TinyGo: 使用 TinyGo 控制 Arduino 的 PWM 输出指南
下一篇
TinyGo: 使用 TinyGo 控制 Arduino 的 PWM 输出指南
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 笔灵AI生成答辩PPT:高效制作学术与职场PPT的利器
    笔灵AI生成答辩PPT
    探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
    24次使用
  • 知网AIGC检测服务系统:精准识别学术文本中的AI生成内容
    知网AIGC检测服务系统
    知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
    40次使用
  • AIGC检测服务:AIbiye助力确保论文原创性
    AIGC检测-Aibiye
    AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
    38次使用
  • 易笔AI论文平台:快速生成高质量学术论文的利器
    易笔AI论文
    易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
    50次使用
  • 笔启AI论文写作平台:多类型论文生成与多语言支持
    笔启AI论文写作平台
    笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
    41次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码