From b58a450c6dd48170daa7ad51899c25851934b257 Mon Sep 17 00:00:00 2001 From: Brandon Berhent Date: Mon, 26 Feb 2024 12:17:47 -0500 Subject: [PATCH] Fix unmarshal error --- models/nano_rpc.go | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/models/nano_rpc.go b/models/nano_rpc.go index b29f0e7..26801f5 100644 --- a/models/nano_rpc.go +++ b/models/nano_rpc.go @@ -1,5 +1,10 @@ package models +import ( + "encoding/json" + "errors" +) + // Requests type AccountInfoAction struct { Action string `json:"action"` @@ -30,7 +35,38 @@ type WorkGenerate struct { // Responses type ReceivableResponse struct { - Blocks map[string]string `json:"blocks"` + Blocks map[string]string +} + +// UnmarshalJSON is a custom unmarshaler for ReceivableResponse, +// handling the case where "blocks" can be a JSON object or an empty string. +func (r *ReceivableResponse) UnmarshalJSON(data []byte) error { + // First, try unmarshaling into the expected format. + var obj struct { + Blocks map[string]string `json:"blocks"` + } + err := json.Unmarshal(data, &obj) + if err == nil { + r.Blocks = obj.Blocks + return nil + } + + // If the first attempt fails, check if "blocks" is an empty string. + var altObj struct { + Blocks json.RawMessage `json:"blocks"` + } + err = json.Unmarshal(data, &altObj) + if err != nil { + return err + } + + // Check if blocks is an empty string. + if string(altObj.Blocks) == `""` { + r.Blocks = make(map[string]string) // Initialize Blocks as an empty map. + return nil + } + + return errors.New("unexpected format for blocks") } type BlockContents struct {