Home > Backend Development > Golang > golang: How to remove spaces and newlines in request body

golang: How to remove spaces and newlines in request body

WBOY
Release: 2024-02-06 11:00:04
forward
719 people have browsed it

golang: How to remove spaces and newlines in request body

Question content

I used the gin framework to write a web service (golang) to receive parameters in json body format. I make this request:

curl --location 'http://foo.bar/test' \
--header 'content-type: application/json' \
--data'{
     "a": "1",
     "b": "2"
}'
Copy after login

Now, I've added a middleware that prints all request parameters to a log file, which runs one layer above the controller. Note that the middleware layer does not know the specific types of parameters. When I read the body and print the log, I get the following results:

[2023/06/20 11:44:38 cst] [info] (.../infra/log.info:18) request_in||traceid=xx||spanid=xxx||path=/test||body= {
     "a": "1",
     "b": "2"
}
Copy after login

I expected something like this:

[2023/06/20 11:44:38 CST] [INFO] (/infra/log.Info:18) request_in||traceid=xx||spanid=xxx||path=/test||body={"a ":"1","b":"2"}
Copy after login

Excuse me: How to remove spaces and line breaks in the text? Note that the body parameter in this example is relatively simple, but the actual situation will be more complex. Thanks.


Correct answer


You can use the following method to replace spaces and newlines in the text.

Use strings.replaceall()

requestbodybytes, err := c.getrawdata()
if err != nil {
  // handle this
}

body := string(requestbodybytes)
body = strings.replaceall(body, "\n", "")
body = strings.replaceall(body, " ", "")

fmt.printf("body=%v \n", body)
Copy after login

This method can be used when you need to change the request body by removing spaces and lines before reaching the controller.

Use grouping

requestBodyBytes, err := c.GetRawData()
if err != nil {
  // Handle this
}

var data interface{}
json.Unmarshal(requestBodyBytes, &data)

marshalledBytes, err := json.Marshal(data)
if err != nil {
  // Handle this
}
fmt.Printf("body=%v \n", string(marshalledBytes))
Copy after login

Use this function when you only need to remove spaces and lines for logging.

The above is the detailed content of golang: How to remove spaces and newlines in request body. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template