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