Skip to content

Commit

Permalink
Fix Access-Control-Allow-Origin (#14)
Browse files Browse the repository at this point in the history
Didn't read the documentation!  Only one can be returned.
  • Loading branch information
spjmurray authored Mar 6, 2024
1 parent 260d73e commit fb0e128
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
4 changes: 2 additions & 2 deletions charts/unikorn/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: A Helm chart for deploying Unikorn

type: application

version: v0.1.3
appVersion: v0.1.3
version: v0.1.4
appVersion: v0.1.4

icon: https://raw.githubusercontent.com/unikorn-cloud/unikorn/main/icons/default.png
18 changes: 14 additions & 4 deletions pkg/server/middleware/cors/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package cors

import (
"net/http"
"slices"
"strconv"
"strings"

Expand All @@ -38,13 +39,22 @@ func (o *Options) AddFlags(f *pflag.FlagSet) {
f.IntVar(&o.MaxAge, "cors-max-age", 86400, "CORS maximum age (may be overridden by the browser)")
}

func setAllowOrigin(w http.ResponseWriter, r *http.Request, allowedOrigins []string) {
if origin := r.Header.Get("Origin"); origin != "" {
if index := slices.IndexFunc(allowedOrigins, func(s string) bool { return s == origin }); index >= 0 {
w.Header().Add("Access-Control-Allow-Origin", origin)
return
}
}

w.Header().Add("Access-Control-Allow-Origin", allowedOrigins[0])
}

func Middleware(schema *openapi.Schema, options *Options) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// All requests get the allow origin header.
for _, origin := range options.AllowedOrigins {
w.Header().Add("Access-Control-Allow-Origin", origin)
}
// All requests get the allow origin header. BUT only one!
setAllowOrigin(w, r, options.AllowedOrigins)

// For normal requests handle them.
if r.Method != http.MethodOptions {
Expand Down

0 comments on commit fb0e128

Please sign in to comment.