I am trying to send a base64 image to my server written in Go using Gin. I created a struct with binding and json tags to represent the request body, it looks as follows:
type createCompanyRequestBody struct {
Name string `json:"name" binding:"required"`
Size string `json:"size" binding:"required"`
Logo string `json:"logo" binding:"required,base64|base64url|base64rawurl"`
}
When trying to decode the body using Gin's ShouldBindJSON
, I get an error for the Logo
field. I did however verify using an online tool (https://onlinepngtools.com/convert-base64-to-png) that the decoded object does include a valid base64 string in the Logo
field.
The code used for decoding the JSON is as follows:
var body createCompanyRequestBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.Status(http.StatusBadRequest) // Will always hit this
}
I haven't used Gin before, so I'm sure there is an oversight on my end, but I can't seem to figure out what. How can I change the struct so that it allows the base64 variants provided as intended?
If you are sending the image as a data URI rather than just a bare base64
string, then you should use the datauri
validator instead of base64|base64URL|base64RawURL
.