2

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?

Bram Vanbilsen
  • 5,763
  • 12
  • 51
  • 84
  • 2
    That’s it! I thought a base64 url and datauri were the same thing. If you’d like and have the time. Can you make your comment an answer so I can mark it as the correct answer? – Bram Vanbilsen Aug 08 '23 at 10:33

1 Answers1

2

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.

mkopriva
  • 35,176
  • 4
  • 57
  • 71