Last active
January 17, 2018 01:54
-
-
Save flashvoid/f9238aad48905a218d4476e45e796acd to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"encoding/json" | |
"math/big" | |
"os" | |
) | |
type dc struct { | |
IP IP | |
Name string | |
} | |
type IP struct { | |
big.Int | |
} | |
func (ip *IP) MarshalJSON() ([]byte, error) { | |
res := fmt.Sprintf("%x", ip) | |
fmt.Println("Marshaling into ", res) | |
return json.Marshal(res) | |
} | |
func (ip *IP) UnmarshalJSON(b []byte) error { | |
var val string | |
err := json.Unmarshal(b, &val) | |
if err != nil { | |
panic(err) | |
} | |
ip.SetString(val, 16) | |
return nil | |
} | |
func main() { | |
d := new(IP) | |
d.SetString("fec0dead00000000", 16) | |
DC := new(dc) | |
DC.Name = "Test" | |
DC.IP = *d | |
j, err := json.Marshal(DC) | |
if err != nil { | |
fmt.Println("Error: ", err) | |
} | |
fmt.Printf("Hello, playground: %x \n", d) | |
os.Stdout.Write(j) | |
var NewDc dc | |
err = json.Unmarshal(j, &NewDc) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("\n\n Unmarshalled as: %v, %s", NewDc, NewDc.IP.Int.Text(16)) | |
} | |
// https://play.golang.org/p/dyHG0E_yrd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment