Search code examples
amazon-web-servicesgoaws-api-gatewaytempdir

How to add a file to a temporary directory?


I have created a temp dir using tmpDir, err := ioutil.TempDir(dir, "OAS"). And i used this path to add a swagger extracted from aws to this temp dir. path = tmpDir + "/" + apiName + ".json", but it doesnt work. i also tried path = <path>/OAS/apiName.json it didn't work either. So my question is if I want add a file to this tempDir how do I define it's path?

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

Solution

  • Since the tmpDir variable is global. Change your code to:

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

    Spotted the difference? := and =. Other fuction doesnt see scope declared variable tmpDir.

    Here is an example of your code playground as you can see the global var dir is empty in other function call. Fixed version