-
-
Notifications
You must be signed in to change notification settings - Fork 123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to upload files and forms with huma? #28
Comments
For non structured (not JSON/CBOR) input you can use an input byte stream, see https://github.com/danielgtaylor/huma#input-streaming. Example: app.Resource("/stream").Post("stream-example", "docs...",
responses.Created(),
responses.InternalServerError(),
).Run(func(ctx huma.Context, input struct {
ContentType string `header:"Content-Type"`
Body io.Reader
}) {
contents, err := ioutil.ReadAll(input.Body)
if err != nil {
ctx.WriteError(http.StatusInternalServerError, "Error reading input")
return
}
fmt.Printf("Got %s input: %s\n", input.ContentType, string(contents))
ctx.WriteHeader(http.StatusNoContent)
}) This can be called like: # Curl example:
$ curl -XPOST :8888/stream -H 'Content-Type: my/custom-type' -d 'this is a test'
# Restish example:
$ echo 'this is a test' | restish post :8888/stream -H 'Content-Type: my/custom-type' As for forms, type FormInput struct {
Form url.Values
}
func (f *FormInput) Resolve(ctx huma.Context, r *http.Request) {
// TODO: Determine if the form should be parsed or not
r.ParseForm()
f.Form = r.PostForm
} Then use Also don't forget to set the request body size limit appropriately for your expected input sizes. |
Thank you for patient reply. I can now upload files from Postman with io.Reader, but it seams that is no button for file upload on Swagger UI. |
Interesting, this isn't something I've had to handle before from the generated docs UI. It looks like it is possible to convince Swagger UI to show the button, e.g. see https://swagger.io/docs/specification/describing-request-body/file-upload/. Huma doesn't directly support setting that up via struct tags, but you can experiment with https://github.com/danielgtaylor/huma/#custom-openapi-fields to get it working. I'm open to ideas how to make this easier within Huma itself since it looks like both Swagger UI and RapiDoc seem to support the feature. What's the ideal way to make this work? |
No description provided.
The text was updated successfully, but these errors were encountered: