Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
3
Indexable
Never
package main

import (
    "fmt"
    "io"
    "os"
    "path/filepath"
)

func copyDir(src, dst string) error {
    // Create the destination directory if it doesn't exist
    if err := os.MkdirAll(dst, os.ModePerm); err != nil {
        return err
    }

    // Read the source directory
    entries, err := os.ReadDir(src)
    if err != nil {
        return err
    }

    // Copy each file and sub-directory
    for _, entry := range entries {
        srcPath := filepath.Join(src, entry.Name())
        dstPath := filepath.Join(dst, entry.Name())

        if entry.IsDir() {
            // Recursively copy sub-directories
            if err := copyDir(srcPath, dstPath); err != nil {
                return err
            }
        } else {
            // Copy files
            if err := copyFile(srcPath, dstPath); err != nil {
                return err
            }
        }
    }

    return nil
}

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

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

    _, err = io.Copy(dstFile, srcFile)
    if err != nil {
        return err
    }

    return nil
}

func main() {
    sourceDir := "/path/to/source"
    destinationDir := "/path/to/destination"

    if err := copyDir(sourceDir, destinationDir); err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Directory copied successfully.")
    }
}