52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
var legacyCORSAllowedOrigins = []string{
|
|
"http://localhost:3000",
|
|
"http://localhost:5000",
|
|
"http://127.0.0.1:3000",
|
|
"http://127.0.0.1:5000",
|
|
}
|
|
|
|
// CORSMiddleware adds CORS headers for the local development origins.
|
|
func CORSMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if origin := c.Request.Header.Get("Origin"); origin != "" && isOriginAllowed(origin, legacyCORSAllowedOrigins) {
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
|
c.Header("Vary", "Origin")
|
|
}
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
|
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
|
|
c.Header("Access-Control-Max-Age", "86400")
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequestLoggerMiddleware logs method, path, status, and latency.
|
|
func RequestLoggerMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
|
|
c.Next()
|
|
|
|
latency := time.Since(start)
|
|
status := c.Writer.Status()
|
|
method := c.Request.Method
|
|
|
|
fmt.Fprintf(gin.DefaultWriter, "%s %s %d %v\n", method, path, status, latency)
|
|
}
|
|
}
|