-2

im trying to create an rest api with go/echo and postgres with raw sql but i cant make it work, no idea whats the problem

the console prints the text in the title

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

enter image description here

12
  • How did you initialize the db? Did you initialize the db? Commented Oct 24, 2023 at 17:52
  • yes i did, thats not the problem, i just didnt show on the code, also i have the type of the json called Recipe that i didnt show it Commented Oct 24, 2023 at 17:56
  • Show the full stack trace panic prints, that should point where the problem is Commented Oct 24, 2023 at 17:58
  • just to confirm that i send the image Commented Oct 24, 2023 at 18:03
  • 1
    It is coming from the Exec call. It is likely that db is not initialized Commented Oct 24, 2023 at 18:06

1 Answer 1

1

I initialize the db in the wrong way, I used

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

instead of

db, err = sql.Open("postgres", dbinfo)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.