Skip to content

Instantly share code, notes, and snippets.

@nicewook
Created November 29, 2023 08:02
Show Gist options
  • Save nicewook/9bb562e2689f26921e54ee3fef8c1620 to your computer and use it in GitHub Desktop.
Save nicewook/9bb562e2689f26921e54ee3fef8c1620 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"time"
)
var totalDuration = 5 * time.Second
func main() {
ctx, cancel := context.WithTimeout(context.Background(), totalDuration)
defer cancel()
name, err := getNameContext(ctx)
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("Sorry, time's up!, but let's check if you can entered your name")
time.Sleep(20 * time.Second)
}
if err != nil {
fmt.Fprintf(os.Stdout, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "Hello %s\n", name)
}
func getNameContext(ctx context.Context) (string, error) {
var err error
name := "John Doe"
c := make(chan error, 1)
go func() {
name, err = getName(os.Stdin, os.Stdout)
fmt.Fprintf(os.Stdout, "Got name: %s\n", name)
c <- err
}()
select {
case <-ctx.Done():
return name, ctx.Err()
case err := <-c:
return name, err
}
}
func getName(r io.Reader, w io.Writer) (string, error) {
scanner := bufio.NewScanner(r)
msg := "Your name please? Press the Enter key when done"
fmt.Fprintln(w, msg)
scanner.Scan()
if err := scanner.Err(); err != nil {
return "", err
}
name := scanner.Text()
if len(name) == 0 {
return "", errors.New("you entered an empty name")
}
return name, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment