package web import ( "net" "strconv" "github.com/Neur0toxine/sshpoke/internal/api/web/handler" "github.com/Neur0toxine/sshpoke/internal/api/web/middleware" "github.com/Neur0toxine/sshpoke/internal/logger" "github.com/gin-contrib/secure" "github.com/gin-gonic/gin" cors "github.com/rs/cors/wrapper/gin" "go.uber.org/zap" ) const ( DefaultPort = 25680 httpProto = "http://" ) func StartServer(token string, port int, log *zap.SugaredLogger, debug bool) { if !debug { gin.SetMode(gin.ReleaseMode) } logMiddleware := middleware.SetupLogger(log) g := gin.New() g.Use(logMiddleware) g.Use(cors.New(cors.Options{ AllowedOrigins: []string{ httpProto + net.JoinHostPort("localhost", strconv.Itoa(port)), httpProto + net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), }, AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "DELETE"}, MaxAge: 60 * 10, AllowCredentials: true, })) g.Use(secure.New(secureConfig())) router(g, token) err := g.Run(net.JoinHostPort("127.0.0.1", strconv.Itoa(port))) if err != nil { logger.Sugar.Errorf("cannot start Web API server on port %d: %s", port, err) } } func router(g *gin.Engine, token string) { api := g.Group("/api/v1") { api.Use(middleware.Auth(token)) api.GET("/config", handler.Config) api.GET("/status", handler.Status) } } func secureConfig() secure.Config { cfg := secure.DefaultConfig() cfg.SSLRedirect = false return cfg }