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

WBOY
Release: 2024-02-05 21:51:03
forward
650 people have browsed it

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 
}
Copy after login

路由器.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)
}
Copy after login

服务器.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"))
}
Copy after login

正确答案


我以错误的方式初始化数据库,我使用了

db, err := sql.Open("postgres", dbinfo)
Copy after login

而不是

db, err = sql.Open("postgres", dbinfo)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template