netmaker/controllers/controller.go

62 lines
1.6 KiB
Go
Raw Normal View History

2021-03-26 00:17:52 +08:00
package controller
import (
2021-07-22 06:55:19 +08:00
"context"
"log"
"net/http"
"os"
"os/signal"
"sync"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gravitl/netmaker/servercfg"
2021-03-26 00:17:52 +08:00
)
func HandleRESTRequests(wg *sync.WaitGroup) {
2021-07-22 06:55:19 +08:00
defer wg.Done()
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
r := mux.NewRouter()
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
// Currently allowed dev origin is all. Should change in prod
// should consider analyzing the allowed methods further
headersOk := handlers.AllowedHeaders([]string{"Access-Control-Allow-Origin", "X-Requested-With", "Content-Type", "authorization"})
originsOk := handlers.AllowedOrigins([]string{servercfg.GetAllowedOrigin()})
methodsOk := handlers.AllowedMethods([]string{"GET", "PUT", "POST", "DELETE"})
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
nodeHandlers(r)
userHandlers(r)
networkHandlers(r)
dnsHandlers(r)
fileHandlers(r)
serverHandlers(r)
extClientHandlers(r)
intClientHandlers(r)
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
port := servercfg.GetAPIPort()
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
srv := &http.Server{Addr: ":" + port, Handler: handlers.CORS(originsOk, headersOk, methodsOk)(r)}
go func() {
2021-03-26 00:17:52 +08:00
err := srv.ListenAndServe()
if err != nil {
log.Println(err)
2021-03-26 00:17:52 +08:00
}
2021-07-22 06:55:19 +08:00
}()
2021-07-22 06:55:19 +08:00
log.Println("REST Server succesfully started on port " + port + " (REST)")
c := make(chan os.Signal)
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
// Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
// Ignore other incoming signals
signal.Notify(c, os.Interrupt)
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
// Block main routine until a signal is received
// As long as user doesn't press CTRL+C a message is not passed and our main routine keeps running
<-c
2021-03-26 00:17:52 +08:00
2021-07-22 06:55:19 +08:00
// After receiving CTRL+C Properly stop the server
log.Println("Stopping the REST server...")
srv.Shutdown(context.TODO())
log.Println("REST Server closed.")
2021-03-26 00:17:52 +08:00
}