Home > Net >  convert rest api POST request from json to form-data in golang gofiber framework
convert rest api POST request from json to form-data in golang gofiber framework

Time:12-31

I have the following code that works for JSON in the body of the POST request but i now want to convert this to using form-data in the body of the request

Here is what i have

func Signin(c *fiber.Ctx) error {
    var data map[string]string

    if err := c.BodyParser(&data); err != nil {
        return err
    }

    var user models.User

    findUser := database.DB.Where("email = ?", data.email).First(&user)

    token, err := middlewares.GenerateJWT(user.Email)

    if err != nil {
        c.Status(fiber.StatusBadRequest)
        return c.JSON(fiber.Map{
            "message": "Invalid credentials",
        })  
    }

    cookie := fiber.Cookie{
        Name: "access_token",
        Value: token,
        Expires: time.Now().Add(time.Hour * 24),
        HTTPOnly: true,
        Secure:   true,
    }

    c.Cookie(&cookie)

    return c.JSON(fiber.Map{
        "access_token": token,
        "token_type": "bearer",
    })

}

above works fine for raw JSON body but i want to change to form-data body

I have tried many things including this but to no avail

func Signin(c *fiber.Ctx) error {

    type SigninData struct {
        email  string `json:"email" xml:"email" form:"email"`
        password string `json:"password" xml:"password" form:"password"`
    }

    data := new(SigninData)

    if err := c.BodyParser(&data); err != nil {
        return err
    }

    var user models.User

    findUser := database.DB.Where("email = ?", data.email).First(&user)

    token, err := middlewares.GenerateJWT(user.Email)

    if err != nil {
        c.Status(fiber.StatusBadRequest)
        return c.JSON(fiber.Map{
            "message": "Invalid credentials",
        })  
    }


    cookie := fiber.Cookie{
        Name: "access_token",
        Value: token,
        Expires: time.Now().Add(time.Hour * 24),
        HTTPOnly: true,
        Secure:   true,
    }

    c.Cookie(&cookie)

    return c.JSON(fiber.Map{
        "access_token": token,
        "token_type": "bearer",
    })

}

but i get the following error

schema: interface must be a pointer to struct

what am i missing that i need to fix to get this to accept form-data?

CodePudding user response:

The method BodyParser expects a pointer to a struct as an argument, but your code is trying to pass it a pointer to a pointer to a struct. Please initialize the struct this way:

data := SigninData{}

Also, try to make the fields of the SigninData struct public:

type SigninData struct {
    Email  string `json:"email" xml:"email" form:"email"`
    Password string `json:"password" xml:"password" form:"password"`
}
  • Related