服务配置
Huma 包含一个基本的命令行和环境变量选项解析器,可用于向您的服务提供运行时配置。这允许您传入诸如服务运行的端口、用于标记日志的环境、数据库等依赖项的密钥和端点等内容。
端口选项
您的第一个 API 可以更新为接受一个可选的网络端口参数,如下所示:
| main.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:"监听端口" short:"p" default:"8888"`
}
// GreetingOutput 表示问候操作响应。
type GreetingOutput struct {
Body struct {
Message string `json:"message" example:"Hello, world!" doc:"问候消息"`
}
}
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 /greeting/{name}
huma.Register(api, huma.Operation{
OperationID: "get-greeting",
Method: http.MethodGet,
Path: "/greeting/{name}",
Summary: "获取问候语",
Description: "根据姓名获取一个人的问候语。",
Tags: []string{"Greetings"},
}, func(ctx context.Context, input *struct{
Name string `path:"name" maxLength:"30" example:"world" doc:"要问候的名称"`
}) (*GreetingOutput, error) {
resp := &GreetingOutput{}
resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
return resp, nil
})
// 告诉 CLI 如何启动您的服务器。
hooks.OnStart(func() {
fmt.Printf("正在端口 %d 上启动服务器...\n", options.Port)
http.ListenAndServe(fmt.Sprintf(":%d", options.Port), router)
})
})
// 运行 CLI。如果没有传递命令,它将启动服务器。
cli.Run()
}
|
就像请求和响应一样,CLI 选项使用一个自定义结构体定义,每个选项对应一个字段。一旦定义完成,只需将您的服务启动代码包装起来,然后从 main 函数运行 CLI 即可。
传递选项
选项可以作为命令行参数显式传递给服务,或者通过以 SERVICE_ 为前缀的环境变量提供。例如,要在端口 8000 上运行服务:
# 示例:传递命令行参数
$ go run main.go --port=8000
# 也支持简短参数
$ go run main.go -p 8000
# 示例:通过环境变量传递
$ SERVICE_PORT=8000 go run main.go
优先级
如果同时存在环境变量和命令行参数,则命令行参数优先。
回顾
恭喜!您刚刚学习了:
- 如何为您的服务添加 CLI 选项
- 如何通过命令行参数或环境变量传递选项
深入了解
想了解更多关于 CLI 的工作原理以及如何使用它?接下来查看这些内容: