0

I am using Go fiber's body parser to parse the request body. I have the following struct

type SignInCredentials struct {
    Email    string
    Password []byte
}

Where I have a Password as a slice of bytes. When I try to parse the body like so

func SignUp(db *database.Database) fiber.Handler {
    return func(c *fiber.Ctx) error {

        cred := new(model.SignUpCredentials)

        if err := c.BodyParser(cred); err != nil {
            return SendParsingError(c)
        }

I get a schema error

schema: error converting value for index 0 of \"Password\

because the type of the form data password doesn't match the []byte type. I looked at their examples and I noticed that in the documentation they use a string to store the password. But I am set on storing it as a slice of bytes. How can I do this?

// Field names should start with an uppercase letter
type Person struct {
    Name string `json:"name" xml:"name" form:"name"`
    Pass string `json:"pass" xml:"pass" form:"pass"`
}

app.Post("/", func(c *fiber.Ctx) error {
        p := new(Person)

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

        log.Println(p.Name) // john
        log.Println(p.Pass) // doe

        // ...
})
anonymous-dev
  • 2,897
  • 9
  • 48
  • 112

1 Answers1

1

It is transmitted as a string, not []byte. You need to parse it as a string first, then you can transform it into the structure you want:

func SignUp(db *database.Database) fiber.Handler {
    return func(c *fiber.Ctx) error {
        // an anonymous struct to parse the body
        body := struct{
            Email string
            Password string
        }{}
        if err := c.BodyParser(body); err != nil {
            return SendParsingError(c)
        }

        cred := SignInCredentials{
            Email:    body.Email,
            Password: []byte(body.Password),
        }
TehSphinX
  • 6,536
  • 1
  • 24
  • 34
  • Is there a way or would it be recommended to transmit it as a array of bytes? – anonymous-dev Dec 10 '20 at 13:06
  • It is a post form, right? That gets url encoded, so: No. Same if the body is json. Json does not have an option for a byte array to be transmitted. – TehSphinX Dec 10 '20 at 13:16