Files
tecamino-dbm/websocket/server.go
Adrian Zuercher 48d05eec7e repo name change
2025-08-07 12:18:57 +02:00

61 lines
1.5 KiB
Go

package websocket
import (
"fmt"
"log"
"sync"
"time"
"gitea.tecamino.com/paadi/tecamino-dbm/cert"
"gitea.tecamino.com/paadi/tecamino-dbm/utils"
"gitea.tecamino.com/paadi/tecamino-logger/logging"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
// 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)
}