Created
June 6, 2024 13:44
-
-
Save elliottminns/26283ef381f367bd3c5c10371999b3d3 to your computer and use it in GitHub Desktop.
Generic Response Handling in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"log" | |
) | |
type Response struct { | |
Status string `json:"status"` | |
Data json.RawMessage `json:"data"` | |
} | |
type NetInfo struct { | |
CurrentBlock uint `json:"current_block"` | |
HighestBlock uint `json:"highest_block"` | |
NetworkID string `json:"network_id"` | |
} | |
func main() { | |
var res Response | |
if err := json.Unmarshal([]byte(data), &res); err != nil { | |
log.Fatalln("failed to unmarshal response:", err) | |
} | |
var netInfo NetInfo | |
if err := json.Unmarshal(res.Data, &netInfo); err != nil { | |
log.Fatalln("failed to unmarshal data:", err) | |
} | |
log.Println(netInfo.CurrentBlock) | |
} | |
const data = ` | |
{ | |
"status": "success", | |
"data": { | |
"listening": true, | |
"syncing": false, | |
"mining": false, | |
"peer_count": 8, | |
"current_block": 40035, | |
"highest_block": 40035, | |
"network_id": "mainnet" | |
} | |
} | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment