Search code examples
gocommand-line-interfaceuser-inputreadline

How to write to stdin in golang?


This is my code

func InputRead() string {
         reader := bufio.NewReader(os.Stdin);
         fmt.Print("> ");
         text, _ := reader.ReadString('\n');
         text = strings.Replace(text, "\n", "", -1);
}

I want to place some string in os.Stdin, how would I achieve that? It should appear
> HAHA then my cursor should have ability to remove that HAHA similar to <input> with prefilled text in HTML.
In python3 its implemented like this

def stdininput(prompt, text):
         def hook():
             readline.insert_text(text)
             readline.redisplay()
         readline.set_pre_input_hook(hook)
         result = input(prompt)
         readline.set_pre_input_hook()
         return result
import readline
print(stdininput('> ', 'haha'))

For those who find it hard to understand, I am just asking to put a certain text (the text that we type when asked for input and can delete it) without typing. Like if user is asked for input and I want to provide a default input so user dont have to type.


Solution

  • Since, no one answered. After going for all the functions for those long period at last I found a function from readline library as kostix said. So, here's the sample program.

    root@kali-linux:/tmp# cat main.go 
    package main
    
    import "github.com/chzyer/readline"
    import "fmt"
    
    func main() {
            input, _ := readline.New("> ");
            defer input.Close();
    
            datax := "Hey niko my friend"; //GTA IV
            data2 := []byte(datax);
            input.WriteStdin(data2);
    
            value, _ := input.Readline()
            fmt.Println(value);
    }
    root@kali-linux:/tmp# go run main.go 
    > Hey niko my friend