英文:
golang: How to remove spaces and line breaks in the request body
问题
我使用gin框架编写了一个使用golang编写的Web服务,用于接收JSON格式的参数。我发送的请求如下所示:
curl --location 'http://foo.bar/test' \
--header 'Content-Type: application/json' \
--data'{
"a": "1",
"b": "2"
}'
现在,我添加了一个中间件,将所有请求参数打印到日志文件中,该中间件在控制器的上一层运行。请注意,在中间件层无法确定参数的具体类型。当我读取请求体并打印日志时,得到以下结果:
[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"
}
我希望得到以下结果:
[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 wrote a web service (golang) using the gin framework to receive parameters in json body format. I make a request like this:
curl --location 'http://foo.bar/test' \
--header 'Content-Type: application/json' \
--data'{
"a": "1",
"b": "2"
}'
Now, I added a middleware that prints all request parameters to a log file, which runs one layer above the controller. Note that the specific type of the parameter is not known at the middleware layer. When I read the body and print the log, I get the following result:
[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 expect 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"}
I would like to ask: How to remove the spaces and line breaks in the body? Note that the body parameter in this example is relatively simple, but the actual situation will be more complicated. Thanks.
答案1
得分: 1
你可以使用以下方法来替换请求体中的空格和换行符。
使用strings.ReplaceAll()函数
requestBodyBytes, err := c.GetRawData()
if err != nil {
// 处理错误
}
body := string(requestBodyBytes)
body = strings.ReplaceAll(body, "\n", "")
body = strings.ReplaceAll(body, " ", "")
fmt.Printf("body=%v \n", body)
当你需要在将请求体传递给控制器之前删除空格和换行符时,可以使用这种方法。
使用Marshaling
requestBodyBytes, err := c.GetRawData()
if err != nil {
// 处理错误
}
var data interface{}
json.Unmarshal(requestBodyBytes, &data)
marshalledBytes, err := json.Marshal(data)
if err != nil {
// 处理错误
}
fmt.Printf("body=%v \n", string(marshalledBytes))
当你只需要删除空格和换行符以进行日志记录时,可以使用这种方法。
英文:
You can Replace spaces and line breaks in the body by using the following approaches.
With 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 may be used when you need to change the request body by deleting spaces and lines before reaching it to the controller.
With Marshaling
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))
When you simply need to delete spaces and lines for logging, use this.
答案2
得分: 1
你可以这样去除空格和换行符:
package main
import (
"fmt"
)
func main() {
data := []byte(`{
"a": "1",
"b": "2"
}`)
i := 0
for _, b := range data {
switch b {
case ' ', '\n', '\r':
default:
data[i] = b
i++
}
}
data = data[:i]
fmt.Printf("%s\n", data)
}
注意:
-
它重用了当前切片的空间。
-
不要像这样记录请求体。原因如下:
- 记录日志的目的是为了查看客户端发送的确切内容。如果内容被修改,就不可信了。
- 在中间件中读取请求体会影响之后执行的处理程序。因为请求体已经被读取,后续的读取大部分时间会得到
EOF
。当然,你可以将请求体存储在其他地方并将其传递给其他处理程序,但这会浪费内存。
英文:
You can remove spaces and line breaks like this:
package main
import (
"fmt"
)
func main() {
data := []byte(`{
"a": "1",
"b": "2"
}`)
i := 0
for _, b := range data {
switch b {
case ' ', '\n', '\r':
default:
data[i] = b
i++
}
}
data = data[:i]
fmt.Printf("%s\n", data)
}
Notes:
-
It reuses the space of the current slice.
-
Don't log request body like this. Reasons:
- The point of logging is to see what exactly is sent from the client. If the content is modified, it's not trust-able any more.
- Reading the request body in a middleware will affect the handlers executed afterward. Because the body has already been read, subsequent reads will get
EOF
most of the time. Of course you can store the body somewhere else and pass it to other handlers, but it's a waste of memory.
答案3
得分: 0
// 从字符串中删除换行符、制表符和空格字符
body = strings.ReplaceAll(body, "\n", "")
body = strings.ReplaceAll(body, " ", "")
body = strings.ReplaceAll(body, "\t", "")
英文:
// Remove new line, tab, and space characters from a string
body = strings.ReplaceAll(body, "\n", "")
body = strings.ReplaceAll(body, " ", "")
body = strings.ReplaceAll(body, "\t", "")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论