echo: http: 恐慌服务:45724: 运行时错误: 无效的内存地址或 nil 指针取消引用 goroutine 10 :
admin 阅读:121 2024-03-16

我尝试使用 go/echo 和 postgres 使用原始 sql 创建一个 REST API,但我无法使其工作,不知道问题是什么
控制台打印标题中的文本
食谱.go
func CreateRecipe(recipe *Recipe) error {
query := `INSERT INTO recipes(title, ingredients, description) VALUES($1, $2, $3);`
_, err := db.Exec(query, recipe.Title, recipe.Ingredients, recipe.Description)
if err != nil {
return err
}
return nil
}路由器.go
func PostRecipe(c echo.Context) error {
recipe := new(models.Recipe)
if err := c.Bind(recipe); err != nil {
return err
}
err := models.CreateRecipe(recipe)
if err != nil {
return err
}
return c.JSON(http.StatusCreated, recipe)
}服务器.go
func Start() {
//Setting up echo
e := echo.New()
e.Use(middleware.CORS())
e.GET("/api/recipes", Home)
e.POST("/api/recipes", PostRecipe)
e.Logger.Fatal(e.Start(":4000"))
}正确答案
我以错误的方式初始化数据库,我使用了
db, err := sql.Open("postgres", dbinfo)而不是
db, err = sql.Open("postgres", dbinfo)声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



