api.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  6. "os/signal"
  7. "sync"
  8. "syscall"
  9. "time"
  10. "github.com/Sirupsen/logrus"
  11. )
  12. type Api struct {
  13. httpServer *http.Server
  14. online bool
  15. running chan os.Signal
  16. }
  17. func NewApi(mux *http.ServeMux, serverAddress string) *Api {
  18. srv := &http.Server{
  19. Addr: serverAddress,
  20. ReadTimeout: 5 * time.Second,
  21. WriteTimeout: 10 * time.Second,
  22. IdleTimeout: 120 * time.Second,
  23. Handler: mux,
  24. }
  25. webserver := &Api{
  26. httpServer: srv,
  27. online: false,
  28. }
  29. return webserver
  30. }
  31. func (api *Api) Start(wg *sync.WaitGroup) error {
  32. defer wg.Done()
  33. go func() {
  34. api.httpServer.ListenAndServe()
  35. }()
  36. go logrus.Info("API webserver has started")
  37. api.running = make(chan os.Signal, 1)
  38. signal.Notify(api.running, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
  39. <-api.running
  40. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  41. if err := api.httpServer.Shutdown(ctx); err != nil {
  42. logrus.Error(err)
  43. } else {
  44. logrus.Info("API webserver shutdown")
  45. }
  46. api.online = false
  47. return nil
  48. }
  49. func (api *Api) Stop() {
  50. if api.online {
  51. logrus.Infof("Shutting down Bot")
  52. api.running <- syscall.SIGINT
  53. }
  54. }