Skip to content

Instantly share code, notes, and snippets.

@elliottminns
Created June 6, 2024 13:47
Show Gist options
  • Save elliottminns/94870f3f0f4071dc41724182c907fdad to your computer and use it in GitHub Desktop.
Save elliottminns/94870f3f0f4071dc41724182c907fdad to your computer and use it in GitHub Desktop.
Generic JSON Unmarshaling in Go
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