Quellcode durchsuchen

Added https support

Mathew Medoff vor 3 Jahren
Ursprung
Commit
d247935436
1 geänderte Dateien mit 35 neuen und 9 gelöschten Zeilen
  1. 35 9
      api.go

+ 35 - 9
api.go

@@ -2,16 +2,16 @@ package api
 
 import (
 	"context"
-	"fmt"
 	"net/http"
 	"os"
 	"os/signal"
+	"strconv"
 	"sync"
 	"syscall"
 	"time"
 
-	"github.com/sirupsen/logrus"
 	"github.com/gorilla/mux"
+	"github.com/sirupsen/logrus"
 )
 
 type Api struct {
@@ -19,27 +19,46 @@ type Api struct {
 	mux        *mux.Router
 	online     bool
 	running    chan os.Signal
+	ssl        bool
+	cert       string
+	key        string
+}
+
+type ApiConfig struct {
+	Address string
+	Port    int
+	SSL     bool
+	Cert    string
+	Key     string
 }
 
-func NewApi(serverAddress string) *Api {
+func NewApi(config ApiConfig) *Api {
+	logrus.Info(config)
 	srv := &http.Server{
-		Addr:         serverAddress,
+		Addr:         config.Address + ":" + strconv.Itoa(config.Port),
 		ReadTimeout:  5 * time.Second,
 		WriteTimeout: 10 * time.Second,
 		IdleTimeout:  120 * time.Second,
 	}
 
+	logrus.Warn(srv.Addr)
+
 	webserver := &Api{
 		httpServer: srv,
 		mux:        mux.NewRouter(),
 		online:     false,
 	}
 
+	if config.SSL {
+		webserver.ssl = true
+		webserver.cert = config.Cert
+		webserver.key = config.Key
+	}
+
 	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)
 }
 
@@ -49,7 +68,14 @@ func (api *Api) Start(wg *sync.WaitGroup) error {
 	api.httpServer.Handler = api.mux
 
 	go func() {
-		api.httpServer.ListenAndServe()
+		if api.ssl {
+			err := api.httpServer.ListenAndServeTLS(api.cert, api.key)
+			if err != nil {
+				logrus.Fatal(err)
+			}
+		} else {
+			api.httpServer.ListenAndServe()
+		}
 	}()
 
 	go logrus.Info("API webserver has started")
@@ -61,9 +87,9 @@ func (api *Api) Start(wg *sync.WaitGroup) error {
 	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
 
 	if err := api.httpServer.Shutdown(ctx); err != nil {
-		logrus.Error(err)
+		go logrus.Error(err)
 	} else {
-		logrus.Info("API webserver shutdown")
+		go logrus.Info("API webserver shutdown")
 	}
 	api.online = false
 	return nil
@@ -71,7 +97,7 @@ func (api *Api) Start(wg *sync.WaitGroup) error {
 
 func (api *Api) Stop() {
 	if api.online {
-		logrus.Infof("Shutting down API webserver")
+		go logrus.Infof("Shutting down API webserver")
 		api.running <- syscall.SIGINT
 	}
 }