Home  >  Article  >  Backend Development  >  How to Extract JSON Data from a Request Body in Go?

How to Extract JSON Data from a Request Body in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 16:26:49703browse

How to Extract JSON Data from a Request Body in Go?

Getting the JSON from the Request Body in Go

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn