Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 1 | package restful |
| 2 | |
| 3 | import ( |
| 4 | "strconv" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | type mime struct { |
| 9 | media string |
| 10 | quality float64 |
| 11 | } |
| 12 | |
| 13 | // insertMime adds a mime to a list and keeps it sorted by quality. |
| 14 | func insertMime(l []mime, e mime) []mime { |
| 15 | for i, each := range l { |
| 16 | // if current mime has lower quality then insert before |
| 17 | if e.quality > each.quality { |
| 18 | left := append([]mime{}, l[0:i]...) |
| 19 | return append(append(left, e), l[i:]...) |
| 20 | } |
| 21 | } |
| 22 | return append(l, e) |
| 23 | } |
| 24 | |
| 25 | // sortedMimes returns a list of mime sorted (desc) by its specified quality. |
| 26 | func sortedMimes(accept string) (sorted []mime) { |
| 27 | for _, each := range strings.Split(accept, ",") { |
| 28 | typeAndQuality := strings.Split(strings.Trim(each, " "), ";") |
| 29 | if len(typeAndQuality) == 1 { |
| 30 | sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0}) |
| 31 | } else { |
| 32 | // take factor |
| 33 | parts := strings.Split(typeAndQuality[1], "=") |
| 34 | if len(parts) == 2 { |
| 35 | f, err := strconv.ParseFloat(parts[1], 64) |
| 36 | if err != nil { |
| 37 | traceLogger.Printf("unable to parse quality in %s, %v", each, err) |
| 38 | } else { |
| 39 | sorted = insertMime(sorted, mime{typeAndQuality[0], f}) |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | return |
| 45 | } |