Skip to content

Commit 3f53fd0

Browse files
authored
fix(encoding): take the first encoding supported (#205)
* fix the encoder to take the first encoding supported * add encoder tests
1 parent b453166 commit 3f53fd0

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

encoding/encode.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package encoding
22

33
import (
44
"context"
5+
"strings"
56

67
"github.com/valyala/fasthttp"
78
)
@@ -50,7 +51,13 @@ func RegisterEncoder[T EncoderConstraint](enc T, mime string, aliases ...string)
5051

5152
// GetEncoder returns the response encoder for a given media type.
5253
func GetEncoder(mime string) ResponseEncoder {
53-
return encoders[mime]
54+
mimeParts := strings.Split(mime, ",")
55+
for _, part := range mimeParts {
56+
if enc, ok := encoders[part]; ok {
57+
return enc
58+
}
59+
}
60+
return nil
5461
}
5562

5663
var encoders = map[string]ResponseEncoder{}

encoding/encode_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,21 @@ func testRegisterEncoder[T encoding.EncoderConstraint](t *testing.T, dec T, cont
6868
}
6969
}
7070
}
71+
72+
func TestGetEncoderMultipleContentTypes(t *testing.T) {
73+
encFn := func(ctx *fasthttp.RequestCtx, v any) error {
74+
return nil
75+
}
76+
77+
encoding.RegisterEncoder(encFn, "application/xml")
78+
79+
enc := encoding.GetEncoder("text/html,application/xhtml+xml,application/xml")
80+
if enc == nil {
81+
t.Fatal("encoder not found")
82+
}
83+
84+
enc = encoding.GetEncoder("application/xhtml+xml")
85+
if enc != nil {
86+
t.Fatal("encoder should not be found")
87+
}
88+
}

0 commit comments

Comments
 (0)