copy a directory in go

You can use the os package in Golang to copy a directory. Here's an example function that takes in two paths where the first path is the source directory and the second path is the destination directory.

main.go
package main

import (
    "io"
    "os"
)

func copyDir(src, dst string) error {
    // get properties of source dir
    srcInfo, err := os.Stat(src)
    if err != nil {
        return err
    }

    // create destination dir
    err = os.MkdirAll(dst, srcInfo.Mode())
    if err != nil {
        return err
    }

    // get contents of the source dir
    entries, err := os.ReadDir(src)
    if err != nil {
        return err
    }

    // copy each file/dir in the source dir to destination dir
    for _, entry := range entries {
        srcPath := src + "/" + entry.Name()
        dstPath := dst + "/" + entry.Name()

        // recursively copy a directory
        if entry.IsDir() {
            err = copyDir(srcPath, dstPath)
            if err != nil {
                return err
            }
        } else {
            // perform copy operation on a file
            err = copyFile(srcPath, dstPath)
            if err != nil {
                return err
            }
        }
    }
    return nil
}

func copyFile(src, dst string) error {
    sourceFile, err := os.Open(src)
    if err != nil {
        return err
    }
    defer sourceFile.Close()

    destFile, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer destFile.Close()

    _, err = io.Copy(destFile, sourceFile)
    if err == nil {
        sourceInfo, err := os.Stat(src)
        if err != nil {
            err = os.Chmod(dst, sourceInfo.Mode())
        }

    }
    return err
}

func main() {
    // examples
    err := copyDir("./srcDir", "./dstDir")
    if err != nil {
        println("Error: ", err)
    }
}
1622 chars
80 lines

This copyDir function recursively copies all the files and subdirectories in the source directory to the destination directory. The copyFile function is called for each file encountered and executes the actual copy operation.

gistlibby LogSnag