Skip to content

Commit

Permalink
Merge pull request #67 from westwind-sc/negotiateContentType_default_…
Browse files Browse the repository at this point in the history
…first

Fix negotiateContentType , if not match, the default should used
  • Loading branch information
qiangxue authored Sep 4, 2021
2 parents cc9c25a + b3e74f1 commit 486266b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
6 changes: 3 additions & 3 deletions content/negotiator.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func NegotiateContentType(r *http.Request, offers []string, defaultOffer string)

func negotiateContentType(accepts []AcceptRange, offers []AcceptRange, defaultOffer AcceptRange) string {
best := defaultOffer.RawString()
bestWeight := float64(0)
bestWeight := defaultOffer.Weight
bestParams := 0

for _, offer := range offers {
Expand All @@ -155,10 +155,10 @@ func negotiateContentType(accepts []AcceptRange, offers []AcceptRange, defaultOf

if bestWeight > (accept.Weight + booster) {
continue // we already have something better..
} else if accept.Type == "*" && accept.Subtype == "*" {
} else if accept.Type == "*" && accept.Subtype == "*" && ((accept.Weight + booster) > bestWeight) {
best = offer.RawString()
bestWeight = accept.Weight + booster
} else if accept.Subtype == "*" && offer.Type == accept.Type {
} else if accept.Subtype == "*" && offer.Type == accept.Type && ((accept.Weight + booster) > bestWeight) {
best = offer.RawString()
bestWeight = accept.Weight + booster
} else if accept.Type == offer.Type && accept.Subtype == offer.Subtype {
Expand Down
19 changes: 19 additions & 0 deletions content/negotiator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ func TestContentNegotiation3(t *testing.T) {
assert.Equal(t, "application/xml", format)
}

func TestContentNegotiation4(t *testing.T) {
header := http.Header{}
header.Set("Accept", "*/*")
req := &http.Request{Header: header}

offers := []string{"application/json", "application/xml"}
format := NegotiateContentType(req, offers, "application/json")
assert.Equal(t, "application/json", format)
}

func TestContentNegotiation5(t *testing.T) {
header := http.Header{}
header.Set("Accept", "*/*")
req := &http.Request{Header: header}

offers := []string{"application/json", "application/xml", "application/json;v=1", "application/json;v=2"}
format := NegotiateContentType(req, offers, "text/html")
assert.Equal(t, "text/html", format)
}
func TestAccept(t *testing.T) {
header := http.Header{}
header.Set("Accept", "application/json; q=1 ; v=1,")
Expand Down

0 comments on commit 486266b

Please sign in to comment.