我正在尝试使用 gin 将 base64 图像发送到用 go 编写的服务器。我创建了一个带有绑定和 json 标签的结构来表示请求正文,如下所示:
type createcompanyrequestbody struct { name string `json:"name" binding:"required"` size string `json:"size" binding:"required"` logo string `json:"logo" binding:"required,base64|base64url|base64rawurl"` }
当尝试使用 gin 的 shouldbindjson
解码正文时,我收到 logo
字段的错误。不过,我确实使用在线工具(https://onlinepngtools.com/convert-base64-to-png)验证了解码的对象确实在 logo
字段中包含有效的 base64 字符串。
解码json的代码如下:
var body createCompanyRequestBody if err := ctx.ShouldBindJSON(&body); err != nil { ctx.Status(http.StatusBadRequest) // Will always hit this }
我以前没有用过杜松子酒,所以我确信我有疏忽,但我似乎不明白是什么。如何更改结构以允许按预期提供的 base64 变体?
如果您将图像作为数据 URI 而不仅仅是发送裸 base64
字符串,那么你应该使用 datauri
验证器而不是 base64|base64URL|base64RawURL
。