add automatic localhost and local ip to allow origin

This commit is contained in:
Adrian Zuercher
2025-06-29 21:18:15 +02:00
parent 59c7705ca1
commit e75d7c8b03
3 changed files with 34 additions and 9 deletions

View File

@@ -23,7 +23,7 @@ func main() {
//initialize new server //initialize new server
dbmHandler.Log.Debug("main", "initialize new server instance") dbmHandler.Log.Debug("main", "initialize new server instance")
s := ws.NewServer(a.AllowOrigins) s := ws.NewServer(a.AllowOrigins, 9000)
//set routes //set routes
dbmHandler.Log.Debug("main", "setting routes") dbmHandler.Log.Debug("main", "setting routes")

View File

@@ -1,5 +1,10 @@
package utils package utils
import (
"fmt"
"net"
)
func ListofA2ZZ() (list []string) { func ListofA2ZZ() (list []string) {
for i := 'A'; i <= 'Z'; i++ { for i := 'A'; i <= 'Z'; i++ {
list = append(list, string(i)) list = append(list, string(i))
@@ -9,12 +14,21 @@ func ListofA2ZZ() (list []string) {
list = append(list, string(i)+string(j)) list = append(list, string(i)+string(j))
} }
} }
// for i := 'A'; i <= 'Z'; i++ {
// for j := 'A'; j <= 'Z'; j++ {
// for k := 'A'; k <= 'Z'; k++ {
// list = append(list, string(i)+string(j)+string(k))
// }
// }
// }
return return
} }
func GetLocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
}
return "", fmt.Errorf("no local IP address found")
}

View File

@@ -2,12 +2,14 @@ package websocket
import ( import (
"fmt" "fmt"
"log"
"sync" "sync"
"time" "time"
"github.com/gin-contrib/cors" "github.com/gin-contrib/cors"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/cert" "github.com/tecamino/tecamino-dbm/cert"
"github.com/tecamino/tecamino-dbm/utils"
"github.com/tecamino/tecamino-logger/logging" "github.com/tecamino/tecamino-logger/logging"
) )
@@ -19,8 +21,17 @@ type Server struct {
} }
// initalizes new dbm server // initalizes new dbm server
func NewServer(allowOrigins []string) *Server { func NewServer(allowOrigins []string, port uint) *Server {
r := gin.Default() 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{ r.Use(cors.New(cors.Config{
AllowOrigins: allowOrigins, AllowOrigins: allowOrigins,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},