Below is the model for my code.
package models
type Goal struct {
Id int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}
When I import models package in controllers and want to use so it give me an errror.
package controllers
import (
"strconv"
"github.com/gofiber/fiber/v2"
"github.com/RohitKuwar/go_fiber/models" //error:"github.com/RohitKuwar/go_fiber/models" imported but not used
)
var goals = []Goal{ //error:undeclared name: Goal
{
Id: 1,
Title: "Read about Promises",
Status: "completed",
},
{
Id: 2,
Title: "Read about Closures",
Status: "active",
},
}
func GetGoals(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(goals)
}
func CreateGoal(c *fiber.Ctx) error {
type Request struct {
Title string `json:"title"`
Status string `json:"status"`
}
var body Request
err := c.BodyParser(&body)
// if error
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "Cannot parse JSON",
"error": err,
})
}
// create a goal variable
goal := &Goal{ //error:undeclared name: Goal
Id: len(goals) + 1,
Title: body.Title,
Status: body.Status,
}
But when I write models in the controller like below then everything works fine.
import (
"strconv"
"github.com/gofiber/fiber/v2"
)
type Goal struct {
Id int `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
}
var goals = []Goal{
{
Id: 1,
Title: "Read about Promises",
Status: "completed",
},
{
Id: 2,
Title: "Read about Closures",
Status: "active",
},
}
func GetGoals(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(goals)
}
But I do not want to use models code in controllers code. I want to keep the model in the models folder. I want to keep models and controllers in separate folders. I think I am doing something wrong while importing models package in controllers or controllers package in models. I am not understanding how can I do it. Can you guys please help me? Thank you in advance.