繁体   English   中英

如何在 Gorm 中支持 Enum 值

[英]How to support Enum value in Gorm

大家好,我是 go 和 Gorm 的新手,我正在使用 Postgres 构建一个简单的 web 服务,我在获取 model 后遇到了问题,我找到了支持 doum 值的方法。 但是我开始遇到新的错误,在网上研究资源后似乎无法修复。

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

 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/gorm@v1.23.8/scan.go:67
    gorm.io/gorm.Scan
      /Users/Cipher/go/pkg/mod/gorm.io/gorm@v1.23.8/scan.go:293
    gorm.io/gorm/callbacks.Query
      /Users/Cipher/go/pkg/mod/gorm.io/gorm@v1.23.8/callbacks/query.go:26
    gorm.io/gorm.(*processor).Execute
      /Users/Cipher/go/pkg/mod/gorm.io/gorm@v1.23.8/callbacks.go:130
    gorm.io/gorm.(*DB).First
      /Users/Cipher/go/pkg/mod/gorm.io/gorm@v1.23.8/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/v5@v5.0.7/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/v5@v5.0.7/mux.go:71
    github.com/go-chi/chi/v5.(*Mux).Mount.func1
      /Users/Cipher/go/pkg/mod/github.com/go-chi/chi/v5@v5.0.7/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/v5@v5.0.7/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/v5@v5.0.7/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/v5@v5.0.7/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/v5@v5.0.7/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/v5@v5.0.7/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/v5@v5.0.7/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/v5@v5.0.7/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”时它无法序列化。

它一直在工作,直到我介绍了枚举值集成。 现在我得到了上面的错误。

我的用户 model 文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM