Skip to content

图像响应#

图像或其他编码或二进制响应可以通过简单地使用 []byte 正文并在操作注册时提供一些额外信息来返回,例如响应正文的内容类型。

示例#

code.go
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humachi"
	"github.com/danielgtaylor/huma/v2/humacli"
	"github.com/go-chi/chi/v5"
)

// CLI 的选项。
type Options struct {
	Port int `help:"监听端口" short:"p" default:"8888"`
}

// ImageOutput 表示图像操作响应。
type ImageOutput struct {
	ContentType string `header:"Content-Type"`
	Body        []byte
}

func main() {
	// 创建一个接受端口选项的 CLI 应用。
	cli := humacli.New(func(hooks humacli.Hooks, options *Options) {
		// 创建一个新的路由器和 API
		router := chi.NewMux()
		api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))

		// 注册 GET /image
		huma.Register(api, huma.Operation{
			OperationID: "get-image",
			Summary:     "获取图像",
			Method:      http.MethodGet,
			Path:        "/image",
			Responses: map[string]*huma.Response{
				"200": {
					Description: "图像响应",
					Content: map[string]*huma.MediaType{
						"image/jpeg": {},
					},
				},
			},
		}, func(ctx context.Context, input *struct{}) (*ImageOutput, error) {
			resp := &ImageOutput{}
			resp.ContentType = "image/png"
			resp.Body = []byte{ /* ... 图像字节在这里 ... */ }
			return resp, nil
		})

		// 告诉 CLI 如何启动服务器。
		hooks.OnStart(func() {
			fmt.Printf("在端口 %d 上启动服务器...\n", options.Port)
			http.ListenAndServe(fmt.Sprintf(":%d", options.Port), router)
		})
	})

	// 运行 CLI。如果没有传递命令,它会启动服务器。
	cli.Run()
}