66 "errors"
77 "fmt"
88 "io"
9+ "mime"
910 "net"
1011 "net/http"
1112 "strings"
@@ -179,6 +180,11 @@ func newHTTPJSONRequest(r *http.Request, body []byte) *Request {
179180}
180181
181182func newAPIGatewayV2Request (r * http.Request , body []byte ) * APIGatewayV2Request {
183+ encoded := requestBodyIsBase64Encoded (r , body )
184+ requestBody := string (body )
185+ if encoded {
186+ requestBody = base64 .StdEncoding .EncodeToString (body )
187+ }
182188 return & APIGatewayV2Request {
183189 Version : "2.0" ,
184190 RouteKey : "$default" ,
@@ -200,8 +206,8 @@ func newAPIGatewayV2Request(r *http.Request, body []byte) *APIGatewayV2Request {
200206 UserAgent : r .UserAgent (),
201207 },
202208 },
203- Body : apiGatewayV2Body ( r , body ) ,
204- IsBase64Encoded : requestBodyIsBase64Encoded ( r , body ) ,
209+ Body : requestBody ,
210+ IsBase64Encoded : encoded ,
205211 }
206212}
207213
@@ -286,26 +292,31 @@ func requestDomainName(r *http.Request) string {
286292 return r .Host
287293}
288294
289- func apiGatewayV2Body (r * http.Request , body []byte ) string {
290- if requestBodyIsBase64Encoded (r , body ) {
291- return base64 .StdEncoding .EncodeToString (body )
292- }
293- return string (body )
294- }
295-
296295func requestBodyIsBase64Encoded (r * http.Request , body []byte ) bool {
297296 if len (body ) == 0 {
298297 return false
299298 }
300- contentType := r .Header .Get ("Content-Type" )
301- if strings .HasPrefix (contentType , "text/" ) || strings .HasPrefix (contentType , "application/json" ) ||
302- strings .HasPrefix (contentType , "application/javascript" ) || strings .HasPrefix (contentType , "application/xml" ) ||
303- strings .HasPrefix (contentType , "application/x-www-form-urlencoded" ) {
299+ contentType := strings .ToLower (r .Header .Get ("Content-Type" ))
300+ mediaType , _ , err := mime .ParseMediaType (contentType )
301+ if err != nil {
302+ mediaType = strings .TrimSpace (strings .SplitN (contentType , ";" , 2 )[0 ])
303+ }
304+ if isTextualMediaType (mediaType ) {
304305 return false
305306 }
306307 return ! utf8 .Valid (body ) || contentType != ""
307308}
308309
310+ func isTextualMediaType (mediaType string ) bool {
311+ return strings .HasPrefix (mediaType , "text/" ) ||
312+ mediaType == "application/json" || strings .HasSuffix (mediaType , "+json" ) ||
313+ mediaType == "application/javascript" ||
314+ mediaType == "application/xml" || strings .HasSuffix (mediaType , "+xml" ) ||
315+ mediaType == "application/x-www-form-urlencoded" ||
316+ mediaType == "application/x-ndjson" ||
317+ mediaType == "application/graphql"
318+ }
319+
309320// APIGatewayV2Request is the HTTP API payload format consumed by Mangum.
310321type APIGatewayV2Request struct {
311322 Version string `json:"version"`
0 commit comments