Skip to content

Commit

Permalink
refactor: minor refactor to prevent casting
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgtaylor committed Nov 12, 2024
1 parent 6e14830 commit f628ea0
Showing 1 changed file with 12 additions and 23 deletions.
35 changes: 12 additions & 23 deletions huma.go
Original file line number Diff line number Diff line change
Expand Up @@ -465,20 +465,22 @@ var bufPool = sync.Pool{

func writeResponse(api API, ctx Context, status int, ct string, body any) error {
if ct == "" {
// If no content type was provided, try to negotiate one with the client.
var err error
ct, err = getContentType(api, ctx, body)
ct, err = api.Negotiate(ctx.Header("Accept"))
if err != nil {
// Couldn't negotiate a content type, so return an error. This is best
// effort and we default to JSON. This prevents loops that would result
// from calling `WriteErr`.
status := http.StatusInternalServerError
if se, ok := err.(StatusError); ok {
status = se.GetStatus()
}
if err := transformAndWrite(api, ctx, status, "application/json", err); err != nil {
return err
notAccept := NewErrorWithContext(ctx, http.StatusNotAcceptable, "unable to marshal response", err)
if e := transformAndWrite(api, ctx, http.StatusNotAcceptable, "application/json", notAccept); e != nil {
return e
}
return err
}

Check warning on line 477 in huma.go

View check run for this annotation

Codecov / codecov/patch

huma.go#L477

Added line #L477 was not covered by tests

if ctf, ok := body.(ContentTypeFilter); ok {
ct = ctf.ContentType(ct)
}

ctx.SetHeader("Content-Type", ct)
}

if err := transformAndWrite(api, ctx, status, ct, body); err != nil {
Expand All @@ -493,19 +495,6 @@ func writeResponseWithPanic(api API, ctx Context, status int, ct string, body an
}
}

func getContentType(api API, ctx Context, body any) (string, error) {
ct, err := api.Negotiate(ctx.Header("Accept"))
if err != nil {
return "", NewErrorWithContext(ctx, http.StatusNotAcceptable, "unable to marshal response", err)
}
if ctf, ok := body.(ContentTypeFilter); ok {
ct = ctf.ContentType(ct)
}

ctx.SetHeader("Content-Type", ct)
return ct, nil
}

// transformAndWrite is a utility function to transform and write a response.
// It is best-effort as the status code and headers may have already been sent.
func transformAndWrite(api API, ctx Context, status int, ct string, body any) error {
Expand Down

0 comments on commit f628ea0

Please sign in to comment.