英文:
How to print a Struct in the Http Response in go lang
问题
我正在使用POSTMAN处理Go语言中的POST请求。我希望以结构体格式(JSON数据的结构体)显示响应。
对于显示普通字符串,我使用rw.Write([]byte(fmt.Sprintf("Hello, %s!", t.Name)))
。
要在响应正文中显示结构体,你应该怎么做?(使用rw.write方法)
fmt.Printf("%+v\n", m)
输出为{ID:1 Name:John Smith Address:123 Main St City:San Francisco State:CA Zip:94113 Coordinate:{Latitude:37.7917618 Longitude:-122.3943405}}
。
这正是我想要在Postman响应中显示的内容。
提前感谢:)
英文:
I am using POSTMAN for handling POST requests in go lang. I wish to display the response in the struct format(A struct of json data).
For displaying a normal string, I am using rw.Write([]byte(fmt.Sprintf("Hello, %s!", t.Name)))
What should I do to display the Struct in response body?(using rw.write method)
fmt.Printf("%+v\n", m)
outputs to {ID:1 Name:John Smith Address:123 Main St City:San Francisco State:CA Zip:94113 Coordinate:{Latitude:37.7917618 Longitude:-122.3943405}}
This is what I want to display exactly in the Postman response .
Thanks in advance:)
答案1
得分: 1
你以某种方式间接回答了你的问题,只是不知道而已。
你提到了这个例子,它具有你正在寻找的功能。fmt.Sprintf
返回一个格式化的字符串,而不是你已经使用的打印到标准输出的方式,即fmt.Printf
。
所以,你可以使用类似下面这样使用fmt.Sprintf
的方式,而不是fmt.Printf("%+v\n", m)
:
structString := fmt.Sprintf("%+v\n", m)
rw.Write([]byte(structString))
另一个解决方案是像@JimB建议的那样直接使用fmt.Fprintf
,它以io.Writer
作为第一个参数,之后是格式化字符串。
fmt.Fprintf(rw, "%+v\n", *m)
英文:
Somehow you have indirectly answered your question but just didn't know about it.
You mentioned this example, which has the function you're looking for. fmt.Sprintf
returns a formatted string instead of the one you were already using that prints to standard out, fmt.Printf
.
> rw.Write([]byte(fmt.Sprintf("Hello, %s!", t.Name)))
So instead of fmt.Printf("%+v\n", m)
, you can use something like the below that uses fmt.Sprintf
:
structString := fmt.Sprintf("%+v\n", m)
rw.Write([]byte(structString))
The other solution as @JimB suggested is to use fmt.Fprintf
directly taking an io.Writer
as its first parameter and a format string afterwards.
fmt.Fprintf(rw, "%+v\n", *m)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论