You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
953 B

  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. "github.com/chzyer/readline"
  7. )
  8. import "log"
  9. func main() {
  10. rl, err := readline.NewEx(&readline.Config{
  11. UniqueEditLine: true,
  12. })
  13. if err != nil {
  14. panic(err)
  15. }
  16. defer rl.Close()
  17. rl.SetPrompt("username: ")
  18. username, err := rl.Readline()
  19. if err != nil {
  20. return
  21. }
  22. rl.ResetHistory()
  23. log.SetOutput(rl.Stderr())
  24. fmt.Fprintln(rl, "Hi,", username+"! My name is Dave.")
  25. rl.SetPrompt(username + "> ")
  26. done := make(chan struct{})
  27. go func() {
  28. rand.Seed(time.Now().Unix())
  29. loop:
  30. for {
  31. select {
  32. case <-time.After(time.Duration(rand.Intn(20)) * 100 * time.Millisecond):
  33. case <-done:
  34. break loop
  35. }
  36. log.Println("Dave:", "hello")
  37. }
  38. log.Println("Dave:", "bye")
  39. done <- struct{}{}
  40. }()
  41. for {
  42. ln := rl.Line()
  43. if ln.CanContinue() {
  44. continue
  45. } else if ln.CanBreak() {
  46. break
  47. }
  48. log.Println(username+":", ln.Line)
  49. }
  50. rl.Clean()
  51. done <- struct{}{}
  52. <-done
  53. }