Problem:
Capturing the raw JSON body of a POST request as a string or interface to store in a JSONB database field.
Solution:
1. Retrieve the Request Body:
<code class="go">bodyBytes, _ := ioutil.ReadAll(context.Request().Body)</code>
2. Restore the Request Body:
Since the http.Response.Body is a buffer that cannot be read multiple times, restore it before any further processing:
<code class="go">context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))</code>
3. Decode the JSON:
Now, you can use the body bytes to decode the JSON into a string or interface:
<code class="go">var rawJSON string if err := json.Unmarshal(bodyBytes, &rawJSON); err != nil { // Handle error }</code>
The above is the detailed content of How to Extract JSON Data from a Request Body in Go?. For more information, please follow other related articles on the PHP Chinese website!