huma icon indicating copy to clipboard operation
huma copied to clipboard

How to upload files and forms with huma?

Open ljg-cqu opened this issue 2 years ago • 3 comments

ljg-cqu avatar Mar 05 '22 07:03 ljg-cqu

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, http.Request.Form is not currently exposed, but you can access it via an input resolver:

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 FormInput to compose your input params and you should be able to access input.Form.

Also don't forget to set the request body size limit appropriately for your expected input sizes.

danielgtaylor avatar Mar 05 '22 18:03 danielgtaylor

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.

ljg-cqu avatar Mar 06 '22 06:03 ljg-cqu

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?

danielgtaylor avatar Mar 06 '22 22:03 danielgtaylor