登录
首页 >  Golang >  Go问答

运行时错误:GORM 在处理 POST 请求时取消了无效的内存地址或 nil 指针

来源:stackoverflow

时间:2024-02-20 19:18:27 325浏览 收藏

本篇文章给大家分享《运行时错误:GORM 在处理 POST 请求时取消了无效的内存地址或 nil 指针》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

//main.go
package main

import (
    "testgoproject/src/mappings"
    "testgoproject/src/models"
    _ "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    _ "net/http"
)

var db *gorm.db

func main()  {
    initdb()
    mappings.initializeroutes()

}

func initdb() {
    var err error
    db, err = gorm.open("mysql", "root:helloworld@/testapp2?charset=utf8&parsetime=true&loc=local")

    if err != nil {
        panic("failed to connect database")
    }
    db.automigrate(&models.bookmodel{})
}
//router.go
package mappings

import (
    "testgoproject/src/controllers"
    "github.com/gin-gonic/gin"
)

func initializeroutes()  {
    router := gin.default()
    router.get("/", controllers.index)
    router.post("/createbook", controllers.create)
    _ = router.run()
}
//bookcontroller.go
package controllers

import (
    "testgoproject/src/models"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "net/http"
)

var db = gorm.db{}

func index(c *gin.context)  {
    c.json(http.statusok, gin.h{"status": http.statusok, "message": "im here!"})
}

func create(c *gin.context)  {
    book := models.bookmodel{
        title: c.postform("title"),
        author: c.postform("author"),
    }

    db.create(&book)
    c.json(http.statuscreated, gin.h{"status": http.statuscreated, "message": "book created successfully!", "bookid": book.id})
}
//bookmodel.go
package models

import "github.com/jinzhu/gorm"

type bookmodel struct {
    gorm.model
    title string `json:"title"`
    author string `json:"author"`
}

所以当我从 postman 发送 post 请求时遇到这样的错误,尝试了很多方法来解决,但没有成功。任何帮助都会很棒。 tia

2020/05/25 10:54:50 [Recovery] 2020/05/25 - 10:54:50 panic recovered:
POST /createBook HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Encoding: gzip, deflate, br
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 48
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0


runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:513 (0x102bd98)
        gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))

[GIN] 2020/05/25-10:54:50|500|2.968348ms|::1|POST "/createBook"

解决方案


您的 db 变量没有为处理程序正确设置

gin.context 中设置 db

func initializeroutes(db *gorm.db) {
    router := gin.default()
    // provide db variable to controllers
    router.use(func(c *gin.context) {
        c.set("db", db)
        c.next()
    })
    ...
}

从主程序发送数据库

mappings.initializeroutes(db)

并从上下文中获取以在处理程序中使用

func Create(c *gin.Context) {
    db := c.MustGet("db").(*gorm.DB)
    ...
}

演示 here 中的工作代码

理论要掌握,实操不能落!以上关于《运行时错误:GORM 在处理 POST 请求时取消了无效的内存地址或 nil 指针》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>