Skip to content

Latest commit

 

History

History
188 lines (161 loc) · 6.11 KB

04.03.md

File metadata and controls

188 lines (161 loc) · 6.11 KB

4.3 Swagger2.0在线API文档

API文档信息可以从两个地方获取,一个是struct Handler的字段标签中定义,一个是通过实现APIHandler接口来定义。

APIHandler接口定义的相关源码:

type (
	// Handler is the main Faygo Handler interface.
	Handler interface {
		Serve(ctx *Context) error
	}
	// APIHandler is the Faygo Handler interface,
	// which is implemented by a struct with API descriptor information.
	// It is an intelligent Handler of binding parameters.
	APIHandler interface {
		Handler
		APIDoc
	}
	// APIDoc provides the API's note, result or parameters information.
	APIDoc interface {
		Doc() Doc
	}
	// Doc api information
	Doc struct {
		Note   string      `json:"note" xml:"note"`
		Return interface{} `json:"return,omitempty" xml:"return,omitempty"`
		Params []ParamInfo `json:"params,omitempty" xml:"params,omitempty"`
	}
	// Notes implementation notes of a response
	Notes struct {
		Note   string      `json:"note" xml:"note"`
		Return interface{} `json:"return,omitempty" xml:"return,omitempty"`
	}
	// ParamInfo is the request parameter information
	ParamInfo struct {
		Name     string      // Parameter name
		In       string      // The position of the parameter
		Required bool        // Is a required parameter
		Model    interface{} // A parameter value that is used to infer a value type and as a default value
		Desc     string      // Description
	}
)

4.3.1 函数类型Handler定义API信息

通过使用函数faygo.WrapDoc()封装,为func Handler添加API文档信息,得到满足APIHandler接口的对象:

// 参数fn为预增加API信息的Handler函数,
// 参数note是API接口说明,
// 参数ret为API返回结果示例,
// 不定参parms为API请求参数信息
func WrapDoc(fn HandlerFunc, note string, ret interface{}, params ...ParamInfo) Handler

示例:

var AdditionHandler = faygo.WrapDoc(
	// Handler
	faygo.HandlerFunc(func(ctx *faygo.Context) error {
		// 获取请求参数,并作类型转换
		var a, b int
		if err := ctx.BindBizParam(&a, "the_one"); err != nil {
			return err
		}
		if a < 0 || a > 100 {
			return ctx.String(406, "参数 the_one 超出 [0,10] 的范围")
		}
		if err := ctx.BindBizParam(&b, "other"); err != nil {
			return err
		}
		return ctx.String(200, "(%s) + (%s) = %d", ctx.QueryParam("the_one"), ctx.QueryParam("other"), a+b)
	}),
	// API接口说明
	"addition",
	// 响应说明或示例
	"返回文本格式的处理结果",
	// 定义参数
	faygo.ParamInfo{
		Name:     "the_one",
		In:       "query",
		Required: true,
		Model:    int(2), // API文档中显示的参数默认值
		Desc:     "plus number, range: [0,100]",
	},
	faygo.ParamInfo{
		Name:     "other",
		In:       "query",
		Required: true,
		Model:    int(-1), // API文档中显示的参数默认值
		Desc:     "other plus number",
	},
)

运行服务后打开API在线文档:

http://localhost:8080/apidoc

测试该API接口:

apidoc func addition

4.3.2 结构体类型Handler定义API信息

struct Handler的API信息涉及到两个地方:

  • 结构体字段的标签,既用于绑定验证参数,也用于API信息的生成
  • 通过定义Doc方法实现APIHandler接口,在字段标签信息的基础上对API信息进行补充

将4.3.1中func Handler改写成struct Handler:

type Addition struct {
	// <in:query> 定义query类型请求参数;
	// 参数名为字段名转为默认的snake格式(默认格式可自定义),即'the_one';
	// 该参数值会被自动转为int类型;
	// <range: 0:100> 当其大小不在[0,100]范围时,faygo自动返回错误,错误模板可以自定义;
	// <desc:plus number> 定义参数描述为'plus number'
	TheOne int `param:"<in:query> <desc:plus number> <range: 0:100>"`
}

// 实现Handler接口
func (a *Addition) Serve(ctx *faygo.Context) error {
	var b int
	if err := ctx.BindBizParam(&b, "other"); err != nil {
		return err
	}
	return ctx.String(200, "(%d) + (%s) = %d", a.TheOne, ctx.QueryParam("other"), a.TheOne+b)
}

// 补充API文档信息
func (a *Addition) Doc() faygo.Doc {
	return faygo.Doc{
		// API接口说明
		Note: "addition",
		// 响应说明或示例
		Return: "返回文本格式的处理结果",
		// 补充参数定义
		Params: []faygo.ParamInfo{
			{
				Name:     "other",
				In:       "query",
				Required: true,
				Model:    int(-1),
				Desc:     "other plus number",
			},
		},
	}
}

该示例不仅展示了如何通过定义Doc方法扩展API的非参数信息,更特意展示了在Doc方法中补充参数信息(实际应用中很少见)。

该Handler的功能与4.3.1中AdditionHandler完全相同。但是为了使API文档中请求参数the_one默认值也相同,在定义路由时,应该使用实例 &Addition{TheOne: 2} 来指定the_one默认值。这里仅展示定义该路由的代码片段,路由详细用法将在第5章中讲述。

frame.NewNamedAPI("addition", "GET", "/addition", &Addition{TheOne: 2})

4.3.3 相关ini配置

Swagger2.0 API在线文档的默认访问路径为 /apidoc,其配置信息在相应Web服务的ini配置文件中(文件名格式 config/{appname}[_{version}].ini),apidoc的配置详情:

[apidoc]                                         # API文档
enable      = true                               # 是否启用
path        = /apidoc                            # 访问的URL路径
nolimit     = false                              # 是否不限访问IP
real_ip     = false                              # 使用真实客户端的IP进行过滤
whitelist   = 192.*|202.122.246.170              # 表示允许带有`192.`前缀或等于`202.122.246.170`的IP访问
desc        =                                    # 项目描述
email       =                                    # 联系人邮箱
terms_url   =                                    # 服务条款URL
license     =                                    # 协议类型
license_url =                                    # 协议内容URL

links