api.go 1.4 KB

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