11package middleware
22
3- import
4- ("net/http"
5-
3+ import (
4+ "net/http"
5+ "os"
6+ "strings"
7+ //"fmt"
8+
69)
710
8- func CORS (next http.Handler ,url string ) http.Handler {
9-
11+ func CORS (next http.Handler ) http.Handler {
1012 return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
1113
12- w .Header (). Set ( "Access-Control-Allow- Origin", url )
14+ origin := r .Header . Get ( " Origin" )
1315
14- w .Header ().Set ("Access-Control-Allow-Credentials " , "true" )
16+ w .Header ().Set ("Access-Control-Allow-Origin " , origin )
1517
18+ w .Header ().Set ("Access-Control-Allow-Credentials" , "true" )
1619 w .Header ().Set ("Access-Control-Allow-Headers" , "Authorization, Content-Type" )
17-
1820 w .Header ().Set ("Access-Control-Allow-Methods" , "GET, POST, PATCH, PUT, DELETE, OPTIONS" )
1921
20- // preflight
2122 if r .Method == http .MethodOptions {
2223 w .WriteHeader (http .StatusOK )
2324 return
@@ -26,3 +27,38 @@ func CORS(next http.Handler,url string) http.Handler {
2627 next .ServeHTTP (w , r )
2728 })
2829}
30+
31+ func allowedOriginsFromEnv () map [string ]struct {} {
32+ origins := map [string ]struct {}{}
33+
34+ for _ , envKey := range []string {"CLIENT_URL" , "CORS_ALLOWED_ORIGINS" } {
35+ raw := strings .TrimSpace (os .Getenv (envKey ))
36+ if raw == "" {
37+ continue
38+ }
39+
40+ for _ , candidate := range strings .Split (raw , "," ) {
41+ origin := strings .TrimSpace (strings .TrimSuffix (candidate , "/" ))
42+ if origin == "" {
43+ continue
44+ }
45+ origins [origin ] = struct {}{}
46+ }
47+ }
48+
49+ if len (origins ) == 0 {
50+ origins ["http://localhost:5173" ] = struct {}{}
51+ }
52+
53+ return origins
54+ }
55+
56+ func isAllowedOrigin (origin string , allowed map [string ]struct {}) bool {
57+ if origin == "" {
58+ return false
59+ }
60+
61+ normalized := strings .TrimSuffix (strings .TrimSpace (origin ), "/" )
62+ _ , ok := allowed [normalized ]
63+ return ok
64+ }
0 commit comments