gpt4 book ai didi

go - 运行时错误 : invalid memory address or nil pointer dereference (golang-gorm) for POST Request

转载 作者:行者123 更新时间:2023-12-01 22:22:41 24 4
gpt4 key购买 nike

//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未为处理程序正确设置变量

设置 dbgin.Context

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()
})
...
}

从 main 发送 db
Mappings.InitializeRoutes(db)

并从上下文中获取在处理程序中使用
func Create(c *gin.Context) {
db := c.MustGet("db").(*gorm.DB)
...
}

操场上的工作代码 here

关于go - 运行时错误 : invalid memory address or nil pointer dereference (golang-gorm) for POST Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62005322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com