Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

illegal base64 data error message

Tags:

go

I'm building an API that accepts JSON data POSTed to it.

I have the following user struct and recently I changed the password datatype to []byte from string so that it "plays nicely" with the bcrypt package.

type User struct {
    Id           string             `json:"id,omitempty"`
    Email        string             `json:"email,omitempty"`
    Username     string             `json:"username,omitempty"`
    Password     []byte             `json:"password,omitempty"`
    Name         string             `json:"name,omitempty"`
}

However, I'm now getting an internal error returned in the JSON response illegal base64 data at input byte 4 when a user is POSTed with a password of 5 or more characters to the API. There are no issues if the password is 4 or less characters.

I've pinpointed the error to this block of code:

err := json.NewDecoder(req.Body).Decode(User)
if err != nil && err != io.EOF {
    return err
}

Any ideas on a fix?

like image 714
tommyd456 Avatar asked Jul 16 '15 08:07

tommyd456


1 Answers

The problem lies in using []byte instead of string for password. This is because the encoding/json package will expect a base64 encoded string when decoding to []byte.

The documentation for encoding/json says:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object.

So, just change it to string:

Password string `json:"password,omitempty"`

When you want to use it with bcrypt, then you just convert the string to []byte:

[]byte(user.Password)
like image 89
ANisus Avatar answered Oct 11 '22 13:10

ANisus