Command line base58 enc/dec in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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