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

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

Barbara Streisand
Release: 2024-10-31 16:26:49
Original
820 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template