echo: http: 恐慌服务:45724: 运行时错误: 无效的内存地址或 nil 指针取消引用 goroutine 10 :

echo: http: 恐慌服务:45724: 运行时错误: 无效的内存地址或 nil 指针取消引用 goroutine 10 :

问题内容

我尝试使用 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)

登录后复制

以上就是echo: http: 恐慌服务:45724: 运行时错误: 无效的内存地址或 nil 指针取消引用 goroutine 10 :的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!