main.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Solution to part 2 of the Whispering Gophers code lab.
  2. //
  3. // This program extends part 1.
  4. //
  5. // It makes a connection the host and port specified by the -dial flag, reads
  6. // lines from standard input and writes JSON-encoded messages to the network
  7. // connection.
  8. //
  9. // You can test this program by installing and running the dump program:
  10. // $ go get github.com/campoy/whispering-gophers/util/dump
  11. // $ dump -listen=localhost:8000
  12. // And in another terminal session, run this program:
  13. // $ part2 -dial=localhost:8000
  14. // Lines typed in the second terminal should appear as JSON objects in the
  15. // first terminal.
  16. //
  17. package main
  18. import (
  19. "bufio"
  20. "encoding/json"
  21. "flag"
  22. "log"
  23. "net"
  24. "os"
  25. )
  26. var dialAddr = flag.String("dial", "localhost:8000", "host:port to dial")
  27. type Message struct {
  28. Body string
  29. }
  30. func main() {
  31. // TODO: Parse the flags.
  32. // TODO: Open a new connection using the value of the "dial" flag.
  33. // TODO: Don't forget to check the error.
  34. s := bufio.NewScanner(os.Stdin)
  35. // TODO: Create a json.Encoder writing into the connection you created before.
  36. for s.Scan() {
  37. m := Message{Body: s.Text()}
  38. err := e.Encode(m)
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. }
  43. if err := s.Err(); err != nil {
  44. log.Fatal(err)
  45. }
  46. }