1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package api
- import (
- "context"
- "net/http"
- "os"
- "os/signal"
- "sync"
- "syscall"
- "time"
- "github.com/Sirupsen/logrus"
- )
- type Api struct {
- httpServer *http.Server
- mux *http.ServeMux
- online bool
- running chan os.Signal
- }
- func NewApi(serverAddress string) *Api {
- srv := &http.Server{
- Addr: serverAddress,
- ReadTimeout: 5 * time.Second,
- WriteTimeout: 10 * time.Second,
- IdleTimeout: 120 * time.Second,
- }
- webserver := &Api{
- httpServer: srv,
- mux: http.NewServeMux(),
- online: false,
- }
- return webserver
- }
- func (api *Api) AddHandler(path string, handler func(http.ResponseWriter, *http.Request)) {
- api.mux.HandleFunc(path, handler)
- }
- func (api *Api) Start(wg *sync.WaitGroup) error {
- defer wg.Done()
- api.httpServer.Handler = api.mux
- go func() {
- api.httpServer.ListenAndServe()
- }()
- go logrus.Info("API webserver has started")
- api.online = true
- api.running = make(chan os.Signal, 1)
- signal.Notify(api.running, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
- <-api.running
- ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
- if err := api.httpServer.Shutdown(ctx); err != nil {
- logrus.Error(err)
- } else {
- logrus.Info("API webserver shutdown")
- }
- api.online = false
- return nil
- }
- func (api *Api) Stop() {
- if api.online {
- logrus.Infof("Shutting down API webserver")
- api.running <- syscall.SIGINT
- }
- }
|