Last active
August 29, 2015 14:06
-
-
Save nictuku/d45adca175ffbbc45f73 to your computer and use it in GitHub Desktop.
net.IP Marshalling in JSON and YAML
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" | |
"fmt" | |
"net" | |
"github.com/GoogleCloudPlatform/kubernetes/Godeps/_workspace/src/gopkg.in/v1/yaml" | |
) | |
type T struct { | |
IP net.IP | |
Want []string // 0 == json, 1 == yaml. | |
} | |
type encoder struct { | |
f func(interface{}) ([]byte, error) | |
d string | |
} | |
func main() { | |
var encs = []encoder{ | |
{json.Marshal, "json"}, | |
{yaml.Marshal, "yaml"}, | |
} | |
for _, t := range []T{ | |
{net.IP{}, []string{`""`, `""`}}, | |
{net.IPv4(127, 0, 0, 1), []string{`"127.0.0.1"`, `"127.0.0.1"`}}, | |
} { | |
for i, s := range encs { | |
got, err := s.f(t.IP) | |
if err != nil { | |
fmt.Println(s.d, err) | |
} else if string(got) != t.Want[i] { | |
fmt.Printf("%v encoding failed: wanted %q, got %q\n", s.d, t.Want[i], string(got)) | |
} | |
} | |
} | |
} | |
// Result: | |
// yaml encoding failed: wanted "\"\"", got "[]\n" | |
// yaml encoding failed: wanted "\"127.0.0.1\"", got "- 0\n- 0\n- 0\n- 0\n- 0\n- 0\n- 0\n- 0\n- 0\n- 0\n- 255\n- 255\n- 127\n- 0\n- 0\n- 1\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment