Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Last active November 30, 2020 12:47
Show Gist options
  • Save developer-guy/0986ebc62fd6af5bf31c873ae3406152 to your computer and use it in GitHub Desktop.
Save developer-guy/0986ebc62fd6af5bf31c873ae3406152 to your computer and use it in GitHub Desktop.
Capturing Sensitive Information from input by editor
package main
import (
"io/ioutil"
"os"
"os/exec"
"fmt"
)
// DefaultEditor is vim because we're adults ;)
const DefaultEditor = "vim"
// OpenFileInEditor opens filename in a text editor.
func OpenFileInEditor(filename string) error {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = DefaultEditor
}
// Get the full executable path for the editor.
executable, err := exec.LookPath(editor)
if err != nil {
return err
}
cmd := exec.Command(executable, filename)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// CaptureInputFromEditor opens a temporary file in a text editor and returns
// the written bytes on success or an error on failure. It handles deletion
// of the temporary file behind the scenes.
func CaptureInputFromEditor() ([]byte, error) {
file, err := ioutil.TempFile(os.TempDir(), "*")
if err != nil {
return []byte{}, err
}
filename := file.Name()
// Defer removal of the temporary file in case any of the next steps fail.
defer os.Remove(filename)
if err = file.Close(); err != nil {
return []byte{}, err
}
if err = OpenFileInEditor(filename); err != nil {
return []byte{}, err
}
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return []byte{}, err
}
return bytes, nil
}
func main() {
sensiviteInputBytes , err := CaptureInputFromEditor()
if err != nil {
panic(err)
}
fmt.Println("Sensitive input:", string(sensiviteInputBytes))
}
@developer-guy
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment