Makefile: add pickrand
[cmccabe-bin] / msgpack-translate.go
1 package main
2
3 import (
4         "bytes"
5         "encoding/hex"
6         "fmt"
7         "github.com/ugorji/go/codec"
8         "io/ioutil"
9         "os"
10         "strings"
11 )
12
13 func usage(retval int) {
14         fmt.Printf("%s: converts msgpack data structures to JSON.\n",
15                 os.Args[0])
16         fmt.Printf("usage: %s [input-file]\n", os.Args[0])
17         fmt.Printf("\n")
18         fmt.Printf("The input file should contain hex digits with no spaces or linebreaks.\n")
19         os.Exit(retval)
20 }
21
22 func main() {
23         i := 1
24         if len(os.Args) < 2 {
25                 usage(1)
26         }
27         if (os.Args[i] == "-h") || (os.Args[i] == "--help") {
28                 usage(0)
29         }
30         if i >= len(os.Args) {
31                 usage(1)
32         }
33         path := os.Args[i]
34         buf, err := ioutil.ReadFile(path)
35         if err != nil {
36                 fmt.Fprintf(os.Stderr, "Got error reading from %s: %s\n",
37                         path, err.Error())
38                 os.Exit(1)
39         }
40         str := strings.ToLower(strings.TrimSpace(string(buf)))
41         if len(str)%2 != 0 {
42                 fmt.Fprintf(os.Stderr, "The number of hex digits is not even.\n")
43                 os.Exit(1)
44         }
45         var bin []byte
46         bin, err = hex.DecodeString(str)
47         if err != nil {
48                 fmt.Fprintf(os.Stderr, "Failed to decode hex string '%s': %s\n",
49                         str, err.Error())
50                 os.Exit(1)
51         }
52         fmt.Fprintf(os.Stdout, "input=\n"+hex.Dump(bin)+"\n")
53
54         // Decode msgpack
55         mh := new(codec.MsgpackHandle)
56         mh.WriteExt = true
57         mh.RawToString = true
58         dec := codec.NewDecoderBytes(bin, mh)
59         var body interface{}
60         err = dec.Decode(&body)
61
62         //fmt.Fprintf(os.Stdout, "body=%v\n", body);
63
64         // Encode JSON
65         jh := new(codec.JsonHandle)
66         var out bytes.Buffer
67         enc := codec.NewEncoder(&out, jh)
68         err = enc.Encode(body)
69         if err != nil {
70                 fmt.Fprintf(os.Stderr, "Error re-encoding message as JSON: %s\n",
71                         err.Error())
72                 os.Exit(1)
73         }
74         fmt.Fprintf(os.Stdout, "output=\n%s\n", out.String())
75         os.Exit(0)
76 }