wms-be/middlewares/cors.go

53 lines
1.5 KiB
Go

package middlewares
import (
"net/http"
"github.com/gin-gonic/gin"
)
// func CORSMiddleware() gin.HandlerFunc {
// return func(c *gin.Context) {
// c.Header("Access-Control-Allow-Origin", "http://localhost:3000, https://wms.avolut.com")
// c.Header("Access-Control-Allow-Credentials", "true")
// c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
// c.Header("Access-Control-Allow-Methods", "POST, HEAD, PATCH, OPTIONS, GET, PUT, DELETE")
// if c.Request.Method == http.MethodOptions {
// c.AbortWithStatus(204)
// return
// }
// c.Next()
// }
// }
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.GetHeader("Origin")
// Daftar origin yang diizinkan
allowedOrigins := map[string]bool{
"http://localhost:3000": true,
"https://wms.avolut.com": true,
}
if allowedOrigins[origin] {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Vary", "Origin") // penting agar cache tidak salah
}
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST, HEAD, PATCH, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == http.MethodOptions {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}