Is there a Go function similar to C\'s getchar
able to handle tab press in console? I want to make some sort of completion in my console app.
1- You may use C.getch()
:
This works in Windows command line, Reads only one character without Enter:
(Run output binary file inside shell (terminal), not inside pipe or Editor.)
package main
//#include
import "C"
import "fmt"
func main() {
c := C.getch()
fmt.Println(c)
}
2- For Linux ( tested on Ubuntu ):
package main
/*
#include
#include
#include
char getch(){
char ch = 0;
struct termios old = {0};
fflush(stdout);
if( tcgetattr(0, &old) < 0 ) perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if( tcsetattr(0, TCSANOW, &old) < 0 ) perror("tcsetattr ICANON");
if( read(0, &ch,1) < 0 ) perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if(tcsetattr(0, TCSADRAIN, &old) < 0) perror("tcsetattr ~ICANON");
return ch;
}
*/
import "C"
import "fmt"
func main() {
fmt.Println(C.getch())
fmt.Println()
}
See:
What is Equivalent to getch() & getche() in Linux?
Why can't I find
3- Also this works, but needs "Enter":
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
r := bufio.NewReader(os.Stdin)
c, err := r.ReadByte()
if err != nil {
panic(err)
}
fmt.Println(c)
}