multiaddr.go 1.28 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9
package main

import (
	"encoding/hex"
	"flag"
	"fmt"
	"os"

	ma "github.com/jbenet/go-multiaddr"
10
	manet "github.com/jbenet/go-multiaddr/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12
)

13
var formats = []string{"string", "bytes", "hex", "slice"}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14 15 16 17
var format string

func init() {
	flag.Usage = func() {
18
		fmt.Fprintf(os.Stderr, "usage: %s [<multiaddr>]\n\nFlags:\n", os.Args[0])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20 21 22 23 24 25 26 27 28 29
		flag.PrintDefaults()
	}

	usage := fmt.Sprintf("output format, one of: %v", formats)
	flag.StringVar(&format, "format", "string", usage)
	flag.StringVar(&format, "f", "string", usage+" (shorthand)")
}

func main() {
	flag.Parse()
	args := flag.Args()
30 31 32 33 34 35 36 37
	if len(args) == 0 {
		maddrs, err := manet.InterfaceMultiaddrs()
		if err != nil {
			die(err)
		}

		output(maddrs...)
		return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39 40 41 42 43 44
	}

	m, err := ma.NewMultiaddr(args[0])
	if err != nil {
		die(err)
	}

45 46 47 48 49 50 51
	output(m)
}

func output(ms ...ma.Multiaddr) {
	for _, m := range ms {
		fmt.Println(outfmt(m))
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54 55 56 57
}

func outfmt(m ma.Multiaddr) string {
	switch format {
	case "string":
		return m.String()
58
	case "slice":
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59
		return fmt.Sprintf("%v", m.Bytes())
60
	case "bytes":
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
		return string(m.Bytes())
	case "hex":
		return "0x" + hex.EncodeToString(m.Bytes())
	}

	die("error: invalid format", format)
	return ""
}

func die(v ...interface{}) {
	fmt.Fprint(os.Stderr, v...)
	fmt.Fprint(os.Stderr, "\n")
	flag.Usage()
	os.Exit(-1)
}