首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >仅在更新时Gorm和Gin错误500

仅在更新时Gorm和Gin错误500
EN

Stack Overflow用户
提问于 2020-11-20 17:50:51
回答 2查看 753关注 0票数 0

对于一个任务列表,我有一个非常简单的CRUD,到目前为止,我能够创建、列出所有、按ID列出的列表和删除记录,但是当我试图更新时,它会给我以下错误:

代码语言:javascript
运行
复制
go-proj          | reflect: call of reflect.Value.Field on string Value
go-proj          | /usr/local/go/src/reflect/value.go:850 (0x4a2464)
go-proj          |      Value.Field: panic(&ValueError{"reflect.Value.Field", v.kind()})
go-proj          | /go/pkg/mod/gorm.io/gorm@v1.20.7/schema/field.go:393 (0x996e50)
go-proj          |      (*Field).setupValuerAndSetter.func2: fieldValue := reflect.Indirect(value).Field(field.StructField.Index[0]).Field(field.StructField.Index[1])
go-proj          | /go/pkg/mod/gorm.io/gorm@v1.20.7/callbacks/update.go:230 (0xb3e3f0)
go-proj          |      ConvertToAssignments: value, isZero := field.ValueOf(updatingValue)
go-proj          | /go/pkg/mod/gorm.io/gorm@v1.20.7/callbacks/update.go:64 (0xb3bfd9)
go-proj          |      Update: if set := ConvertToAssignments(db.Statement); len(set) != 0 {
go-proj          | /go/pkg/mod/gorm.io/gorm@v1.20.7/callbacks.go:105 (0x9a5b7c)
go-proj          |      (*processor).Execute: f(db)
go-proj          | /go/pkg/mod/gorm.io/gorm@v1.20.7/finisher_api.go:303 (0x9ad886)
go-proj          |      (*DB).Updates: tx.callbacks.Update().Execute(tx)
go-proj          | /app/app/controllers/listController.go:70 (0xb49c7b)
go-proj          |      Update: if err := models.DB.Model(&list).Updates(input).Error; err != nil {
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x93d01a)
go-proj          |      (*Context).Next: c.handlers[c.index](c)
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/recovery.go:83 (0x951004)
go-proj          |      RecoveryWithWriter.func1: c.Next()
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x93d01a)
go-proj          |      (*Context).Next: c.handlers[c.index](c)
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/logger.go:241 (0x950104)
go-proj          |      LoggerWithConfig.func1: c.Next()
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x93d01a)
go-proj          |      (*Context).Next: c.handlers[c.index](c)
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:409 (0x947359)
go-proj          |      (*Engine).handleHTTPRequest: c.Next()
go-proj          | /go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:367 (0x946a4c)
go-proj          |      (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
go-proj          | /usr/local/go/src/net/http/server.go:2843 (0x6cd7c2)
go-proj          |      serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
go-proj          | /usr/local/go/src/net/http/server.go:1925 (0x6c8ecc)
go-proj          |      (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
go-proj          | /usr/local/go/src/runtime/asm_amd64.s:1374 (0x46cba0)
go-proj          |      goexit: BYTE    $0x90   // NOP
go-proj          | 
go-proj-nginx    | 172.27.0.1 - - [20/Nov/2020:17:32:56 +0000] "PUT /list/3 HTTP/1.1" 500 0 "-" "PostmanRuntime/7.6.0"

我尝试过更改两个框架( 戈姆杜松子酒 )的版本

我将提取代码中唯一重要的部分:

路由器:

代码语言:javascript
运行
复制
r := gin.Default()

r.PUT("/list/:id", controllers.Update)

型号:

代码语言:javascript
运行
复制
type List struct {
    gorm.Model
    UserId uint
    Title  string
    Status uint
}

主计长:

代码语言:javascript
运行
复制
type UpdateListInput struct {
        Title  string `json:"title"`
        Status uint   `json:"status"`
}

func Update(c *gin.Context) {
        var list models.List

        if err := models.DB.Where("id = ?", c.Param("id")).First(&list).Error; err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found"})
                return
        }

        var input UpdateListInput
        if err := c.ShouldBindJSON(&input); err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
                return
        }

        if err := models.DB.Model(&list).Updates(input).Error; err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }

        c.JSON(http.StatusOK, gin.H{"data": list})
}

我将向/list/:id发送以下JSON

代码语言:javascript
运行
复制
{
    "title": "Shopping List 2",
    "status": 2
}

要了解更多信息,您可以查看我的回购文件夹.docker/ on GitHub,也许我在Nginx、Postgres甚至Golang配置上搞砸了什么东西,因为我在容器上运行我的应用程序。

Edit1: --我通过硬编码要在控制器中更新的数据来工作:

代码语言:javascript
运行
复制
func Update(c *gin.Context) {                                  
     var list models.List                                  
     if err := models.DB.Where("id = ?", c.Param("id")).First(&list).Error; err != nil {                                  
         c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found"})                                  
         return                                  
     }                                  
                                   
     input := map[string]interface{}{                                        
         "title":  "AAAAAAAAAa",                                                                                                                         
         "status": 3,                                                                                                                                    
     }                                                                                                                                                   
     if err := models.DB.Model(&list).Updates(input).Error; err != nil {                                                                                 
         c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})                                                                                      
         return                                                                                                                                          
     }                                                                                                                                                   
                                                                                       
      c.JSON(http.StatusOK, gin.H{"data": list})
}  
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-20 19:32:11

这是一个解决办法,我可能会在戈姆氏上打开一个问题,因为我不认为这是正确的方法,我要做的唯一的事情就是使用https://golang.org/pkg/reflect包从UpdateListInput struct转换为map[string]interface{}的变量

这是我的控制器:

代码语言:javascript
运行
复制
func Update(c *gin.Context) {
        var list models.List
        if err := models.DB.Where("id = ?", c.Param("id")).First(&list).Error; err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found"})
                return
        }

        var input UpdateListInput
        if err := c.ShouldBindJSON(&input); err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
                return
        }
        v := reflect.ValueOf(input)
        typeOfV := v.Type()

        inputData := map[string]interface{}{}

        for i := 0; i < v.NumField(); i++ {
                inputData[typeOfV.Field(i).Name] = v.Field(i).Interface()
        }

        if err := models.DB.Model(&list).Updates(inputData).Error; err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
                return
        }

        c.JSON(http.StatusOK, gin.H{"data": list})
}
票数 1
EN

Stack Overflow用户

发布于 2022-05-08 09:11:46

在控制器中试一试:

代码语言:javascript
运行
复制
data := models.List{Title: input.Title,Status: input.Status}

if err := models.DB.Model(&list).Updates(&data).Error; err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}

c.JSON(http.StatusOK, gin.H{"data": data})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64934410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档