From 982781e599e5289f9e5861c5f580b72df499963c Mon Sep 17 00:00:00 2001 From: Colin Patrick Mccabe Date: Thu, 25 Jun 2015 18:05:27 -0700 Subject: [PATCH] msgpack-translate.go: add program for msgpack translation Signed-off-by: Colin McCabe --- .gitignore | 1 + msgpack-translate.go | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 0 deletions(-) create mode 100644 msgpack-translate.go diff --git a/.gitignore b/.gitignore index f0b2e2e..6d9e56f 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ vimstart show_default_sockopts print-code-points hexconv +msgpack-translate # # Normal rules diff --git a/msgpack-translate.go b/msgpack-translate.go new file mode 100644 index 0000000..b120762 --- /dev/null +++ b/msgpack-translate.go @@ -0,0 +1,76 @@ +package main + +import ( + "bytes" + "encoding/hex" + "fmt" + "github.com/ugorji/go/codec" + "io/ioutil" + "os" + "strings" +) + +func usage(retval int) { + fmt.Printf("%s: converts msgpack data structures to JSON.\n", + os.Args[0]) + fmt.Printf("usage: %s [input-file]\n", os.Args[0]) + fmt.Printf("\n") + fmt.Printf("The input file should contain hex digits with no spaces or linebreaks.\n") + os.Exit(retval) +} + +func main() { + i := 1 + if len(os.Args) < 2 { + usage(1) + } + if (os.Args[i] == "-h") || (os.Args[i] == "--help") { + usage(0) + } + if i >= len(os.Args) { + usage(1) + } + path := os.Args[i] + buf, err := ioutil.ReadFile(path) + if err != nil { + fmt.Fprintf(os.Stderr, "Got error reading from %s: %s\n", + path, err.Error()) + os.Exit(1) + } + str := strings.ToLower(strings.TrimSpace(string(buf))) + if len(str)%2 != 0 { + fmt.Fprintf(os.Stderr, "The number of hex digits is not even.\n") + os.Exit(1) + } + var bin []byte + bin, err = hex.DecodeString(str) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to decode hex string '%s': %s\n", + str, err.Error()) + os.Exit(1) + } + fmt.Fprintf(os.Stdout, "input=\n"+hex.Dump(bin)+"\n") + + // Decode msgpack + mh := new(codec.MsgpackHandle) + mh.WriteExt = true + mh.RawToString = true + dec := codec.NewDecoderBytes(bin, mh) + var body interface{} + err = dec.Decode(&body) + + //fmt.Fprintf(os.Stdout, "body=%v\n", body); + + // Encode JSON + jh := new(codec.JsonHandle) + var out bytes.Buffer + enc := codec.NewEncoder(&out, jh) + err = enc.Encode(body) + if err != nil { + fmt.Fprintf(os.Stderr, "Error re-encoding message as JSON: %s\n", + err.Error()) + os.Exit(1) + } + fmt.Fprintf(os.Stdout, "output=\n%s\n", out.String()) + os.Exit(0) +} -- 1.6.6.rc1.39.g9a42