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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With