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 数据中的浮点数转换为整数时,进行字节解码
- 下一篇
- TinyGo: 使用 TinyGo 控制 Arduino 的 PWM 输出指南
查看更多
最新文章
-
- Golang · Go问答 | 5小时前 |
- Go cgo.Handle 管理 Go 值跨语言传递
- 403浏览 收藏
-
- Golang · Go问答 | 5小时前 | CGO · 内存管理 · Go问答 · Go CGO unsafe.Pointer cgo.Handle runtime.Pinner
- Go cgo 指针规则导致 panic 的边界定位
- 223浏览 收藏
-
- Golang · Go问答 | 6小时前 | go ·
- Go GOMAXPROCS 变化对并发吞吐的影响
- 417浏览 收藏
-
- Golang · Go问答 | 7小时前 | go · pprof · Go alloc_space inuse_space heap profile
- Go heap profile inuse_space 与 alloc_space 的选择
- 350浏览 收藏
-
- Golang · Go问答 | 7小时前 | go · 性能排查 ·
- Go runtime/trace 观察阻塞区域的阅读方式
- 283浏览 收藏
-
- Golang · Go问答 | 7小时前 | Go问答 · Go pprof 性能剖析 goroutine泄漏 并发排查
- Go pprof goroutine 泄漏剖析的采样方法
- 104浏览 收藏
-
- Golang · Go问答 | 7小时前 | 垃圾回收 · 资源管理 · Go问答 · Go 资源释放 AddCleanup close SetFinalizer
- Go SetFinalizer 不适合资源关闭的替代方案
- 439浏览 收藏
-
- Golang · Go问答 | 8小时前 |
- Go runtime.KeepAlive 防止句柄过早回收
- 489浏览 收藏
-
- Golang · Go问答 | 8小时前 |
- Go Signal Stop 与退出流程的竞态处理
- 168浏览 收藏
-
- Golang · Go问答 | 2天前 |
- Go ColumnTypes 推断动态查询字段的安全用法
- 319浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 290次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 343次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 346次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 308次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 131次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
