I have a struct defined as follows
type WallpaperType int
// ...
type WallpaperInfo struct {
WallpaperType WallpaperType `json:"type"`
HelpMsg string `json:"help"`
Path string `json:"path"`
ImageColor color.RGBA `json:"imageColor"`
}
Printing such a struct using
winfo := &WallpaperInfo{...}
log.Println(winfo)
log.Printf("%+v\n", winfo)
Gives something like this
&{Slideshow Wallpaper is a slideshow D:\Images\Wallpapers\autumn-autumn-leaves-blur-close-up-589840.jpg {219 77 66 167}}
&{WallpaperType:Slideshow HelpMsg:Wallpaper is a slideshow Path:D:\Images\Wallpapers\autumn-autumn-leaves-blur-close-up-589840.jpg ImageColor:{R:219 G:77 B:66 A:167}}
I'd like to print it as a JSON so I've implemented the String
method for the struct as follows
func (w WallpaperInfo) String() string {
bytes, err := json.Marshal(w)
if err != nil {
return "" // ???
// this will call the method recursively
// return fmt.Sprintf("%+v\n", w)
}
return string(bytes)
}
In case there's an error in the String()
method,
I'd like to print the original &{WallpaperType:Slideshow HelpMsg:Wallpaper is a slideshow Path:D:\Images\Wallpapers\autumn-autumn-leaves-blur-close-up-589840.jpg ImageColor:{R:219 G:77 B:66 A:167}}
I've tried returning fmt.Sprintf("%+v\n", w)
but it does recursive call to the same function.
Any way I can return the original struct format? Because if json fails I don't know a way to print it differently.