run initializes the chatServer and then starts a http.Server for the passed in address.
()
| 23 | // run initializes the chatServer and then |
| 24 | // starts a http.Server for the passed in address. |
| 25 | func run() error { |
| 26 | if len(os.Args) < 2 { |
| 27 | return errors.New("please provide an address to listen on as the first argument") |
| 28 | } |
| 29 | |
| 30 | l, err := net.Listen("tcp", os.Args[1]) |
| 31 | if err != nil { |
| 32 | return err |
| 33 | } |
| 34 | log.Printf("listening on ws://%v", l.Addr()) |
| 35 | |
| 36 | cs := newChatServer() |
| 37 | s := &http.Server{ |
| 38 | Handler: cs, |
| 39 | ReadTimeout: time.Second * 10, |
| 40 | WriteTimeout: time.Second * 10, |
| 41 | } |
| 42 | errc := make(chan error, 1) |
| 43 | go func() { |
| 44 | errc <- s.Serve(l) |
| 45 | }() |
| 46 | |
| 47 | sigs := make(chan os.Signal, 1) |
| 48 | signal.Notify(sigs, os.Interrupt) |
| 49 | select { |
| 50 | case err := <-errc: |
| 51 | log.Printf("failed to serve: %v", err) |
| 52 | case sig := <-sigs: |
| 53 | log.Printf("terminating: %v", sig) |
| 54 | } |
| 55 | |
| 56 | ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) |
| 57 | defer cancel() |
| 58 | |
| 59 | return s.Shutdown(ctx) |
| 60 | } |