Skip to content

Instantly share code, notes, and snippets.

@artyom
Created March 12, 2016 22:06
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save artyom/a59e2707976124f387f5 to your computer and use it in GitHub Desktop.
Save artyom/a59e2707976124f387f5 to your computer and use it in GitHub Desktop.
Example of interactive terminal in Go
package main
import (
"fmt"
"io"
"log"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
if err := chat(); err != nil {
log.Fatal(err)
}
}
func chat() error {
if !terminal.IsTerminal(0) || !terminal.IsTerminal(1) {
return fmt.Errorf("stdin/stdout should be terminal")
}
oldState, err := terminal.MakeRaw(0)
if err != nil {
return err
}
defer terminal.Restore(0, oldState)
screen := struct {
io.Reader
io.Writer
}{os.Stdin, os.Stdout}
term := terminal.NewTerminal(screen, "")
term.SetPrompt(string(term.Escape.Red) + "> " + string(term.Escape.Reset))
rePrefix := string(term.Escape.Cyan) + "Human says:" + string(term.Escape.Reset)
for {
line, err := term.ReadLine()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if line == "" {
continue
}
fmt.Fprintln(term, rePrefix, line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment