utils.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package cors
  2. import (
  3. "net/http"
  4. "strconv"
  5. "strings"
  6. "time"
  7. )
  8. func generateNormalHeaders(c Config) http.Header {
  9. headers := make(http.Header)
  10. if c.AllowCredentials {
  11. headers.Set("Access-Control-Allow-Credentials", "true")
  12. }
  13. if len(c.ExposeHeaders) > 0 {
  14. exposeHeaders := normalize(c.ExposeHeaders)
  15. headers.Set("Access-Control-Expose-Headers", strings.Join(exposeHeaders, ","))
  16. }
  17. if c.AllowAllOrigins {
  18. headers.Set("Access-Control-Allow-Origin", "*")
  19. } else {
  20. headers.Set("Vary", "Origin")
  21. }
  22. return headers
  23. }
  24. func generatePreflightHeaders(c Config) http.Header {
  25. headers := make(http.Header)
  26. if c.AllowCredentials {
  27. headers.Set("Access-Control-Allow-Credentials", "true")
  28. }
  29. if len(c.AllowMethods) > 0 {
  30. allowMethods := normalize(c.AllowMethods)
  31. value := strings.Join(allowMethods, ",")
  32. headers.Set("Access-Control-Allow-Methods", value)
  33. }
  34. if len(c.AllowHeaders) > 0 {
  35. allowHeaders := normalize(c.AllowHeaders)
  36. value := strings.Join(allowHeaders, ",")
  37. headers.Set("Access-Control-Allow-Headers", value)
  38. }
  39. if c.MaxAge > time.Duration(0) {
  40. value := strconv.FormatInt(int64(c.MaxAge/time.Second), 10)
  41. headers.Set("Access-Control-Max-Age", value)
  42. }
  43. if c.AllowAllOrigins {
  44. headers.Set("Access-Control-Allow-Origin", "*")
  45. } else {
  46. headers.Set("Vary", "Origin")
  47. }
  48. return headers
  49. }
  50. func normalize(values []string) []string {
  51. if values == nil {
  52. return nil
  53. }
  54. distinctMap := make(map[string]bool, len(values))
  55. normalized := make([]string, 0, len(values))
  56. for _, value := range values {
  57. value = strings.TrimSpace(value)
  58. value = strings.ToLower(value)
  59. if _, seen := distinctMap[value]; !seen {
  60. normalized = append(normalized, value)
  61. distinctMap[value] = true
  62. }
  63. }
  64. return normalized
  65. }