http urls monitor.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package http
  2. import (
  3. "os"
  4. "os/signal"
  5. "strings"
  6. "syscall"
  7. "git.links123.net/links123.com/monitor_status/cmd/http/router"
  8. "github.com/braintree/manners"
  9. "github.com/sirupsen/logrus"
  10. "github.com/spf13/cobra"
  11. )
  12. // RunCommand cobra subcommand http
  13. func RunCommand() *cobra.Command {
  14. var host, port string
  15. cmd := &cobra.Command{
  16. Use: "http",
  17. Short: "Run the http service",
  18. Run: func(cmd *cobra.Command, args []string) {
  19. go Start(host, port)
  20. // 阻塞退出 捕获信号
  21. signalChan := make(chan os.Signal)
  22. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  23. logrus.Infof("caught signal %+v, begin garbage collection", <-signalChan)
  24. Stop()
  25. },
  26. }
  27. cmd.PersistentFlags().StringVarP(&host, "host", "o", "127.0.0.1", "server hostname")
  28. cmd.PersistentFlags().StringVarP(&port, "port", "p", "8080", "server port")
  29. return cmd
  30. }
  31. // Start use for cobra or testing
  32. func Start(host, port string) {
  33. // build router
  34. r := router.BuildRouter()
  35. // start server
  36. err := manners.ListenAndServe(strings.Join([]string{host, port}, ":"), r)
  37. if err != nil {
  38. panic(err)
  39. }
  40. }
  41. // Stop stop the http service graceful
  42. func Stop() {
  43. if manners.Close() {
  44. logrus.Info("http server stopped")
  45. }
  46. }