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" }'
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" }
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"}
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.
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)
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))
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!