-1

I want to do something ordinary

payload

{
    "first_name": "name",
    "last_name": "last name",
    "email": "email",
    "password": "123"
}

struct

type Register struct {
    FirstName string `json:"first_name" validate:"required" min=1 max=255`
    LastName  string `json:"last_name" validate:"required" min=1 max=255`
    Email     string `json:"email" validate:"required,email"`
    Password  string `json:"password" validate:"required,min=4,max=45"`
}

run code

register := new(Register)
c.BodyParser(register)

output

{
    "first_name": "",
    "last_name": "",
    "email": "email",
    "password": "123"
}

But it fails because payload is snake case. if it was upperCase it wouldn't be a problem. It's weird because the best practice is to be like this and it doesn't work.

  • 2
    Your struct tags for FirstName and LastName don't follow [convention](https://pkg.go.dev/reflect#StructTag), the min/max are outside of the validate double quotes. Voting to close because of typo. – mkopriva Nov 11 '22 at 21:57
  • Thanks for the notice. I fixed it correctly but BodyParser still doesn't work. – Muhammed Alper Uslu Nov 13 '22 at 17:18
  • 1
    You are sending the data as `form-data` but the fields in Go use `json` struct tag keys. Change `json:"..."` to `form:"..."`, or send the data as JSON instead of form-data. – mkopriva Nov 13 '22 at 17:34
  • Also, do NOT post images of text. Copy paste the text and insert it as is into the question, for code text add syntax highlighting by wrapping the text in tripple backquotes, etc. But do NOT post images of text (sometimes images make sense, but not when you're sharing text). – mkopriva Nov 13 '22 at 17:37
  • 1
    Thank you very much for the help. I never guessed that the error would be in the payload. – Muhammed Alper Uslu Nov 13 '22 at 17:50

1 Answers1

0

this code run without error(s) and return all struct's field(s):

package main

import (
    "github.com/gofiber/fiber/v2"
)

type Register struct {
    FirstName string `json:"first_name" validate:"required" min=1 max=255`
    LastName  string `json:"last_name" validate:"required" min=1 max=255`
    Email     string `json:"email" validate:"required,email"`
    Password  string `json:"password" validate:"required,min=4,max=45"`
}

func main() {
    app := fiber.New()
    app.Get("/", func(c *fiber.Ctx) error {
        register := new(Register)
        if err := c.BodyParser(register); err != nil {
            return err
        }
        return c.JSON(register)
    })
    app.Listen(":5000")
}

output:

{
    "first_name": "first name ",
    "last_name": "last name",
    "email": "email",
    "password": "123"
}

official document: see here and also: json output with fiber