In Go, we can use the Gin framework to handle HTTP requests and bind data to custom request structures. To receive both JSON data and an image in a single multipart/form-data request, we can define the following request handler:
func UpdateProfile(c *gin.Context) { type request struct { Avatar *multipart.FileHeader `form:"avatar" binding:"required"` User struct { Username string `json:"username" binding:"required,min=4,max=20"` Description string `json:"description" binding:"required,max=100"` } `form:"user" binding:"required"` } var updateRequest request // Bind the request data to the request structure if err := c.ShouldBindWith(&updateRequest, binding.FormMultipart); err != nil { // Return an appropriate error response _ = c.AbortWithError(http.StatusBadRequest, err) return } // Handle the image // ... // Handle the JSON data // ... }
To send a request with both JSON data and an image, use a multipart/form-data content type. The request body should be structured as follows:
--boundary Content-Disposition: form-data; name="avatar"; filename="profile.jpg" Content-Type: image/jpeg //... image data --boundary Content-Disposition: form-data; name="user" Content-Type: application/json { "username": "username", "description": "description" } --boundary--
The above is the detailed content of How to Handle JSON and Image Upload Simultaneously in a Go Gin Framework?. For more information, please follow other related articles on the PHP Chinese website!