blob: d7ea2b6157949919619c67ac90ff9c496fb6cf0c [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001package restful
2
3import (
4 "strconv"
5 "strings"
6)
7
8type mime struct {
9 media string
10 quality float64
11}
12
13// insertMime adds a mime to a list and keeps it sorted by quality.
14func 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.
26func 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}