diff --git a/api.go b/api.go index 7e34b2b..debc0a8 100644 --- a/api.go +++ b/api.go @@ -46,6 +46,8 @@ type Config struct { // DisableNoContent controls whether a nil or zero value response should // automatically return 204 No Content with an empty body. DisableNoContent bool + + ForceDefaultEncoding bool } // New creates a new API instance. @@ -126,24 +128,30 @@ func (r *API) RequestHandler() fasthttp.RequestHandler { } return func(ctx *fasthttp.RequestCtx) { - ct := ctx.Request.Header.ContentType() - if len(ct) == 0 || bytes.HasPrefix(ct, anyEncoding) { - ctx.Request.Header.SetContentType(r.config.DefaultEncoding) - } + contentType := ctx.Request.Header.ContentType() + accept := ctx.Request.Header.Peek(fasthttp.HeaderAccept) - ac := ctx.Request.Header.Peek(fasthttp.HeaderAccept) - if len(ac) == 0 || bytes.HasPrefix(ac, anyEncoding) { + if r.config.ForceDefaultEncoding { + ctx.Request.Header.SetContentType(r.config.DefaultEncoding) ctx.Request.Header.Set(fasthttp.HeaderAccept, r.config.DefaultEncoding) + } else { + if len(contentType) == 0 || bytes.HasPrefix(contentType, anyEncoding) { + ctx.Request.Header.SetContentType(r.config.DefaultEncoding) + } + if len(accept) == 0 || bytes.HasPrefix(accept, anyEncoding) { + ctx.Request.Header.Set(fasthttp.HeaderAccept, r.config.DefaultEncoding) + } } h(ctx) // Content-Length of -3 means handler returned nil. if ctx.Response.Header.ContentLength() == -3 { - ctx.Response.Header.SetContentLength(0) - - if !r.config.DisableNoContent { - ctx.Response.SetBody(nil) + if r.config.DisableNoContent { + ctx.Response.Header.SetContentLength(len(ctx.Request.Body())) + } else { + ctx.Response.Header.SetContentLength(0) + ctx.Response.ResetBody() if ctx.Response.StatusCode() == fasthttp.StatusOK { ctx.Response.SetStatusCode(fasthttp.StatusNoContent)