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

Method Transform

transforms.go:157–236  ·  view source on GitHub ↗

Transform is called for every response to add the `$schema` field and/or the Link header pointing to the JSON Schema.

(ctx Context, _ string, v any)

Source from the content-addressed store, hash-verified

155// Transform is called for every response to add the `$schema` field and/or
156// the Link header pointing to the JSON Schema.
157func (t *SchemaLinkTransformer) Transform(ctx Context, _ string, v any) (any, error) {
158 vv := reflect.ValueOf(v)
159 if vv.Kind() == reflect.Pointer && vv.IsNil() {
160 return v, nil
161 }
162
163 typ := deref(reflect.TypeOf(v))
164
165 if typ.Kind() != reflect.Struct {
166 return v, nil
167 }
168
169 infos := t.types[typ]
170 if len(infos) == 0 {
171 return v, nil
172 }
173
174 info := infos[0]
175 if len(infos) > 1 {
176 // More than one schema link for this type, try to find the one that
177 // matches the current operation.
178 op := ctx.Operation()
179 if op != nil {
180 opID := op.OperationID
181 for _, i := range infos {
182 if i.opID == opID {
183 info = i
184 break
185 }
186 }
187 }
188 }
189
190 ctx.AppendHeader("Link", info.header)
191 tmp := reflect.New(info.t).Elem()
192
193 // Set the `$schema` field.
194 schemaURL := getSchemaHost(ctx)
195
196 if schemaURL == "" || strings.HasPrefix(schemaURL, "localhost") {
197 if t.oapi != nil && len(t.oapi.Servers) > 0 && t.oapi.Servers[0].URL != "" {
198 serverURL := t.oapi.Servers[0].URL
199 if !strings.HasPrefix(serverURL, "/") {
200 schemaURL = serverURL
201 }
202 }
203 if schemaURL == "" {
204 schemaURL = "localhost"
205 }
206 }
207
208 buf := bufPool.Get().(*bytes.Buffer)
209 if !strings.Contains(schemaURL, "://") {
210 if ctx.TLS() == nil && (strings.HasPrefix(schemaURL, "localhost") || strings.HasPrefix(schemaURL, "127.0.0.1")) {
211 buf.WriteString("http://")
212 } else {
213 buf.WriteString("https://")
214 }

Callers

nothing calls this directly

Calls 9

getSchemaHostFunction · 0.85
derefFunction · 0.70
OperationMethod · 0.65
AppendHeaderMethod · 0.65
GetMethod · 0.65
TLSMethod · 0.65
PutMethod · 0.65
StringMethod · 0.45
ResetMethod · 0.45

Tested by

no test coverage detected