-2

我创建了一个临时目录,使用tmpDir, err := ioutil.TempDir(dir, "OAS"). 我使用此路径将从 aws 中提取的 swagger 添加到此临时目录。path = tmpDir + "/" + apiName + ".json",但它不起作用。我也试过path = <path>/OAS/apiName.json了也没用。所以我的问题是如果我想向这个 tempDir 添加一个文件,我该如何定义它的路径?

cmd_3, err := exec.Command("aws", "apigateway", "get-export", "--rest-api-id", api_id, "--stage-name", stageName, "--export-type", "swagger", path).Output()
    pwd, err := os.Getwd()
    if err != nil {
        return
    }
    dir = pwd
} //gets the path where the program is executed from

    apiName := flagApiNameToGet
    stageName := flagStageName
    path = tmpDir + "/" + apiName + ".json"
    // Searching for API ID:
    for _, item := range apis.Items {
        if item.Name == apiName {
            fmt.Printf("API ID found: %+v ", item.Id)
            api_id := item.Id 
            cmd_3, err := exec.Command("aws", "apigateway", "get-export", "--rest-api-id", api_id, "--stage-name", stageName, "--export-type", "swagger", path).Output()
            if err != nil {
                return err
            }
            output := string(cmd_3[:])
            fmt.Println(output)
            found = true 
            break
        }
    }

func execute() {
    tmpDir, err := ioutil.TempDir(dir, "OAS")
        if err != nil {
            fmt.Println("Error creating temporary directory to store OAS")
            return
        }
    fmt.Println("Temporary directory created:", tmpDir)
    defer os.RemoveAll(tmpDir)

    err = getOAS()
    if err != nil {
        utils.HandleErrorAndExit("Error getting OAS from AWS. ", err)
    }
    err = initializeProject()
    if err != nil {
        utils.HandleErrorAndExit("Error initializing project. ", err)
    }
    fmt.Println("Temporary directory deleted")
}
4

1 回答 1

1

由于tmpDir变量是全局的。将您的代码更改为:

var err error
tmpDir, err = ioutil.TempDir(dir, "OAS")

发现区别了吗?:==。其他功能看不到范围声明的变量tmpDir

这是您的代码示例,playground您可以看到全局 var dir 在其他函数调用中为空。Fixed version

于 2020-09-21T07:31:10.193 回答