来到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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
