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:)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.