move a json file in go

To move a json file to a new location in go, you can use the os package to first open the file and read its contents, then create a new file at the destination location and write the contents to it. Finally, you can use the os.Remove() function to delete the original file from its old location. Here's an example code snippet:

main.go
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    sourcePath := "path/to/source/file.json"
    destPath := "path/to/destination/file.json"

    // Open and read the source file
    sourceFile, err := os.Open(sourcePath)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer sourceFile.Close()
    sourceContents, err := ioutil.ReadAll(sourceFile)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Create and write to the destination file
    destFile, err := os.Create(destPath)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer destFile.Close()
    err = ioutil.WriteFile(destPath, sourceContents, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Remove the source file
    err = os.Remove(sourcePath)
    if err != nil {
        fmt.Println(err)
        return
    }
}
923 chars
47 lines

related categories

gistlibby LogSnag