当前位置:首页 > 文章列表 > 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大学堂免费AI认证证书:大模型工程师认证,提升您的职场竞争力
    免费AI认证证书
    科大讯飞AI大学堂推出免费大模型工程师认证,助力您掌握AI技能,提升职场竞争力。体系化学习,实战项目,权威认证,助您成为企业级大模型应用人才。
    31次使用
  • 茅茅虫AIGC检测:精准识别AI生成内容,保障学术诚信
    茅茅虫AIGC检测
    茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
    160次使用
  • 赛林匹克平台:科技赛事聚合,赋能AI、算力、量子计算创新
    赛林匹克平台(Challympics)
    探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
    210次使用
  • SEO  笔格AIPPT:AI智能PPT制作,免费生成,高效演示
    笔格AIPPT
    SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
    179次使用
  • 稿定PPT:在线AI演示设计,高效PPT制作工具
    稿定PPT
    告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
    169次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码