Home  >  Article  >  Backend Development  >  echo: http: panic-service:45724: runtime error: invalid memory address or nil pointer dereferenced goroutine 10:

echo: http: panic-service:45724: runtime error: invalid memory address or nil pointer dereferenced goroutine 10:

WBOY
WBOYforward
2024-02-05 21:51:03646browse

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)

The above is the detailed content of echo: http: panic-service:45724: runtime error: invalid memory address or nil pointer dereferenced goroutine 10:. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete