简体   繁体   中英

Loop through each element in Swagger yaml in Go

I am trying to loop through all the paths and methods in a Swagger document using Golang and get few fields from that, for eg: to get the value of operationId for each path and method. Below is the sample Swagger document -

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"

This Swagger document is not static and it will change. So I have not defined a struct for this as paths and methods will not remain same. Below is the sample code -

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)
    }
}

I am able to print the map like below -

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]]]]

How can I print each path and method like below -

/pet post addPet
/pet put updatePet
/pet/findByStatus get findPetsByStatus

You can continue to use type assertion and for loops.

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)
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM