如何在Go语言中将结构体打印到HTTP响应中

huangapple go评论85阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年10月21日 09:11:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/33249338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定