So I've started a project which involves modules sending and receiving messages from a server via websockets. However I wanted a simple way for me to interact and send messages to the modules.
So I have the program ask for my message in a goroutine, when I hit enter, it sends the message and prompts me for another. In the main goroutine it will wait until it receives a message and when it does, write over the current line and replace what was on the line before on a new line.
There is only one problem, however. It don't know how to keep my input to place on the new line. In my testing with the following example, it seems that os.Stdin.Read halts until it receives a new-line character.
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
// Input Buffer
var msg string
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanBytes)
go func() {
for {
// Prompt the user for a message
fmt.Print("client1: ")
// Scan os.Stdin, splitting on bytes
for scanner.Scan() {
if scanner.Text() == "\n" {
break
} else {
// If the character is not \n, add to the input buffer
msg += scanner.Text()
}
}
// Do something with the input buffer then clear it
fmt.Println(msg)
msg = ""
}
}()
for {
select {
// Receive a message from a client
case <-time.After(5 * time.Second):
// Write the message over the current line
fmt.Println("\rclient2: Hello")
// Prompt the user again for their message
// proving the current input buffer
fmt.Print("client1: " + msg)
}
}
}
An example output:
client1: Hello!
Hello!
client2: Hello
client1: Bye!
Bye!
client2: Hello
client2: Hello // Was "client1: Good " before being overwritten
client1: Bye!
Good Bye!
Any ideas are greatly appreciated. Thank you in advanced.