podman
98 строк · 2.7 Кб
1// Copyright 2013 The Go Authors. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd.
6
7// this file was taken from the github.com/golang/gddo repository
8
9package middleware
10
11import (
12"net/http"
13"strings"
14
15"github.com/go-openapi/runtime/middleware/header"
16)
17
18// NegotiateContentEncoding returns the best offered content encoding for the
19// request's Accept-Encoding header. If two offers match with equal weight and
20// then the offer earlier in the list is preferred. If no offers are
21// acceptable, then "" is returned.
22func NegotiateContentEncoding(r *http.Request, offers []string) string {
23bestOffer := "identity"
24bestQ := -1.0
25specs := header.ParseAccept(r.Header, "Accept-Encoding")
26for _, offer := range offers {
27for _, spec := range specs {
28if spec.Q > bestQ &&
29(spec.Value == "*" || spec.Value == offer) {
30bestQ = spec.Q
31bestOffer = offer
32}
33}
34}
35if bestQ == 0 {
36bestOffer = ""
37}
38return bestOffer
39}
40
41// NegotiateContentType returns the best offered content type for the request's
42// Accept header. If two offers match with equal weight, then the more specific
43// offer is preferred. For example, text/* trumps */*. If two offers match
44// with equal weight and specificity, then the offer earlier in the list is
45// preferred. If no offers match, then defaultOffer is returned.
46func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string {
47bestOffer := defaultOffer
48bestQ := -1.0
49bestWild := 3
50specs := header.ParseAccept(r.Header, "Accept")
51for _, rawOffer := range offers {
52offer := normalizeOffer(rawOffer)
53// No Accept header: just return the first offer.
54if len(specs) == 0 {
55return rawOffer
56}
57for _, spec := range specs {
58switch {
59case spec.Q == 0.0:
60// ignore
61case spec.Q < bestQ:
62// better match found
63case spec.Value == "*/*":
64if spec.Q > bestQ || bestWild > 2 {
65bestQ = spec.Q
66bestWild = 2
67bestOffer = rawOffer
68}
69case strings.HasSuffix(spec.Value, "/*"):
70if strings.HasPrefix(offer, spec.Value[:len(spec.Value)-1]) &&
71(spec.Q > bestQ || bestWild > 1) {
72bestQ = spec.Q
73bestWild = 1
74bestOffer = rawOffer
75}
76default:
77if spec.Value == offer &&
78(spec.Q > bestQ || bestWild > 0) {
79bestQ = spec.Q
80bestWild = 0
81bestOffer = rawOffer
82}
83}
84}
85}
86return bestOffer
87}
88
89func normalizeOffers(orig []string) (norm []string) {
90for _, o := range orig {
91norm = append(norm, normalizeOffer(o))
92}
93return
94}
95
96func normalizeOffer(orig string) string {
97return strings.SplitN(orig, ";", 2)[0]
98}
99