echo:http:panic serving [::1]:45724:runtime error:invalid memory address or nil pointer dereference goroutine 10 [running]:

jchrr9hc  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(136)

我试图创建一个休息API与去/回声和postgres与原始SQL,但我不能使它工作,不知道什么问题
控制台打印标题中的文本
recipe.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 
}

字符串
router.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)
}


server.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"))
}


x1c 0d1x的数据

k2arahey

k2arahey1#

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

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

字符串
而不是

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

相关问题