Improved UX by reusing scanLine function

This commit is contained in:
raul 2024-03-03 10:29:50 +01:00
parent a89ca3987b
commit 9e978f0bcf
3 changed files with 48 additions and 2 deletions

View File

@ -9,7 +9,7 @@ import (
func bgChecker() { func bgChecker() {
for { for {
if check == true { if check == true {
fmt.Println("Check has been set to true, quitting") fmt.Println("\nCheck has been set to true, quitting")
os.Exit(0) os.Exit(0)
} }
time.Sleep(time.Second) time.Sleep(time.Second)

View File

@ -2,23 +2,34 @@ package main
import ( import (
"fmt" "fmt"
"os"
"strconv"
) )
var check bool = false var check bool = false
var choice string var choice string
var err error
func main() { func main() {
var numChoice int var numChoice int
for { for {
fmt.Printf("[1] Basic concurrency\n") fmt.Printf("[1] Basic concurrency\n")
fmt.Printf("[2] Channels\n")
fmt.Printf("\rChoose your function: ") fmt.Printf("\rChoose your function: ")
fmt.Scanln(&numChoice)
strChoice := scanLine()
numChoice, err = strconv.Atoi(strChoice)
catchErr(err)
switch numChoice { switch numChoice {
case 1: case 1:
fun1() fun1()
os.Exit(0)
case 2:
fun2()
os.Exit(0)
default: default:
fmt.Printf("Choose an actual function, please\n") fmt.Printf("Choose an actual function, please\n")
} }

View File

@ -0,0 +1,35 @@
package main
import (
"bufio"
"os"
"runtime"
"strings"
)
func scanLine() (line string) {
switch runtime.GOOS {
case "linux":
in := bufio.NewReader(os.Stdin)
lineNew, err := in.ReadString('\n')
catchErr(err)
line = strings.Trim(lineNew, "\n")
// I hate Windows
case "windows":
in := bufio.NewReader(os.Stdin)
lineNew, err := in.ReadString('\r')
catchErr(err)
line = strings.Trim(lineNew, "\r")
}
return line
}
func catchErr(err error) (errHappened bool) {
errHappened = false
if err != nil {
//fmt.Println(err)
errHappened = true
}
return errHappened
}