Created
June 6, 2024 13:47
-
-
Save elliottminns/94870f3f0f4071dc41724182c907fdad to your computer and use it in GitHub Desktop.
Generic JSON Unmarshaling 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[T any] struct { | |
Status string `json:"status"` | |
Data T `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[NetInfo] | |
if err := json.Unmarshal([]byte(data), &res); err != nil { | |
log.Fatalln("failed to unmarshal response:", err) | |
} | |
log.Println(res.Data.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