github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/http/header-accept.go (about) 1 /* For license and copyright information please see LEGAL file in repository */ 2 3 package http 4 5 import ( 6 "strconv" 7 "strings" 8 ) 9 10 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 11 type mime struct { 12 media string 13 quality float64 14 } 15 16 // insertMime adds a mime to a list and keeps it sorted by quality. 17 func insertMime(l []mime, e mime) []mime { 18 for i, each := range l { 19 // if current mime has lower quality then insert before 20 if e.quality > each.quality { 21 left := append([]mime{}, l[0:i]...) 22 return append(append(left, e), l[i:]...) 23 } 24 } 25 return append(l, e) 26 } 27 28 // sortMimes returns a list of mime sorted (desc) by its specified quality. 29 func sortMimes(accept string) (sorted []mime) { 30 for _, each := range strings.Split(accept, ",") { 31 typeAndQuality := strings.Split(strings.Trim(each, " "), ";") 32 if len(typeAndQuality) == 1 { 33 sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0}) 34 } else { 35 // take factor 36 parts := strings.Split(typeAndQuality[1], "=") 37 if len(parts) == 2 { 38 f, err := strconv.ParseFloat(parts[1], 64) 39 if err != nil { 40 // traceLogger.Printf("unable to parse quality in %s, %v", each, err) 41 } else { 42 sorted = insertMime(sorted, mime{typeAndQuality[0], f}) 43 } 44 } 45 } 46 } 47 return 48 }