Add open CORS handling to seeder API
This commit is contained in:
parent
55d727f176
commit
09b446db89
1 changed files with 20 additions and 3 deletions
|
|
@ -13,6 +13,21 @@ import (
|
||||||
//go:embed docs/openapi.json
|
//go:embed docs/openapi.json
|
||||||
var swaggerJSON string
|
var swaggerJSON string
|
||||||
|
|
||||||
|
func withCORS(handler http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||||
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||||
|
|
||||||
|
if r.Method == http.MethodOptions {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
godotenv.Load()
|
godotenv.Load()
|
||||||
port := os.Getenv("PORT")
|
port := os.Getenv("PORT")
|
||||||
|
|
@ -20,7 +35,9 @@ func main() {
|
||||||
port = "8080"
|
port = "8080"
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/seed", func(w http.ResponseWriter, r *http.Request) {
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
|
mux.HandleFunc("/seed", func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
return
|
return
|
||||||
|
|
@ -44,7 +61,7 @@ func main() {
|
||||||
w.Write([]byte(result))
|
w.Write([]byte(result))
|
||||||
})
|
})
|
||||||
|
|
||||||
http.HandleFunc("/swagger.json", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/swagger.json", func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodGet {
|
if r.Method != http.MethodGet {
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
return
|
return
|
||||||
|
|
@ -55,7 +72,7 @@ func main() {
|
||||||
})
|
})
|
||||||
|
|
||||||
log.Printf("Seeder API listening on port %s", port)
|
log.Printf("Seeder API listening on port %s", port)
|
||||||
if err := http.ListenAndServe(":"+port, nil); err != nil {
|
if err := http.ListenAndServe(":"+port, withCORS(mux)); err != nil {
|
||||||
log.Fatalf("Server error: %v", err)
|
log.Fatalf("Server error: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue