Search code examples
gogo-fiber

How do I parse the password as a byte array with fiber


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

        // ...
})

Solution

  • 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),
            }