MCPcopy
hub / github.com/danielgtaylor/huma / transformAndWrite

Function transformAndWrite

huma.go:601–638  ·  view source on GitHub ↗

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.

(api API, ctx Context, status int, ct string, body any)

Source from the content-addressed store, hash-verified

599// transformAndWrite is a utility function to transform and write a response.
600// It is best-effort as the status code and headers may have already been sent.
601func transformAndWrite(api API, ctx Context, status int, ct string, body any) error {
602 // Try to transform and then marshal/write the response.
603 // Status code was already sent, so just log the error if something fails,
604 // and do our best to stuff it into the body of the response.
605 statusStr, ok := statusStrings[status]
606 if !ok {
607 statusStr = strconv.Itoa(status)
608 }
609
610 tVal, tErr := api.Transform(ctx, statusStr, body)
611 if tErr != nil {
612 ctx.SetStatus(status)
613 ctx.BodyWriter().Write([]byte("error transforming response"))
614 // When including tVal in the panic message, the server may become unresponsive for some time if the value is very large
615 // therefore, it has been removed from the panic message
616 return fmt.Errorf("error transforming response for %s %s %d: %w", ctx.Operation().Method, ctx.Operation().Path, status, tErr)
617 }
618
619 ctx.SetStatus(status)
620
621 if status != http.StatusNoContent && status != http.StatusNotModified {
622 if mErr := api.Marshal(ctx.BodyWriter(), ct, tVal); mErr != nil {
623 if errors.Is(ctx.Context().Err(), context.Canceled) {
624 // The client disconnected, so don't bother writing anything. Attempt
625 // to set the status in case it'll get logged. Technically, this was
626 // not a normal successful request.
627 ctx.SetStatus(499)
628 return nil
629 }
630 ctx.BodyWriter().Write([]byte("error marshaling response"))
631 // When including tVal in the panic message, the server may become unresponsive for some time if the value is very large
632 // therefore, it has been removed from the panic message
633 return fmt.Errorf("error marshaling response for %s %s %d: %w", ctx.Operation().Method, ctx.Operation().Path, status, mErr)
634 }
635 }
636
637 return nil
638}
639
640func parseArrElement[T any](values []string, parse func(string) (T, error)) ([]T, error) {
641 result := make([]T, 0, len(values))

Callers 1

writeResponseFunction · 0.85

Calls 7

TransformMethod · 0.65
SetStatusMethod · 0.65
BodyWriterMethod · 0.65
OperationMethod · 0.65
MarshalMethod · 0.65
ContextMethod · 0.65
WriteMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…