utils.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package cors
  2. import "strings"
  3. const toLower = 'a' - 'A'
  4. type converter func(string) string
  5. type wildcard struct {
  6. prefix string
  7. suffix string
  8. }
  9. func (w wildcard) match(s string) bool {
  10. return len(s) >= len(w.prefix+w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix)
  11. }
  12. // convert converts a list of string using the passed converter function
  13. func convert(s []string, c converter) []string {
  14. out := []string{}
  15. for _, i := range s {
  16. out = append(out, c(i))
  17. }
  18. return out
  19. }
  20. // parseHeaderList tokenize + normalize a string containing a list of headers
  21. func parseHeaderList(headerList string) []string {
  22. l := len(headerList)
  23. h := make([]byte, 0, l)
  24. upper := true
  25. // Estimate the number headers in order to allocate the right splice size
  26. t := 0
  27. for i := 0; i < l; i++ {
  28. if headerList[i] == ',' {
  29. t++
  30. }
  31. }
  32. headers := make([]string, 0, t)
  33. for i := 0; i < l; i++ {
  34. b := headerList[i]
  35. if b >= 'a' && b <= 'z' {
  36. if upper {
  37. h = append(h, b-toLower)
  38. } else {
  39. h = append(h, b)
  40. }
  41. } else if b >= 'A' && b <= 'Z' {
  42. if !upper {
  43. h = append(h, b+toLower)
  44. } else {
  45. h = append(h, b)
  46. }
  47. } else if b == '-' || b == '_' || (b >= '0' && b <= '9') {
  48. h = append(h, b)
  49. }
  50. if b == ' ' || b == ',' || i == l-1 {
  51. if len(h) > 0 {
  52. // Flush the found header
  53. headers = append(headers, string(h))
  54. h = h[:0]
  55. upper = true
  56. }
  57. } else {
  58. upper = b == '-' || b == '_'
  59. }
  60. }
  61. return headers
  62. }