我正在尝试使用 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 main
import (
"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
函数式编程