Created
April 13, 2018 05:07
-
-
Save picatz/80172d089adef61c2c8b797e4027e9c6 to your computer and use it in GitHub Desktop.
Automatically encode/decode base64 data via a STDIN pipe
This file contains hidden or 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 ( | |
"bufio" | |
"encoding/base64" | |
"fmt" | |
"os" | |
) | |
func main() { | |
f, _ := os.Stdin.Stat() | |
if f.Mode()&os.ModeNamedPipe == 0 { | |
fmt.Println("must pipe data into this command!") | |
os.Exit(1) | |
} | |
scanner := bufio.NewScanner(os.Stdin) | |
for scanner.Scan() { | |
if scanner.Err() != nil { | |
os.Exit(0) | |
} | |
decodedString, err := base64.StdEncoding.DecodeString(scanner.Text()) | |
if err != nil { | |
data := []byte(scanner.Text()) | |
encodedString := base64.StdEncoding.EncodeToString(data) | |
fmt.Println(encodedString) | |
continue | |
} else { | |
fmt.Println(string(decodedString)) | |
} | |
} | |
} | |
// echo -e 'Hello\nWorld!' > file.txt | |
// cat file.txt | ./base64 | |
// cat file.txt | ./base64 | ./base64 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment