登录
首页 >  Golang >  Go问答

从 Go 结构生成 OpenAPI XML 模型

来源:stackoverflow

时间:2024-04-25 16:09:34 256浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《从 Go 结构生成 OpenAPI XML 模型》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

有没有办法使用golang结构生成xml的openapi规范文档?我的结构使用编码/xml 注释进行注释,如下所示:

type Error struct {
    Text      string `xml:",chardata"`
    Type      string `xml:"Type,attr"`
    Code      string `xml:"Code,attr"`
    ShortText string `xml:"ShortText,attr"`
}

我想自动生成一个 openapi 模型,它尊重这些注释


正确答案


您可以使用标准库中的 reflect 包来检查结构及其标签,并且可以使用 gopkg.in/yaml.v3 包来生成 open api 格式。您只需编写将您的类型转换为另一种类型的逻辑,即与 open api 文档的结构相匹配的类型。

以下是如何解决此问题的示例,请注意,它不完整,因此不应按原样使用:

// declare a structure that matches the openapi's yaml document
type datatype struct {
    type  string               `yaml:"type,omitempty"`
    props map[string]*datatype `yaml:"properties,omitempty"`
    xml   *xml                 `yaml:"xml,omitempty"`
}
type xml struct {
    name string `yaml:"name,omitempty"`
    attr bool   `yaml:"attribute,omitempty"`
}
// write a marshal func that converts a given type to the structure declared above
// - this example converts only plain structs
func marshalopenapi(v interface{}) (interface{}, error) {
    rt := reflect.typeof(v)
    if rt.kind() == reflect.struct {
        obj := datatype{type: "object"}

        for i := 0; i < rt.numfield(); i++ {
            f := rt.field(i)
            tag := strings.split(f.tag.get("xml"), ",")
            if len(tag) == 0 || len(tag[0]) == 0 { // no name?
                continue
            }
            if obj.props == nil {
                obj.props = make(map[string]*datatype)
            }

            name := tag[0]
            obj.props[name] = &datatype{
                type: gotypetoopenapitype(f.type),
            }
            if len(tag) > 1 && tag[1] == "attr" {
                obj.props[name].xml = &xml{attr: true}
            }
        }

        return obj, nil
    }
    return nil, fmt.errorf("unsupported type")
}
// have all your types implement the yaml.marshaler interface by
// delegating to the marshal func implemented above
func (e error) marshalyaml() (interface{}, error) {
    return marshalopenapi(e)
}
// marshal the types
yaml.Marshal(map[string]map[string]interface{}{
    "schemas": {
        "error": Error{},
        // ...
    },
})

拨打 playground 试试。

终于介绍完啦!小伙伴们,这篇关于《从 Go 结构生成 OpenAPI XML 模型》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>