You need a simple way to format the output of your marshaled JSON output! Yes, Golang made it easy for us by using MarshalIndent function from JSON package:
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
Simple code example:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Response struct {
Code int
Data Data
}
type Data struct {
Urls []string
Count int
}
func main() {
res := Response{
Code: http.StatusOK,
Data: Data{
Urls: []string{
"https://www.code-paste.com/",
"https://www.code-paste.com/category/golang/",
},
Count: 2,
},
}
resBytes, err := json.MarshalIndent(res, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(resBytes))
}
Pingback: Print Struct as String in Golang – Code Paste