Huma:一个现代化的Go微框架

Huma是一个为Go语言设计的现代化、简单、快速且灵活的微框架,用于构建HTTP REST/RPC API。它支持OpenAPI 3和JSON Schema,旨在为开发者提供一个高效的后端API开发环境。

Huma的主要特点

  • 灵活性:支持自定义路由器(如Go 1.22+的标准库路由器)、中间件和日志/指标系统。
  • 文档生成:自动根据OpenAPI和JSON Schema生成文档,确保文档始终与代码同步。
  • 错误处理:使用RFC 9457和application/problem+json格式处理错误。
  • 内容协商:支持JSON和CBOR格式的内容协商。
  • 条件请求:支持If-Match或If-Unmodified-Since等条件请求头。
  • PATCH操作:支持RFC 7386 JSON Merge Patch和RFC 6902 JSON Patch。
  • 静态类型:支持静态类型的路径、查询、头部参数、请求体等。
  • 自动验证:自动验证输入模型并处理错误。

安装Huma

要使用Huma,首先需要安装Go 1.21或更高版本,然后使用以下命令安装Huma:

arduino 复制代码
bash
go get -u github.com/danielgtaylor/huma/v2

基本示例

以下是一个简单的"Hello World"示例,展示如何使用Huma创建一个API:

go 复制代码
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"

	_ "github.com/danielgtaylor/huma/v2/formats/cbor"
)

// CLI选项
type Options struct {
	Port int `help:"Port to listen on" short:"p" default:"8888"`
}

// 响应结构体
type GreetingOutput struct {
	Body struct {
		Message string `json:"message" example:"Hello, world!" doc:"Greeting message"`
	}
}

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"))

		// 添加操作处理函数
		huma.Get(api, "/greeting/{name}", func(ctx context.Context, input *struct {
			Name string `path:"name" maxLength:"30" example:"world" doc:"Name to greet"`
		}) (*GreetingOutput, error) {
			resp := &GreetingOutput{}
			resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
			return resp, nil
		})

		// 启动服务器
		hooks.OnStart(func() {
			http.ListenAndServe(fmt.Sprintf(":%d", options.Port), router)
		})
	})

	// 运行CLI
	cli.Run()
}

测试API

使用以下命令运行示例:

go 复制代码
bash
go run greet.go

然后,可以使用Restish或curl测试API:

bash 复制代码
bash
restish :8888/greeting/world

文档和OpenAPI

访问http://localhost:8888/docs查看生成的文档,访问http://localhost:8888/openapi.jsonhttp://localhost:8888/openapi.yaml查看OpenAPI定义。

使用标准库路由器

如果你使用Go 1.22或更高版本,可以通过以下方式切换到标准库路由器:

css 复制代码
go
router := http.NewServeMux()
api := humago.New(router, huma.DefaultConfig("My API", "1.0.0"))

确保你的go.mod文件中指定了Go 1.22或更高版本。

相关推荐
学长毕业设计12 分钟前
基于SpringBoot的民间艺术传承管理系统(源码+文档+讲解视频)
java·spring boot·后端
小蒜学长12 分钟前
基于Springboot+Vue的环保行动志愿者招募系统设计与实现(代码+数据库+LW)
java·数据库·vue.js·spring boot·后端
用户2333768521835 分钟前
Ubuntu上fpm多架构打包实战
后端
JavaGuide1 小时前
轻量开源版 IDEA 来了!
前端·后端
Json____1 小时前
springboot开发高校选课管理系统:从零构建前后端分离的全栈实践
java·spring boot·后端·毕业设计·毕设·wwwoop.com
站大爷IP2 小时前
Python的列表推导式把我写崩了,原来圆括号和方括号不是一回事
后端
梦在远山后2 小时前
Python 中字符串常用写法
人工智能·后端
geovindu2 小时前
python:HandWriting Recognition using paddlepaddle
开发语言·后端·python·paddlepaddle
步行cgn2 小时前
为何以继承方式引入SpringBoot
java·spring boot·后端
windliang2 小时前
Agent Loop 的 while 循环什么时候开始不够用
人工智能·面试·开源