Skip to content

Commit 138793b

Browse files
committed
fix: cors add origin
1 parent 29e5cd8 commit 138793b

2 files changed

Lines changed: 47 additions & 11 deletions

File tree

backend/cmd/server/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,8 @@ func main() {
106106
w.WriteHeader(http.StatusOK)
107107
fmt.Fprintln(w, "OK")
108108
})
109-
url:=requiredEnv("CLIENT_URL")
110-
check(http.ListenAndServe(httpAddress(), corsmiddleware.CORS(mux,url)))
109+
//url:=requiredEnv("CLIENT_URL")
110+
check(http.ListenAndServe(httpAddress(), corsmiddleware.CORS(mux)))
111111

112112
}
113113
func check(err error) {
Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,24 @@
11
package 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

Comments
 (0)