Thisnthat 5 vuotta sitten
commit
95a80ce796
1 muutettua tiedostoa jossa 66 lisäystä ja 0 poistoa
  1. 66 0
      api.go

+ 66 - 0
api.go

@@ -0,0 +1,66 @@
+package api
+
+import (
+	"context"
+	"net/http"
+	"os"
+	"os/signal"
+	"sync"
+	"syscall"
+	"time"
+
+	"github.com/Sirupsen/logrus"
+)
+
+type Api struct {
+	httpServer *http.Server
+	online     bool
+	running    chan os.Signal
+}
+
+func NewApi(mux *http.ServeMux, serverAddress string) *Api {
+	srv := &http.Server{
+		Addr:         serverAddress,
+		ReadTimeout:  5 * time.Second,
+		WriteTimeout: 10 * time.Second,
+		IdleTimeout:  120 * time.Second,
+		Handler:      mux,
+	}
+
+	webserver := &Api{
+		httpServer: srv,
+		online:     false,
+	}
+
+	return webserver
+}
+
+func (api *Api) Start(wg *sync.WaitGroup) error {
+	defer wg.Done()
+
+	go func() {
+		api.httpServer.ListenAndServe()
+	}()
+
+	go logrus.Info("API webserver has started")
+	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 Bot")
+		api.running <- syscall.SIGINT
+	}
+}