package websocket import ( "fmt" "log" "sync" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/tecamino/tecamino-dbm/cert" "github.com/tecamino/tecamino-dbm/utils" "github.com/tecamino/tecamino-logger/logging" ) // server model for database manager websocket type Server struct { Routes *gin.Engine sync.RWMutex Logger *logging.Logger } // initalizes new dbm server func NewServer(allowOrigins []string, port uint) *Server { r := gin.Default() allowOrigins = append(allowOrigins, fmt.Sprintf("http://localhost:%d", port)) localIP, err := utils.GetLocalIP() if err != nil { log.Printf("get local ip : %s", err.Error()) } else { allowOrigins = append(allowOrigins, fmt.Sprintf("http://%s:%d", localIP, port)) } r.Use(cors.New(cors.Config{ AllowOrigins: allowOrigins, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, MaxAge: 12 * time.Hour, })) return &Server{ Routes: r, } } // serve dbm as http func (s *Server) ServeHttp(ip string, port uint) error { return s.Routes.Run(fmt.Sprintf("%s:%d", ip, port)) } // serve dbm as http func (s *Server) ServeHttps(ip string, port uint, cert cert.Cert) error { // generate self signed tls certificate if err := cert.GenerateSelfSignedCert(); err != nil { return err } return s.Routes.RunTLS(fmt.Sprintf("%s:%d", ip, port), cert.CertFile, cert.KeyFile) }