api.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. mux *http.ServeMux
  15. online bool
  16. running chan os.Signal
  17. }
  18. func NewApi(serverAddress string) *Api {
  19. srv := &http.Server{
  20. Addr: serverAddress,
  21. ReadTimeout: 5 * time.Second,
  22. WriteTimeout: 10 * time.Second,
  23. IdleTimeout: 120 * time.Second,
  24. }
  25. webserver := &Api{
  26. httpServer: srv,
  27. mux: http.NewServeMux(),
  28. online: false,
  29. }
  30. return webserver
  31. }
  32. func (api *Api) AddHandler(path string, handler func(http.ResponseWriter, *http.Request)) {
  33. api.mux.HandleFunc(path, handler)
  34. }
  35. func (api *Api) Start(wg *sync.WaitGroup) error {
  36. defer wg.Done()
  37. api.httpServer.Handler = api.mux
  38. go func() {
  39. api.httpServer.ListenAndServe()
  40. }()
  41. go logrus.Info("API webserver has started")
  42. api.online = true
  43. api.running = make(chan os.Signal, 1)
  44. signal.Notify(api.running, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
  45. <-api.running
  46. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  47. if err := api.httpServer.Shutdown(ctx); err != nil {
  48. logrus.Error(err)
  49. } else {
  50. logrus.Info("API webserver shutdown")
  51. }
  52. api.online = false
  53. return nil
  54. }
  55. func (api *Api) Stop() {
  56. if api.online {
  57. logrus.Infof("Shutting down API webserver")
  58. api.running <- syscall.SIGINT
  59. }
  60. }