| package middleware | |
| import ( | |
| "log" | |
| "os" | |
| "time" | |
| "github.com/gofiber/fiber/v2" | |
| "github.com/gofiber/fiber/v2/middleware/cors" | |
| "github.com/gofiber/fiber/v2/middleware/recover" | |
| ) | |
| func SetupMiddleware(app *fiber.App) { | |
| app.Use(recover.New()) | |
| // Read allowed origins from env — set ALLOWED_ORIGINS on HuggingFace to your Render frontend URL | |
| // e.g. ALLOWED_ORIGINS=https://creepurl.onrender.com | |
| // Defaults to * (all origins) so it works out of the box | |
| allowedOrigins := os.Getenv("ALLOWED_ORIGINS") | |
| if allowedOrigins == "" { | |
| allowedOrigins = "*" | |
| } | |
| app.Use(cors.New(cors.Config{ | |
| AllowOrigins: allowedOrigins, | |
| AllowMethods: "GET,POST,OPTIONS", | |
| AllowHeaders: "Content-Type,Authorization,Accept", | |
| MaxAge: 300, | |
| })) | |
| app.Use(requestLogger) | |
| } | |
| func requestLogger(c *fiber.Ctx) error { | |
| start := time.Now() | |
| err := c.Next() | |
| duration := time.Since(start) | |
| log.Printf("[%s] %s %s — %d (%s)", | |
| c.Method(), | |
| c.Path(), | |
| c.IP(), | |
| c.Response().StatusCode(), | |
| duration, | |
| ) | |
| return err | |
| } |