Skip to content

Instantly share code, notes, and snippets.

@ricjcosme
Created April 4, 2018 10:19
Show Gist options
  • Save ricjcosme/1af098bb7c8e19675c6c41e17050e712 to your computer and use it in GitHub Desktop.
Save ricjcosme/1af098bb7c8e19675c6c41e17050e712 to your computer and use it in GitHub Desktop.
Command line base58 enc/dec in golang
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
"bufio"
b58 "github.com/jbenet/go-base58"
"github.com/spf13/cobra"
)
var b58Cmd = &cobra.Command{
Use: "b58",
Short: "",
Long: "",
Run: b58CmdFunc,
}
var encCmd = &cobra.Command{
Use: "enc",
Short: "",
Long: "",
Run: encodeFunc,
}
var decCmd = &cobra.Command{
Use: "dec",
Short: "",
Long: "",
Run: decodeFunc,
}
func b58CmdFunc(c *cobra.Command, inp []string) {
c.Help()
}
func encodeFunc(c *cobra.Command, inp []string) {
reader := bufio.NewReader(os.Stdin)
text, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
input := strings.TrimRight(text, "\r\n")
fmt.Printf("encoded: %s\n", b58.Encode([]byte(input)))
}
func decodeFunc(c *cobra.Command, inp []string) {
if len(inp) > 0 {
for _, s := range inp {
fmt.Println(string(b58.Decode(s)))
}
} else {
i, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
if i[len(i)-1] == '\n' {
i = i[:len(i)-1]
}
decoded := b58.Decode(string(i))
os.Stdout.Write(decoded)
}
}
func main() {
b58Cmd.AddCommand(encCmd, decCmd)
b58Cmd.Execute()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment