//main.gopackage mainimport ( "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.DBfunc 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.gopackage Mappingsimport ( "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.gopackage Controllersimport ( "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.gopackage Modelsimport "github.com/jinzhu/gorm"type BookModel struct { gorm.Model Title string `json:"title"` Author string `json:"author"`}因此,當(dāng)我從 Postman 發(fā)送 POST 請(qǐng)求時(shí),收到這樣的錯(cuò)誤嘗試解決了很多方法,但沒(méi)有奏效。任何幫助都會(huì)很棒。TIA2020/05/25 10:54:50 [Recovery] 2020/05/25 - 10:54:50 panic recovered:POST /createBook HTTP/1.1Host: localhost:8080Accept: */*Accept-Encoding: gzip, deflate, brCache-Control: no-cacheConnection: keep-aliveContent-Length: 48Content-Type: application/jsonUser-Agent: PostmanRuntime/7.25.0
1 回答

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
您db的變量沒(méi)有為處理程序正確設(shè)置
設(shè)置db在gin.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 發(fā)送 db
Mappings.InitializeRoutes(db)
并從上下文中獲取在處理程序中使用
func Create(c *gin.Context) {
db := c.MustGet("db").(*gorm.DB)
...
}
操場(chǎng)上的工作代碼在這里
- 1 回答
- 0 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)
0/150
提交
取消