Created
September 30, 2023 11:30
-
-
Save Ozoniuss/a95ace6b8d729d710434e85f435510ff to your computer and use it in GitHub Desktop.
4- capture with channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"os/signal" | |
"strconv" | |
"syscall" | |
) | |
// scanStringUntilValid is a helper provided to get a string input from the | |
// terminal. It doesn't do any additional logic to simply retrieving the user | |
// input; it is only provided for consistency. | |
func scanStringUntilValid(s *bufio.Scanner, prefix string) string { | |
fmt.Print(prefix) | |
if !s.Scan() { | |
return "" | |
} | |
return s.Text() | |
} | |
// scanIntUntilValid is a helper provided to get a float input from the terminal. | |
// It will prompt the user for a value until the value is a valid floating | |
// point number. | |
func scanFloatUntilValid(s *bufio.Scanner, prefix string) float64 { | |
var valfloat float64 | |
var err error | |
for { | |
fmt.Print(prefix) | |
if !s.Scan() { | |
return 0 | |
} | |
val := s.Text() | |
if valfloat, err = strconv.ParseFloat(val, 64); err != nil { | |
fmt.Println("Invalid number, please try again.") | |
continue | |
} | |
return float64(valfloat) | |
} | |
} | |
type Debt struct { | |
Person string | |
Amount float64 | |
Currency string | |
Details string | |
} | |
func CreateDebtPrompter(header string) Debt { | |
if header != "" { | |
fmt.Println(header) | |
} | |
s := bufio.NewScanner(os.Stdin) | |
debt := Debt{} | |
ops := []func(){ | |
func() { | |
debt.Person = scanStringUntilValid(s, "person: ") | |
}, | |
func() { | |
debt.Amount = scanFloatUntilValid(s, "amount: ") | |
}, | |
func() { | |
debt.Currency = scanStringUntilValid(s, "currency: ") | |
}, | |
func() { | |
debt.Details = scanStringUntilValid(s, "details: ") | |
}, | |
} | |
for _, op := range ops { | |
select { | |
case <-c: | |
fmt.Println("exited") | |
os.Exit(1) | |
default: | |
op() | |
} | |
} | |
return debt | |
} | |
var c = make(chan os.Signal, 1) | |
func main() { | |
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) | |
go func() { | |
<-c | |
fmt.Println("exited") | |
os.Exit(1) | |
}() | |
debt := CreateDebtPrompter("") | |
fmt.Println("debt created: %s", debt) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment