This commit is contained in:
lbenedar
2026-03-24 15:21:13 +03:00
parent 974e7f151f
commit 338ef680ba
2 changed files with 65 additions and 1 deletions

View File

@@ -173,7 +173,9 @@ func (app *application) requirePermissions(code string, next http.HandlerFunc) h
func (app *application) enableCORS(next http.Handler) http.Handler { func (app *application) enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Vary", "Origin") w.Header().Add("Vary", "Origin")
w.Header().Add("Vary", "Access-Control-Request-Method")
origin := r.Header.Get("Origin") origin := r.Header.Get("Origin")
@@ -181,6 +183,14 @@ func (app *application) enableCORS(next http.Handler) http.Handler {
for i := range app.config.cors.trustedOrigins { for i := range app.config.cors.trustedOrigins {
if origin == app.config.cors.trustedOrigins[i] { if origin == app.config.cors.trustedOrigins[i] {
w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, PUT, PATCH, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.WriteHeader(http.StatusOK)
return
}
break break
} }
} }

View File

@@ -0,0 +1,54 @@
package main
import (
"flag"
"log"
"net/http"
)
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Preflight CORS</h1>
<div id="output"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
fetch("http://localhost:4000/v1/tokens/authentication", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'alice@example.com',
password: 'pa55word'
})
}).then(
function (response) {
response.text().then(function (text) {
document.getElementById("output").innerHTML = text;
});
},
function(err) {
document.getElementById("output").innerHTML = err;
}
);
});
</script>
</body>
</html>`
func main() {
addr := flag.String("addr", ":9000", "Server address")
flag.Parse()
log.Printf("starting server on %s", *addr)
err := http.ListenAndServe(*addr, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(html))
}))
log.Fatal(err)
}