1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package api
- import (
- "context"
- "fmt"
- "net/http"
- "os"
- "os/signal"
- "sync"
- "syscall"
- "time"
- "github.com/sirupsen/logrus"
- "github.com/gorilla/mux"
- )
- type Api struct {
- httpServer *http.Server
- mux *mux.Router
- 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: mux.NewRouter(),
- online: false,
- }
- return webserver
- }
- func (api *Api) AddHandler(path string, handler func(http.ResponseWriter, *http.Request), method string) {
- fmt.Println(path)
- api.mux.HandleFunc(path, handler).Methods(method)
- }
- 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
- }
- }
|