Skip to content

Commit

Permalink
feat: force encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
abemedia committed May 15, 2023
1 parent 5759715 commit 426a000
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 426a000

Please sign in to comment.