api.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  6. "os/signal"
  7. "strconv"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "github.com/gorilla/mux"
  12. "github.com/sirupsen/logrus"
  13. )
  14. type Api struct {
  15. httpServer *http.Server
  16. mux *mux.Router
  17. online bool
  18. running chan os.Signal
  19. ssl bool
  20. cert string
  21. key string
  22. }
  23. type ApiConfig struct {
  24. Address string
  25. Port int
  26. SSL bool
  27. Cert string
  28. Key string
  29. }
  30. func NewApi(config ApiConfig) *Api {
  31. logrus.Info(config)
  32. srv := &http.Server{
  33. Addr: config.Address + ":" + strconv.Itoa(config.Port),
  34. ReadTimeout: 5 * time.Second,
  35. WriteTimeout: 10 * time.Second,
  36. IdleTimeout: 120 * time.Second,
  37. }
  38. logrus.Warn(srv.Addr)
  39. webserver := &Api{
  40. httpServer: srv,
  41. mux: mux.NewRouter(),
  42. online: false,
  43. }
  44. if config.SSL {
  45. webserver.ssl = true
  46. webserver.cert = config.Cert
  47. webserver.key = config.Key
  48. }
  49. return webserver
  50. }
  51. func (api *Api) AddHandler(path string, handler func(http.ResponseWriter, *http.Request), method string) {
  52. api.mux.HandleFunc(path, handler).Methods(method)
  53. }
  54. func (api *Api) Start(wg *sync.WaitGroup) error {
  55. defer wg.Done()
  56. api.httpServer.Handler = api.mux
  57. go func() {
  58. if api.ssl {
  59. err := api.httpServer.ListenAndServeTLS(api.cert, api.key)
  60. if err != nil {
  61. logrus.Fatal(err)
  62. }
  63. } else {
  64. api.httpServer.ListenAndServe()
  65. }
  66. }()
  67. go logrus.Info("API webserver has started")
  68. api.online = true
  69. api.running = make(chan os.Signal, 1)
  70. signal.Notify(api.running, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
  71. <-api.running
  72. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  73. if err := api.httpServer.Shutdown(ctx); err != nil {
  74. go logrus.Error(err)
  75. } else {
  76. go logrus.Info("API webserver shutdown")
  77. }
  78. api.online = false
  79. return nil
  80. }
  81. func (api *Api) Stop() {
  82. if api.online {
  83. go logrus.Infof("Shutting down API webserver")
  84. api.running <- syscall.SIGINT
  85. }
  86. }