summaryrefslogtreecommitdiff
path: root/vendor/github.com/xlgmokha/x/pkg/serde/media.go
blob: 5d108dcc361ba996926eaf75d0e49be491466fcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package serde

import (
	"mime"
	"sort"
	"strconv"
	"strings"

	"github.com/google/jsonapi"
)

type MediaType string

const (
	JSONAPI MediaType = jsonapi.MediaType
	JSON    MediaType = "application/json"
	Text    MediaType = "text/plain"
	YAML    MediaType = "application/yaml"
	Default MediaType = JSON
)

func (self MediaType) String() string {
	return string(self)
}

func MediaTypeFor(value string) MediaType {
	mediaTypes := sortedByQualityValues(strings.Split(value, ","))

	for _, mediaType := range mediaTypes {
		switch mediaType {
		case jsonapi.MediaType:
			return JSONAPI
		case "application/json":
			return JSON
		case "text/plain":
			return Text
		default:
			continue
		}
	}
	return Default
}

func sortedByQualityValues(mimeTypes []string) []string {
	weights := map[string]float64{}
	valid := []string{}

	for i, mimeType := range mimeTypes {
		if mtype, params, err := mime.ParseMediaType(mimeType); err == nil {
			valid = append(valid, mtype)
			if _, ok := weights[mtype]; !ok {
				weights[mtype] = 1.0 - (0.1 * float64(i))
			}
			if quality, ok := params["q"]; ok {
				if val, err := strconv.ParseFloat(quality, 64); err == nil {
					weights[mtype] = val
				}
			}
		}
	}
	sort.Slice(valid, func(x, y int) bool {
		xWeight := weights[valid[x]]
		yWeight := weights[valid[y]]
		return xWeight > yWeight
	})
	return valid
}