Gorm 如何支持枚举值
来源:stackoverflow
时间:2024-02-16 15:39:23 296浏览 收藏
来到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删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习