cors/utils.go
Manu Mtz.-Almeida b08ec4416c Fixes CORS
2015-11-12 01:17:15 +01:00

70 lines
1.7 KiB
Go

package cors
import (
"net/http"
"strconv"
"strings"
"time"
)
func generateNormalHeaders(c Config) http.Header {
headers := make(http.Header)
if c.AllowCredentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
if len(c.ExposedHeaders) > 0 {
exposedHeaders := normalize(c.ExposedHeaders)
headers.Set("Access-Control-Expose-Headers", strings.Join(exposedHeaders, ", "))
}
if c.AllowAllOrigins {
headers.Set("Access-Control-Allow-Origin", "*")
} else {
headers.Set("Vary", "Origin")
}
return headers
}
func generatePreflightHeaders(c Config) http.Header {
headers := make(http.Header)
if c.AllowCredentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
if len(c.AllowedMethods) > 0 {
allowedMethods := normalize(c.AllowedMethods)
value := strings.Join(allowedMethods, ", ")
headers.Set("Access-Control-Allow-Methods", value)
}
if len(c.AllowedHeaders) > 0 {
allowedHeaders := normalize(c.AllowedHeaders)
value := strings.Join(allowedHeaders, ", ")
headers.Set("Access-Control-Allow-Headers", value)
}
if c.MaxAge > time.Duration(0) {
value := strconv.FormatInt(int64(c.MaxAge/time.Second), 10)
headers.Set("Access-Control-Max-Age", value)
}
if c.AllowAllOrigins {
headers.Set("Access-Control-Allow-Origin", "*")
} else {
headers.Set("Vary", "Origin")
}
return headers
}
func normalize(values []string) []string {
if values == nil {
return nil
}
distinctMap := make(map[string]bool, len(values))
normalized := make([]string, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
value = strings.ToLower(value)
if _, seen := distinctMap[value]; !seen {
normalized = append(normalized, value)
distinctMap[value] = true
}
}
return normalized
}