msgpack-translate.go: add program for msgpack translation
authorColin Patrick Mccabe <cmccabe@alumni.cmu.edu>
Fri, 26 Jun 2015 01:05:27 +0000 (18:05 -0700)
committerColin Patrick Mccabe <cmccabe@alumni.cmu.edu>
Fri, 26 Jun 2015 01:06:33 +0000 (18:06 -0700)
Signed-off-by: Colin McCabe <cmccabe@alumni.cmu.edu>

.gitignore
msgpack-translate.go [new file with mode: 0644]

index f0b2e2e..6d9e56f 100644 (file)
@@ -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 (file)
index 0000000..b120762
--- /dev/null
@@ -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)
+}