Skip to content

Instantly share code, notes, and snippets.

@nictuku
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nictuku/d45adca175ffbbc45f73 to your computer and use it in GitHub Desktop.
Save nictuku/d45adca175ffbbc45f73 to your computer and use it in GitHub Desktop.
net.IP Marshalling in JSON and YAML
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