Reading JSON from Request Body in Go
In Go, obtaining the raw JSON body of a POST request can be challenging for beginners. This is because http.Response.Body buffers responses, preventing subsequent readings.
However, a workaround exists to capture JSON bodies without relying on predetermined data structures. To achieve this:
<code class="go">// Capture the body bytes bodyBytes, _ := ioutil.ReadAll(context.Request().Body) // Restore the response body context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // Decode the JSON var v interface{} err := json.NewDecoder(context.Request().Body).Decode(&v) if err != nil { return result, err }</code>
This approach preserves the original body for subsequent readings.
To further demonstrate, here's an example using Echo framework:
<code class="go">func myHandler(c echo.Context) error { // Capture the body bytes bodyBytes, _ := ioutil.ReadAll(c.Request().Body) // Restore the response body c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // Decode the JSON var payload map[string]interface{} err := json.NewDecoder(c.Request().Body).Decode(&payload) if err != nil { return c.JSON(http.StatusBadRequest, "Invalid JSON provided") } // Use the decoded payload return c.JSON(http.StatusOK, payload) }</code>
This solution enables you to capture the raw JSON body without any imposed structure, making it ideal for situations where you need to handle arbitrary JSON data.
The above is the detailed content of How to Read JSON from Request Body in Go Without Defined Data Structures?. For more information, please follow other related articles on the PHP Chinese website!