diff options
| author | Jeff Carr <[email protected]> | 2024-10-22 16:33:36 -0500 |
|---|---|---|
| committer | Jeff Carr <[email protected]> | 2024-10-22 16:33:36 -0500 |
| commit | f2040886198b8f4a25ce1a9f65585097b299f9fa (patch) | |
| tree | ab7bd4f70c521c97ba766c96a31af5284baf76f1 /storageinfo.go | |
| parent | 8f1544654b1d5534d9d27437237eca8d8e6dfa96 (diff) | |
attempt at human readable message in JSON output
Signed-off-by: Jeff Carr <[email protected]>
Diffstat (limited to 'storageinfo.go')
| -rw-r--r-- | storageinfo.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/storageinfo.go b/storageinfo.go new file mode 100644 index 0000000..9df42c2 --- /dev/null +++ b/storageinfo.go @@ -0,0 +1,53 @@ +package virtbuf + +import ( + "encoding/json" + "fmt" + "strconv" +) + +type StorageInfo struct { + Capacity int64 +} + +// MarshalJSON custom marshals the StorageInfo struct to JSON +func (s StorageInfo) MarshalJSON() ([]byte, error) { + capacityStr := fmt.Sprintf("%d GB", s.Capacity) + return json.Marshal(map[string]string{ + "capacity": capacityStr, + }) +} + +// UnmarshalJSON custom unmarshals JSON into the StorageInfo struct +func (s *StorageInfo) UnmarshalJSON(data []byte) error { + var raw map[string]string + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + if capacityStr, ok := raw["capacity"]; ok { + capacityStr = capacityStr[:len(capacityStr)-3] // Remove the " GB" suffix + capacity, err := strconv.ParseInt(capacityStr, 10, 64) + if err != nil { + return err + } + s.Capacity = capacity + } + + return nil +} + +/* +func main() { + info := StorageInfo{Capacity: 64} + + // Marshaling to JSON + jsonData, _ := json.Marshal(info) + fmt.Println(string(jsonData)) // Output: {"capacity":"64 GB"} + + // Unmarshaling back to Go struct + var newInfo StorageInfo + _ = json.Unmarshal(jsonData, &newInfo) + fmt.Println(newInfo.Capacity) // Output: 64 +} +*/ |
