为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中遍历 Swagger yaml 中的每个元素

在 Go 中遍历 Swagger yaml 中的每个元素

Go
倚天杖 2022-10-17 15:53:26
我正在尝试使用 Golang 遍历 Swagger 文档中的所有路径和方法,并从中获取一些字段,例如:获取每个路径和方法的 operationId 的值。以下是示例 Swagger 文档 -swagger: "2.0"host: "petstore.swagger.io"basePath: "/v2"schemes:- "https"- "http"paths:  /pet:    post:      tags:      - "pet"      summary: "Add a new pet to the store"      operationId: "addPet"    put:      tags:      - "pet"      summary: "Update an existing pet"      operationId: "updatePet"  /pet/findByStatus:    get:      tags:      - "pet"      summary: "Finds Pets by status"      operationId: "findPetsByStatus"这个 Swagger 文档不是静态的,它会改变。所以我没有为此定义一个结构,因为路径和方法不会保持不变。以下是示例代码 -package mainimport (    "fmt"    "log"    "gopkg.in/yaml.v2")func main() {m := make(map[interface{}]interface{})err := yaml.Unmarshal([]byte(data), &m)if err != nil {    log.Fatalf("error: %v", err)}fmt.Printf("--- m:\n%v\n\n", m)for k, v := range m {    fmt.Println(k, ":", v)    }}我可以像下面这样打印地图 -paths : map[/pet:map[post:map[operationId:addPet summary:Add a new pet to the store tags:[pet]] put:map[operationId:updatePet summary:Update an existing pet tags:[pet]]] /pet/findByStatus:map[get:map[operationId:findPetsByStatus summary:Finds Pets by status tags:[pet]]]]如何打印如下所示的每个路径和方法 -/pet post addPet/pet put updatePet/pet/findByStatus get findPetsByStatus
查看完整描述

1 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

有几个选项,使用https://github.com/getkin/kin-openapi来解析您的 YAML。下面的示例将要求您将 YAML 转换为 JSON。


    t := &openapi2.T{}


    if err := t.UnmarshalJSON([]byte(jsdata)); err != nil {

        panic(err)

    }


    for path, item := range t.Paths {

        for method, op := range item.Operations() {

            fmt.Printf("%s %s %s\n", path, method, op.OperationID)

        }

    }

或者您可以继续使用类型断言和 for 循环。


func main() {


    m := make(map[string]interface{})

    err := yaml.Unmarshal([]byte(data), &m)

    if err != nil {

        log.Fatalf("error: %v", err)

    }


    for k, v := range m {

        if k != "paths" {

            continue

        }


        m2, ok := v.(map[interface{}]interface{})

        if !ok {

            continue

        }


        if ok {

            for path, x := range m2 {

                m3, ok := x.(map[interface{}]interface{})

                if !ok {

                    continue

                }

                for method, x := range m3 {

                    m4, ok := x.(map[interface{}]interface{})

                    if !ok {

                        continue

                    }

                    operationId, ok := m4["operationId"]

                    if !ok {

                        continue

                    }

                    fmt.Println(path, method, operationId)

                }

            }

        }

    }

}


查看完整回答
反对 回复 2022-10-17
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信