ch18.4
This commit is contained in:
@@ -173,7 +173,9 @@ func (app *application) requirePermissions(code string, next http.HandlerFunc) h
|
||||
|
||||
func (app *application) enableCORS(next http.Handler) http.Handler {
|
||||
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")
|
||||
|
||||
@@ -181,6 +183,14 @@ func (app *application) enableCORS(next http.Handler) http.Handler {
|
||||
for i := range app.config.cors.trustedOrigins {
|
||||
if origin == app.config.cors.trustedOrigins[i] {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
54
cmd/examples/cors/preflight/main.go
Normal file
54
cmd/examples/cors/preflight/main.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user