Add cors middleware

This commit is contained in:
2025-07-27 19:05:15 +02:00
parent f061a65baf
commit 40d11b12ca
6 changed files with 24 additions and 4 deletions

View File

@@ -23,6 +23,9 @@ type ServerConfig struct {
// Server port to bind to
Port int `yaml:"port"`
// Allowed origins for CORS (e.g., "http://localhost:3000")
AllowedOrigins []string `yaml:"allowed_origins"`
}
// InstancesConfig contains instance management configuration
@@ -57,8 +60,9 @@ func LoadConfig(configPath string) (Config, error) {
// 1. Start with defaults
cfg := Config{
Server: ServerConfig{
Host: "",
Port: 8080,
Host: "0.0.0.0",
Port: 8080,
AllowedOrigins: []string{"*"}, // Default to allow all origins
},
Instances: InstancesConfig{
PortRange: [2]int{8000, 9000},

View File

@@ -15,11 +15,13 @@ import (
type Handler struct {
InstanceManager InstanceManager
config Config
}
func NewHandler(im InstanceManager) *Handler {
func NewHandler(im InstanceManager, config Config) *Handler {
return &Handler{
InstanceManager: im,
config: config,
}
}

View File

@@ -5,6 +5,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
httpSwagger "github.com/swaggo/http-swagger"
_ "llamactl/docs"
@@ -15,6 +16,16 @@ func SetupRouter(handler *Handler) *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.Logger)
// Add CORS middleware
r.Use(cors.Handler(cors.Options{
AllowedOrigins: handler.config.Server.AllowedOrigins,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
MaxAge: 300,
}))
r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("/swagger/doc.json"),
))