Documentation
¶
Overview ¶
Package fileutil provides extreme simplicity file and path utilities for Golang. Package fileutil은 Golang을 위한 극도로 간단한 파일 및 경로 유틸리티를 제공합니다.
This package reduces 20+ lines of repetitive file manipulation code to just 1-2 lines. 이 패키지는 20줄 이상의 반복적인 파일 조작 코드를 단 1-2줄로 줄입니다.
Features 특징: - Safe file operations with automatic directory creation 자동 디렉토리 생성을 사용한 안전한 파일 작업 - Cross-platform compatibility 크로스 플랫폼 호환성 - Comprehensive file/directory operations 포괄적인 파일/디렉토리 작업 - Path manipulation and validation 경로 조작 및 검증 - File hashing and checksums 파일 해싱 및 체크섬 - File compression (zip, tar, gzip) 파일 압축 (zip, tar, gzip) - Temporary file management 임시 파일 관리 - Zero external dependencies (except yaml) 외부 의존성 없음 (yaml 제외)
Example 예제:
// Write file with automatic directory creation 자동 디렉토리 생성과 함께 파일 쓰기
err := fileutil.WriteString("path/to/file.txt", "Hello, World!")
// Read file 파일 읽기
content, err := fileutil.ReadString("path/to/file.txt")
// Copy file 파일 복사
err = fileutil.CopyFile("source.txt", "destination.txt")
// List all .go files recursively 모든 .go 파일 재귀적으로 나열
files, err := fileutil.FindFiles(".", func(path string, info os.FileInfo) bool {
return filepath.Ext(path) == ".go"
})
Version information is loaded dynamically from cfg/app.yaml. 버전 정보는 cfg/app.yaml에서 동적으로 로드됩니다.
Index ¶
- Constants
- Variables
- func Abs(path string) (string, error)
- func AccessTime(path string) (time.Time, error)
- func AppendBytes(path string, data []byte) error
- func AppendFile(path string, data []byte) error
- func AppendLines(path string, lines []string) error
- func AppendString(path string, content string) error
- func Base(path string) string
- func ChangeExt(path, newExt string) string
- func ChangeTime(path string) (time.Time, error)
- func Checksum(path string) (string, error)
- func Chmod(path string, mode os.FileMode) error
- func Chown(path string, uid, gid int) error
- func Clean(path string) error
- func CleanPath(path string) string
- func CompareFiles(path1, path2 string) (bool, error)
- func CompareHash(path1, path2 string) (bool, error)
- func CopyDir(src, dst string, options ...CopyOption) error
- func CopyFile(src, dst string, options ...CopyOption) error
- func CopyRecursive(src, dst string, options ...CopyOption) error
- func CreateFile(path string, perm ...os.FileMode) (*os.File, error)
- func CreateTemp(dir, pattern string) (string, error)
- func CreateTempDir(dir, pattern string) (string, error)
- func DeleteDir(path string) error
- func DeleteFile(path string) error
- func DeleteFiles(paths ...string) error
- func DeletePattern(pattern string) error
- func DeleteRecursive(path string) error
- func Dir(path string) string
- func DirSize(path string) (int64, error)
- func Exists(path string) bool
- func Ext(path string) string
- func FileInfo(path string) (os.FileInfo, error)
- func FilterFiles(files []string, predicate func(path string) bool) ([]string, error)
- func FindFiles(root string, predicate func(path string, info os.FileInfo) bool) ([]string, error)
- func FromSlash(path string) string
- func Glob(pattern string) ([]string, error)
- func HasExt(path string, exts ...string) bool
- func Hash(path string, algorithm string) (string, error)
- func HashBytes(path string) ([]byte, error)
- func HashDir(path string) (string, error)
- func IsAbs(path string) bool
- func IsDir(path string) bool
- func IsEmpty(path string) (bool, error)
- func IsExecutable(path string) bool
- func IsExist(err error) bool
- func IsFile(path string) bool
- func IsInvalid(err error) bool
- func IsNotFound(err error) bool
- func IsPermission(err error) bool
- func IsReadable(path string) bool
- func IsSafe(path, root string) bool
- func IsSymlink(path string) bool
- func IsValid(path string) bool
- func IsWritable(path string) bool
- func Join(elem ...string) string
- func ListAll(dir string, recursive ...bool) ([]string, error)
- func ListDirs(dir string, recursive ...bool) ([]string, error)
- func ListFiles(dir string, recursive ...bool) ([]string, error)
- func Lstat(path string) (os.FileInfo, error)
- func MD5(path string) (string, error)
- func Match(pattern, name string) (bool, error)
- func MkdirAll(path string, perm ...os.FileMode) error
- func ModTime(path string) (time.Time, error)
- func MoveDir(src, dst string) error
- func MoveFile(src, dst string) error
- func NewWriter(path string, perm ...os.FileMode) (*bufio.Writer, *os.File, error)
- func Normalize(path string) (string, error)
- func ReadBytes(path string, offset, size int64) ([]byte, error)
- func ReadCSV(path string) ([][]string, error)
- func ReadChunk(path string, chunkSize int64, fn func([]byte) error) error
- func ReadFile(path string) ([]byte, error)
- func ReadJSON(path string, v interface{}) error
- func ReadLines(path string) ([]string, error)
- func ReadString(path string) (string, error)
- func ReadYAML(path string, v interface{}) error
- func Rel(basepath, targpath string) (string, error)
- func RemoveEmpty(path string) error
- func Rename(old, new string) error
- func RenameExt(path, newExt string) error
- func SHA1(path string) (string, error)
- func SHA256(path string) (string, error)
- func SHA512(path string) (string, error)
- func SafeMove(src, dst string) error
- func Size(path string) (int64, error)
- func SizeHuman(path string) (string, error)
- func Split(path string) (dir, file string)
- func Stat(path string) (os.FileInfo, error)
- func SyncDirs(src, dst string) error
- func ToSlash(path string) string
- func Touch(path string) error
- func VerifyChecksum(path, expectedChecksum string) (bool, error)
- func Walk(root string, fn filepath.WalkFunc) error
- func WalkDirs(root string, fn func(path string, info os.FileInfo) error) error
- func WalkFiles(root string, fn func(path string, info os.FileInfo) error) error
- func WithoutExt(path string) string
- func WriteAtomic(path string, data []byte, perm ...os.FileMode) error
- func WriteCSV(path string, records [][]string, perm ...os.FileMode) error
- func WriteFile(path string, data []byte, perm ...os.FileMode) error
- func WriteJSON(path string, v interface{}, perm ...os.FileMode) error
- func WriteLines(path string, lines []string, perm ...os.FileMode) error
- func WriteString(path string, content string, perm ...os.FileMode) error
- func WriteYAML(path string, v interface{}, perm ...os.FileMode) error
- type CopyOption
Constants ¶
const ( // DefaultFileMode is the default file permission (rw-r--r--) // DefaultFileMode는 기본 파일 권한입니다 (rw-r--r--) DefaultFileMode os.FileMode = 0644 // DefaultDirMode is the default directory permission (rwxr-xr-x) // DefaultDirMode는 기본 디렉토리 권한입니다 (rwxr-xr-x) DefaultDirMode os.FileMode = 0755 // DefaultExecMode is the default executable file permission (rwxr-xr-x) // DefaultExecMode는 기본 실행 파일 권한입니다 (rwxr-xr-x) DefaultExecMode os.FileMode = 0755 )
Default file and directory permissions 기본 파일 및 디렉토리 권한
const ( // DefaultBufferSize is the default buffer size for reading/writing (32KB) // DefaultBufferSize는 읽기/쓰기를 위한 기본 버퍼 크기입니다 (32KB) DefaultBufferSize = 32 * 1024 // DefaultChunkSize is the default chunk size for streaming operations (1MB) // DefaultChunkSize는 스트리밍 작업을 위한 기본 청크 크기입니다 (1MB) DefaultChunkSize = 1024 * 1024 )
Buffer sizes for I/O operations I/O 작업을 위한 버퍼 크기
const ( KB = 1024 MB = 1024 * KB GB = 1024 * MB TB = 1024 * GB )
Size units for human-readable file sizes 사람이 읽기 쉬운 파일 크기를 위한 크기 단위
Variables ¶
var ( // ErrNotFound indicates that the file or directory was not found // ErrNotFound는 파일 또는 디렉토리를 찾을 수 없음을 나타냅니다 ErrNotFound = errors.New("fileutil: file or directory not found") // ErrNotFile indicates that the path is not a regular file // ErrNotFile은 경로가 일반 파일이 아님을 나타냅니다 ErrNotFile = errors.New("fileutil: not a regular file") // ErrNotDirectory indicates that the path is not a directory // ErrNotDirectory는 경로가 디렉토리가 아님을 나타냅니다 ErrNotDirectory = errors.New("fileutil: not a directory") // ErrPermission indicates a permission denied error // ErrPermission은 권한 거부 에러를 나타냅니다 ErrPermission = errors.New("fileutil: permission denied") // ErrInvalidPath indicates that the path is invalid or unsafe // ErrInvalidPath는 경로가 유효하지 않거나 안전하지 않음을 나타냅니다 ErrInvalidPath = errors.New("fileutil: invalid or unsafe path") // ErrAlreadyExists indicates that the file or directory already exists // ErrAlreadyExists는 파일 또는 디렉토리가 이미 존재함을 나타냅니다 ErrAlreadyExists = errors.New("fileutil: file or directory already exists") // ErrIsDirectory indicates that the operation cannot be performed on a directory // ErrIsDirectory는 디렉토리에서 작업을 수행할 수 없음을 나타냅니다 ErrIsDirectory = errors.New("fileutil: is a directory") // ErrNotEmpty indicates that the directory is not empty // ErrNotEmpty는 디렉토리가 비어 있지 않음을 나타냅니다 ErrNotEmpty = errors.New("fileutil: directory not empty") // ErrInvalidFormat indicates an invalid file format // ErrInvalidFormat은 유효하지 않은 파일 형식을 나타냅니다 ErrInvalidFormat = errors.New("fileutil: invalid file format") // ErrInvalidChecksum indicates that the checksum verification failed // ErrInvalidChecksum은 체크섬 검증 실패를 나타냅니다 ErrInvalidChecksum = errors.New("fileutil: invalid checksum") )
Common errors 일반적인 에러
var Version = version.Get()
Version is the current version of the fileutil package Version은 fileutil 패키지의 현재 버전입니다
Functions ¶
func Abs ¶
Abs returns the absolute path of a file or directory Abs는 파일 또는 디렉토리의 절대 경로를 반환합니다
Example 예제:
abs, err := fileutil.Abs("relative/path/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(abs) // "/current/dir/relative/path/file.txt"
func AccessTime ¶
AccessTime returns the access time of a file or directory AccessTime은 파일 또는 디렉토리의 액세스 시간을 반환합니다
Note: This function is platform-specific and may not work on all systems. 참고: 이 함수는 플랫폼별로 다르며 모든 시스템에서 작동하지 않을 수 있습니다.
Example 예제:
accessTime, err := fileutil.AccessTime("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Last accessed: %s\n", accessTime)
func AppendBytes ¶
AppendBytes is an alias for AppendFile AppendBytes는 AppendFile의 별칭입니다
func AppendFile ¶
AppendFile appends data to a file, creating it if it doesn't exist AppendFile은 파일에 데이터를 추가하고, 파일이 존재하지 않으면 생성합니다
Example 예제:
err := fileutil.AppendFile("log.txt", []byte("New log entry\n"))
if err != nil {
log.Fatal(err)
}
func AppendLines ¶
AppendLines appends lines to a file, creating it if it doesn't exist AppendLines는 파일에 줄을 추가하고, 파일이 존재하지 않으면 생성합니다
Example 예제:
lines := []string{"Line 1", "Line 2", "Line 3"}
err := fileutil.AppendLines("log.txt", lines)
if err != nil {
log.Fatal(err)
}
func AppendString ¶
AppendString appends a string to a file, creating it if it doesn't exist AppendString은 파일에 문자열을 추가하고, 파일이 존재하지 않으면 생성합니다
Example 예제:
err := fileutil.AppendString("log.txt", "New log entry\n")
if err != nil {
log.Fatal(err)
}
func Base ¶
Base returns the last element of a path Base는 경로의 마지막 요소를 반환합니다
This is an alias for filepath.Base. 이는 filepath.Base의 별칭입니다.
Example 예제:
base := fileutil.Base("path/to/file.txt")
// Result: "file.txt"
func ChangeExt ¶
ChangeExt changes the file extension ChangeExt는 파일 확장자를 변경합니다
Example 예제:
path := fileutil.ChangeExt("file.txt", ".md")
// Result: "file.md"
func ChangeTime ¶
ChangeTime returns the change time of a file or directory ChangeTime은 파일 또는 디렉토리의 변경 시간을 반환합니다
Note: This function is platform-specific and may not work on all systems. 참고: 이 함수는 플랫폼별로 다르며 모든 시스템에서 작동하지 않을 수 있습니다.
Example 예제:
changeTime, err := fileutil.ChangeTime("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Last changed: %s\n", changeTime)
func Checksum ¶
Checksum calculates the SHA256 checksum of a file Checksum은 파일의 SHA256 체크섬을 계산합니다
This is an alias for SHA256. 이는 SHA256의 별칭입니다.
Example 예제:
checksum, err := fileutil.Checksum("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("Checksum:", checksum)
func Chmod ¶
Chmod changes the mode of a file or directory Chmod는 파일 또는 디렉토리의 모드를 변경합니다
Example 예제:
err := fileutil.Chmod("path/to/file.txt", 0644)
if err != nil {
log.Fatal(err)
}
func Chown ¶
Chown changes the owner and group of a file or directory Chown은 파일 또는 디렉토리의 소유자와 그룹을 변경합니다
Example 예제:
err := fileutil.Chown("path/to/file.txt", 1000, 1000)
if err != nil {
log.Fatal(err)
}
func Clean ¶
Clean removes all files and subdirectories in a directory but keeps the directory itself Clean은 디렉토리의 모든 파일과 하위 디렉토리를 제거하지만 디렉토리 자체는 유지합니다
Example 예제:
err := fileutil.Clean("path/to/directory")
if err != nil {
log.Fatal(err)
}
func CleanPath ¶
CleanPath cleans a path by simplifying it CleanPath는 경로를 단순화하여 정리합니다
This is an alias for filepath.Clean. 이는 filepath.Clean의 별칭입니다.
Example 예제:
clean := fileutil.CleanPath("path/to/../file.txt")
// Result: "path/file.txt"
func CompareFiles ¶
CompareFiles compares two files byte by byte CompareFiles는 두 파일을 바이트 단위로 비교합니다
Returns true if the files are identical, false otherwise. 파일이 동일하면 true를, 그렇지 않으면 false를 반환합니다.
Example 예제:
same, err := fileutil.CompareFiles("file1.txt", "file2.txt")
if err != nil {
log.Fatal(err)
}
if same {
fmt.Println("Files are identical")
}
func CompareHash ¶
CompareHash compares two files by comparing their SHA256 hashes CompareHash는 두 파일의 SHA256 해시를 비교하여 파일을 비교합니다
This is faster than byte-by-byte comparison for large files. 이는 큰 파일에 대해 바이트 단위 비교보다 빠릅니다.
Example 예제:
same, err := fileutil.CompareHash("file1.txt", "file2.txt")
if err != nil {
log.Fatal(err)
}
if same {
fmt.Println("Files have the same hash")
}
func CopyDir ¶
func CopyDir(src, dst string, options ...CopyOption) error
CopyDir copies a directory from src to dst with optional settings CopyDir는 선택적 설정을 사용하여 src에서 dst로 디렉토리를 복사합니다
Example 예제:
// Copy directory 디렉토리 복사
err := fileutil.CopyDir("source-dir", "destination-dir")
// Copy with filter (exclude hidden files) 필터와 함께 복사 (숨겨진 파일 제외)
err = fileutil.CopyDir("source-dir", "destination-dir",
fileutil.WithFilter(func(path string, info os.FileInfo) bool {
return !strings.HasPrefix(info.Name(), ".")
}))
func CopyFile ¶
func CopyFile(src, dst string, options ...CopyOption) error
CopyFile copies a file from src to dst with optional settings CopyFile은 선택적 설정을 사용하여 src에서 dst로 파일을 복사합니다
Example 예제:
// Simple copy 간단한 복사
err := fileutil.CopyFile("source.txt", "destination.txt")
// Copy with overwrite 덮어쓰기와 함께 복사
err = fileutil.CopyFile("source.txt", "destination.txt",
fileutil.WithOverwrite(true))
// Copy with progress callback 진행 상황 콜백과 함께 복사
err = fileutil.CopyFile("source.txt", "destination.txt",
fileutil.WithProgress(func(written, total int64) {
fmt.Printf("Progress: %d/%d (%.2f%%)\n",
written, total, float64(written)/float64(total)*100)
}))
func CopyRecursive ¶
func CopyRecursive(src, dst string, options ...CopyOption) error
CopyRecursive is an alias for CopyDir CopyRecursive는 CopyDir의 별칭입니다
func CreateFile ¶
WriteStream writes data to a file using buffered I/O WriteStream은 버퍼링된 I/O를 사용하여 파일에 데이터를 씁니다
This is useful for writing large amounts of data efficiently. 이는 대량의 데이터를 효율적으로 쓰는 데 유용합니다.
Example 예제:
file, err := fileutil.CreateFile("large-file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, line := range lines {
writer.WriteString(line + "\n")
}
writer.Flush()
func CreateTemp ¶
CreateTemp creates a temporary file in the specified directory CreateTemp는 지정된 디렉토리에 임시 파일을 생성합니다
Example 예제:
tempPath, err := fileutil.CreateTemp("", "temp-*.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("Temp file:", tempPath)
func CreateTempDir ¶
CreateTempDir creates a temporary directory in the specified directory CreateTempDir는 지정된 디렉토리에 임시 디렉토리를 생성합니다
Example 예제:
tempDir, err := fileutil.CreateTempDir("", "temp-dir-*")
if err != nil {
log.Fatal(err)
}
fmt.Println("Temp directory:", tempDir)
func DeleteDir ¶
DeleteDir deletes an empty directory DeleteDir는 빈 디렉토리를 삭제합니다
Example 예제:
err := fileutil.DeleteDir("path/to/empty-dir")
if err != nil {
log.Fatal(err)
}
func DeleteFile ¶
DeleteFile deletes a file DeleteFile은 파일을 삭제합니다
Example 예제:
err := fileutil.DeleteFile("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
func DeleteFiles ¶
DeleteFiles deletes multiple files DeleteFiles는 여러 파일을 삭제합니다
Example 예제:
err := fileutil.DeleteFiles("file1.txt", "file2.txt", "file3.txt")
if err != nil {
log.Fatal(err)
}
func DeletePattern ¶
DeletePattern deletes all files matching a glob pattern DeletePattern은 glob 패턴과 일치하는 모든 파일을 삭제합니다
Example 예제:
// Delete all .tmp files 모든 .tmp 파일 삭제
err := fileutil.DeletePattern("*.tmp")
if err != nil {
log.Fatal(err)
}
func DeleteRecursive ¶
DeleteRecursive deletes a file or directory recursively DeleteRecursive는 파일 또는 디렉토리를 재귀적으로 삭제합니다
This is an alias for os.RemoveAll. 이는 os.RemoveAll의 별칭입니다.
Example 예제:
err := fileutil.DeleteRecursive("path/to/directory")
if err != nil {
log.Fatal(err)
}
func Dir ¶
Dir returns the directory part of a path Dir는 경로의 디렉토리 부분을 반환합니다
This is an alias for filepath.Dir. 이는 filepath.Dir의 별칭입니다.
Example 예제:
dir := fileutil.Dir("path/to/file.txt")
// Result: "path/to"
func DirSize ¶
DirSize calculates the total size of all files in a directory recursively DirSize는 디렉토리의 모든 파일 크기를 재귀적으로 계산합니다
Example 예제:
size, err := fileutil.DirSize("path/to/directory")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Directory size: %d bytes\n", size)
func Exists ¶
Exists checks if a file or directory exists Exists는 파일 또는 디렉토리가 존재하는지 확인합니다
Example 예제:
if fileutil.Exists("path/to/file.txt") {
fmt.Println("File exists")
}
func Ext ¶
Ext returns the file extension of a path Ext는 경로의 파일 확장자를 반환합니다
This is an alias for filepath.Ext. 이는 filepath.Ext의 별칭입니다.
Example 예제:
ext := fileutil.Ext("file.txt")
// Result: ".txt"
func FileInfo ¶
FileInfo returns the FileInfo for a file or directory FileInfo는 파일 또는 디렉토리의 FileInfo를 반환합니다
This is an alias for os.Stat. 이는 os.Stat의 별칭입니다.
Example 예제:
info, err := fileutil.FileInfo("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Name: %s, Size: %d\n", info.Name(), info.Size())
func FilterFiles ¶
FilterFiles filters a slice of file paths using a predicate function FilterFiles는 조건자 함수를 사용하여 파일 경로 슬라이스를 필터링합니다
Example 예제:
// Filter large files (>1MB) 큰 파일 필터링 (>1MB)
large, err := fileutil.FilterFiles(files, func(path string) bool {
info, _ := os.Stat(path)
return info.Size() > 1024*1024
})
func FindFiles ¶
FindFiles finds all files matching a predicate function FindFiles는 조건자 함수와 일치하는 모든 파일을 찾습니다
Example 예제:
// Find all .go files 모든 .go 파일 찾기
files, err := fileutil.FindFiles(".", func(path string, info os.FileInfo) bool {
return filepath.Ext(path) == ".go"
})
func FromSlash ¶
FromSlash converts a path from forward slashes to OS-specific separators FromSlash는 경로를 슬래시에서 OS별 구분자로 변환합니다
This is an alias for filepath.FromSlash. 이는 filepath.FromSlash의 별칭입니다.
Example 예제:
osPath := fileutil.FromSlash("path/to/file.txt")
// Result: "path/to/file.txt" (on Unix)
// Result: "path\\to\\file.txt" (on Windows)
func Glob ¶
Glob returns all files matching a pattern Glob는 패턴과 일치하는 모든 파일을 반환합니다
This is an alias for filepath.Glob. 이는 filepath.Glob의 별칭입니다.
Example 예제:
files, err := fileutil.Glob("*.txt")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file)
}
func HasExt ¶
HasExt checks if a path has one of the specified extensions HasExt는 경로가 지정된 확장자 중 하나를 가지고 있는지 확인합니다
Example 예제:
if fileutil.HasExt("file.txt", ".txt", ".md") {
fmt.Println("File has a valid extension")
}
func Hash ¶
Hash calculates the hash of a file using the specified algorithm Hash는 지정된 알고리즘을 사용하여 파일의 해시를 계산합니다
Supported algorithms: md5, sha1, sha256, sha512 지원되는 알고리즘: md5, sha1, sha256, sha512
Example 예제:
hash, err := fileutil.Hash("path/to/file.txt", "sha256")
if err != nil {
log.Fatal(err)
}
fmt.Println("Hash:", hash)
func HashBytes ¶
HashBytes calculates the hash of a file and returns it as a byte slice HashBytes는 파일의 해시를 계산하고 바이트 슬라이스로 반환합니다
This is useful when you need the raw hash bytes instead of a hex string. 이는 16진수 문자열 대신 원시 해시 바이트가 필요할 때 유용합니다.
Example 예제:
hashBytes, err := fileutil.HashBytes("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
func HashDir ¶
HashDir calculates the combined hash of all files in a directory HashDir는 디렉토리의 모든 파일의 결합된 해시를 계산합니다
This is useful for detecting changes in a directory. 이는 디렉토리의 변경 사항을 감지하는 데 유용합니다.
Example 예제:
hash, err := fileutil.HashDir("path/to/directory")
if err != nil {
log.Fatal(err)
}
fmt.Println("Directory hash:", hash)
func IsAbs ¶
IsAbs checks if a path is absolute IsAbs는 경로가 절대 경로인지 확인합니다
This is an alias for filepath.IsAbs. 이는 filepath.IsAbs의 별칭입니다.
Example 예제:
if fileutil.IsAbs("/absolute/path") {
fmt.Println("Path is absolute")
}
func IsDir ¶
IsDir checks if the path is a directory IsDir는 경로가 디렉토리인지 확인합니다
Example 예제:
if fileutil.IsDir("path/to/directory") {
fmt.Println("Is a directory")
}
func IsEmpty ¶
IsEmpty checks if a directory is empty IsEmpty는 디렉토리가 비어 있는지 확인합니다
Example 예제:
empty, err := fileutil.IsEmpty("path/to/directory")
if err != nil {
log.Fatal(err)
}
if empty {
fmt.Println("Directory is empty")
}
func IsExecutable ¶
IsExecutable checks if a file is executable IsExecutable은 파일이 실행 가능한지 확인합니다
Example 예제:
if fileutil.IsExecutable("path/to/script.sh") {
fmt.Println("File is executable")
}
func IsExist ¶
IsExist checks if the error is an "already exists" error IsExist는 에러가 "이미 존재함" 에러인지 확인합니다
Example 예제:
if fileutil.IsExist(err) { Handle already exists 이미 존재함 처리
}
func IsFile ¶
IsFile checks if the path is a regular file IsFile은 경로가 일반 파일인지 확인합니다
Example 예제:
if fileutil.IsFile("path/to/file.txt") {
fmt.Println("Is a file")
}
func IsInvalid ¶
IsInvalid checks if the error is an "invalid path" error IsInvalid는 에러가 "유효하지 않은 경로" 에러인지 확인합니다
Example 예제:
if fileutil.IsInvalid(err) { Handle invalid path 유효하지 않은 경로 처리
}
func IsNotFound ¶
IsNotFound checks if the error is a "file not found" error IsNotFound는 에러가 "파일을 찾을 수 없음" 에러인지 확인합니다
Example 예제:
if fileutil.IsNotFound(err) { Handle file not found 파일을 찾을 수 없음 처리
}
func IsPermission ¶
IsPermission checks if the error is a "permission denied" error IsPermission은 에러가 "권한 거부됨" 에러인지 확인합니다
Example 예제:
if fileutil.IsPermission(err) { Handle permission denied 권한 거부됨 처리
}
func IsReadable ¶
IsReadable checks if a file or directory is readable IsReadable은 파일 또는 디렉토리가 읽기 가능한지 확인합니다
Example 예제:
if fileutil.IsReadable("path/to/file.txt") {
fmt.Println("File is readable")
}
func IsSafe ¶
IsSafe checks if a path is safe (no path traversal attempts) IsSafe는 경로가 안전한지 확인합니다 (경로 순회 시도 없음)
This function checks if the path contains ".." or absolute paths outside the root. 이 함수는 경로에 ".."가 포함되어 있거나 루트 외부의 절대 경로가 있는지 확인합니다.
Example 예제:
if fileutil.IsSafe("path/to/file.txt", "/root/dir") {
fmt.Println("Path is safe")
}
func IsSymlink ¶
IsSymlink checks if the path is a symbolic link IsSymlink은 경로가 심볼릭 링크인지 확인합니다
Example 예제:
if fileutil.IsSymlink("path/to/link") {
fmt.Println("Is a symbolic link")
}
func IsValid ¶
IsValid checks if a path is valid (not empty and contains no invalid characters) IsValid는 경로가 유효한지 확인합니다 (비어 있지 않고 유효하지 않은 문자를 포함하지 않음)
Example 예제:
if fileutil.IsValid("path/to/file.txt") {
fmt.Println("Path is valid")
}
func IsWritable ¶
IsWritable checks if a file or directory is writable IsWritable은 파일 또는 디렉토리가 쓰기 가능한지 확인합니다
Example 예제:
if fileutil.IsWritable("path/to/file.txt") {
fmt.Println("File is writable")
}
func Join ¶
Join joins path elements into a single path using the OS-specific separator Join은 OS별 구분자를 사용하여 경로 요소를 단일 경로로 결합합니다
This is an alias for filepath.Join. 이는 filepath.Join의 별칭입니다.
Example 예제:
path := fileutil.Join("home", "user", "documents", "file.txt")
// Result: "home/user/documents/file.txt" (on Unix)
// Result: "home\\user\\documents\\file.txt" (on Windows)
func ListAll ¶
ListAll lists all files and directories ListAll은 모든 파일과 디렉토리를 나열합니다
If recursive is true, it lists all entries recursively. recursive가 true이면 모든 항목을 재귀적으로 나열합니다.
Example 예제:
// List all entries in current directory only 현재 디렉토리의 모든 항목만 나열
entries, err := fileutil.ListAll(".")
// List all entries recursively 재귀적으로 모든 항목 나열
entries, err = fileutil.ListAll(".", true)
func ListDirs ¶
ListDirs lists all subdirectories in a directory ListDirs는 디렉토리의 모든 하위 디렉토리를 나열합니다
If recursive is true, it lists all subdirectories recursively. recursive가 true이면 모든 하위 디렉토리를 재귀적으로 나열합니다.
Example 예제:
// List subdirectories in current directory only 현재 디렉토리의 하위 디렉토리만 나열
dirs, err := fileutil.ListDirs(".")
// List subdirectories recursively 재귀적으로 하위 디렉토리 나열
dirs, err = fileutil.ListDirs(".", true)
func ListFiles ¶
ListFiles lists all files in a directory ListFiles는 디렉토리의 모든 파일을 나열합니다
If recursive is true, it lists files in all subdirectories. recursive가 true이면 모든 하위 디렉토리의 파일을 나열합니다.
Example 예제:
// List files in current directory only 현재 디렉토리의 파일만 나열
files, err := fileutil.ListFiles(".")
// List files recursively 재귀적으로 파일 나열
files, err = fileutil.ListFiles(".", true)
func Lstat ¶
Lstat returns the FileInfo for a file or directory (does not follow symbolic links) Lstat은 파일 또는 디렉토리의 FileInfo를 반환합니다 (심볼릭 링크를 따라가지 않음)
Example 예제:
info, err := fileutil.Lstat("path/to/link")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Name: %s, Size: %d\n", info.Name(), info.Size())
func MD5 ¶
MD5 calculates the MD5 hash of a file MD5는 파일의 MD5 해시를 계산합니다
Example 예제:
hash, err := fileutil.MD5("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("MD5:", hash)
func Match ¶
Match checks if a filename matches a pattern Match는 파일 이름이 패턴과 일치하는지 확인합니다
This is an alias for filepath.Match. 이는 filepath.Match의 별칭입니다.
Example 예제:
matched, err := fileutil.Match("*.txt", "file.txt")
if err != nil {
log.Fatal(err)
}
if matched {
fmt.Println("File matches pattern")
}
func MkdirAll ¶
MkdirAll creates a directory and all necessary parents MkdirAll은 디렉토리와 모든 필요한 부모 디렉토리를 생성합니다
Example 예제:
err := fileutil.MkdirAll("path/to/nested/directory")
if err != nil {
log.Fatal(err)
}
func ModTime ¶
ModTime returns the modification time of a file or directory ModTime은 파일 또는 디렉토리의 수정 시간을 반환합니다
Example 예제:
modTime, err := fileutil.ModTime("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Last modified: %s\n", modTime)
func MoveDir ¶
MoveDir moves a directory from src to dst MoveDir는 src에서 dst로 디렉토리를 이동합니다
Example 예제:
err := fileutil.MoveDir("old-path/dir", "new-path/dir")
if err != nil {
log.Fatal(err)
}
func MoveFile ¶
MoveFile moves a file from src to dst MoveFile은 src에서 dst로 파일을 이동합니다
Example 예제:
err := fileutil.MoveFile("old-path/file.txt", "new-path/file.txt")
if err != nil {
log.Fatal(err)
}
func NewWriter ¶
NewWriter creates a new buffered writer for the specified file NewWriter는 지정된 파일에 대한 새 버퍼링된 writer를 생성합니다
Example 예제:
writer, file, err := fileutil.NewWriter("output.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
defer writer.Flush()
for _, line := range lines {
writer.WriteString(line + "\n")
}
func Normalize ¶
Normalize normalizes a path by cleaning it and making it absolute if possible Normalize는 경로를 정리하고 가능하면 절대 경로로 만들어 정규화합니다
Example 예제:
normalized, err := fileutil.Normalize("./path/../file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(normalized) // "/current/dir/file.txt"
func ReadBytes ¶
ReadBytes reads a specific number of bytes from a file at a given offset ReadBytes는 주어진 오프셋에서 파일로부터 특정 바이트 수를 읽습니다
Example 예제:
// Read 100 bytes starting from offset 1000
data, err := fileutil.ReadBytes("large-file.bin", 1000, 100)
if err != nil {
log.Fatal(err)
}
func ReadCSV ¶
ReadCSV reads a CSV file and returns its contents as a slice of string slices ReadCSV는 CSV 파일을 읽고 내용을 문자열 슬라이스의 슬라이스로 반환합니다
Example 예제:
records, err := fileutil.ReadCSV("data.csv")
if err != nil {
log.Fatal(err)
}
for _, record := range records {
fmt.Println(record)
}
func ReadChunk ¶
ReadChunk reads a file in chunks and calls the provided function for each chunk ReadChunk는 파일을 청크 단위로 읽고 각 청크마다 제공된 함수를 호출합니다
This is useful for processing large files without loading them entirely into memory. 이는 파일을 메모리에 전체 로드하지 않고 큰 파일을 처리하는 데 유용합니다.
Example 예제:
err := fileutil.ReadChunk("large-file.txt", 1024*1024, func(chunk []byte) error { Process chunk 청크 처리
fmt.Printf("Read %d bytes\n", len(chunk))
return nil
})
func ReadFile ¶
ReadFile reads the entire file and returns its contents as a byte slice ReadFile은 전체 파일을 읽고 내용을 바이트 슬라이스로 반환합니다
Example 예제:
data, err := fileutil.ReadFile("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
func ReadJSON ¶
ReadJSON reads a JSON file and unmarshals it into the provided value ReadJSON은 JSON 파일을 읽고 제공된 값으로 언마샬합니다
Example 예제:
var config Config
err := fileutil.ReadJSON("config.json", &config)
if err != nil {
log.Fatal(err)
}
func ReadLines ¶
ReadLines reads a file and returns its contents as a slice of lines ReadLines는 파일을 읽고 내용을 줄의 슬라이스로 반환합니다
Example 예제:
lines, err := fileutil.ReadLines("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
for _, line := range lines {
fmt.Println(line)
}
func ReadString ¶
ReadString reads the entire file and returns its contents as a string ReadString은 전체 파일을 읽고 내용을 문자열로 반환합니다
Example 예제:
content, err := fileutil.ReadString("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(content)
func ReadYAML ¶
ReadYAML reads a YAML file and unmarshals it into the provided value ReadYAML은 YAML 파일을 읽고 제공된 값으로 언마샬합니다
Example 예제:
var config Config
err := fileutil.ReadYAML("config.yaml", &config)
if err != nil {
log.Fatal(err)
}
func Rel ¶
Rel returns the relative path from basepath to targpath Rel은 basepath에서 targpath로의 상대 경로를 반환합니다
Example 예제:
relPath, err := fileutil.Rel("/base/path", "/base/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(relPath) // "to/file.txt"
func RemoveEmpty ¶
RemoveEmpty removes all empty directories recursively under the given path RemoveEmpty는 주어진 경로 아래의 모든 빈 디렉토리를 재귀적으로 제거합니다
Example 예제:
err := fileutil.RemoveEmpty("path/to/directory")
if err != nil {
log.Fatal(err)
}
func Rename ¶
Rename renames a file or directory Rename은 파일 또는 디렉토리의 이름을 변경합니다
This is an alias for os.Rename. 이는 os.Rename의 별칭입니다.
Example 예제:
err := fileutil.Rename("old-name.txt", "new-name.txt")
if err != nil {
log.Fatal(err)
}
func RenameExt ¶
RenameExt renames a file by changing its extension RenameExt는 파일의 확장자를 변경하여 이름을 변경합니다
Example 예제:
err := fileutil.RenameExt("file.txt", ".md")
if err != nil {
log.Fatal(err)
}
// Result: "file.md"
func SHA1 ¶
SHA1 calculates the SHA1 hash of a file SHA1은 파일의 SHA1 해시를 계산합니다
Example 예제:
hash, err := fileutil.SHA1("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("SHA1:", hash)
func SHA256 ¶
SHA256 calculates the SHA256 hash of a file SHA256은 파일의 SHA256 해시를 계산합니다
Example 예제:
hash, err := fileutil.SHA256("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("SHA256:", hash)
func SHA512 ¶
SHA512 calculates the SHA512 hash of a file SHA512는 파일의 SHA512 해시를 계산합니다
Example 예제:
hash, err := fileutil.SHA512("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("SHA512:", hash)
func SafeMove ¶
SafeMove moves a file or directory safely by copying first and then deleting SafeMove는 먼저 복사한 다음 삭제하여 파일 또는 디렉토리를 안전하게 이동합니다
This is slower than MoveFile/MoveDir but ensures data integrity. 이는 MoveFile/MoveDir보다 느리지만 데이터 무결성을 보장합니다.
Example 예제:
err := fileutil.SafeMove("source.txt", "destination.txt")
if err != nil {
log.Fatal(err)
}
func Size ¶
Size returns the size of a file in bytes Size는 파일의 크기를 바이트로 반환합니다
Example 예제:
size, err := fileutil.Size("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("File size: %d bytes\n", size)
func SizeHuman ¶
SizeHuman returns the file size in a human-readable format (e.g., "1.5 MB") SizeHuman은 사람이 읽기 쉬운 형식으로 파일 크기를 반환합니다 (예: "1.5 MB")
Example 예제:
size, err := fileutil.SizeHuman("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("File size: %s\n", size)
func Split ¶
Split splits a path into directory and file components Split은 경로를 디렉토리와 파일 구성 요소로 분할합니다
This is an alias for filepath.Split. 이는 filepath.Split의 별칭입니다.
Example 예제:
dir, file := fileutil.Split("path/to/file.txt")
// dir = "path/to/", file = "file.txt"
func Stat ¶
Stat returns the FileInfo for a file or directory Stat은 파일 또는 디렉토리의 FileInfo를 반환합니다
Example 예제:
info, err := fileutil.Stat("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Name: %s, Size: %d\n", info.Name(), info.Size())
func SyncDirs ¶
SyncDirs synchronizes the contents of two directories SyncDirs는 두 디렉토리의 내용을 동기화합니다
This function copies new and updated files from src to dst. Files in dst that don't exist in src are not removed. 이 함수는 src에서 dst로 새 파일과 업데이트된 파일을 복사합니다. src에 존재하지 않는 dst의 파일은 제거되지 않습니다.
Example 예제:
err := fileutil.SyncDirs("source-dir", "destination-dir")
if err != nil {
log.Fatal(err)
}
func ToSlash ¶
ToSlash converts a path to use forward slashes ToSlash는 경로를 슬래시로 변환합니다
This is an alias for filepath.ToSlash. 이는 filepath.ToSlash의 별칭입니다.
Example 예제:
slashPath := fileutil.ToSlash("path\\to\\file.txt")
// Result: "path/to/file.txt"
func Touch ¶
Touch creates a file if it doesn't exist, or updates its modification time if it does Touch는 파일이 존재하지 않으면 생성하고, 존재하면 수정 시간을 업데이트합니다
Example 예제:
err := fileutil.Touch("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
func VerifyChecksum ¶
VerifyChecksum verifies that a file's checksum matches the expected value VerifyChecksum은 파일의 체크섬이 예상 값과 일치하는지 확인합니다
Example 예제:
expected := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
valid, err := fileutil.VerifyChecksum("path/to/file.txt", expected)
if err != nil {
log.Fatal(err)
}
if !valid {
fmt.Println("Checksum mismatch!")
}
func Walk ¶
Walk walks the file tree rooted at root, calling fn for each file or directory Walk는 root를 루트로 하는 파일 트리를 순회하며 각 파일 또는 디렉토리에 대해 fn을 호출합니다
This is an alias for filepath.Walk. 이는 filepath.Walk의 별칭입니다.
Example 예제:
err := fileutil.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Println(path)
return nil
})
func WalkDirs ¶
WalkDirs walks the file tree and calls fn only for directories WalkDirs는 파일 트리를 순회하며 디렉토리에 대해서만 fn을 호출합니다
Example 예제:
err := fileutil.WalkDirs(".", func(path string, info os.FileInfo) error {
fmt.Println("Directory:", path)
return nil
})
func WalkFiles ¶
WalkFiles walks the file tree and calls fn only for files WalkFiles는 파일 트리를 순회하며 파일에 대해서만 fn을 호출합니다
Example 예제:
err := fileutil.WalkFiles(".", func(path string, info os.FileInfo) error {
fmt.Println("File:", path)
return nil
})
func WithoutExt ¶
WithoutExt returns the path without the file extension WithoutExt는 파일 확장자를 제외한 경로를 반환합니다
Example 예제:
path := fileutil.WithoutExt("file.txt")
// Result: "file"
func WriteAtomic ¶
WriteAtomic writes data to a file atomically by writing to a temporary file first and then renaming it to the target path WriteAtomic는 먼저 임시 파일에 쓴 다음 대상 경로로 이름을 변경하여 파일에 원자적으로 데이터를 씁니다
This prevents corruption if the write operation is interrupted. 이는 쓰기 작업이 중단될 경우 손상을 방지합니다.
Example 예제:
err := fileutil.WriteAtomic("important.txt", []byte("Critical data"))
if err != nil {
log.Fatal(err)
}
func WriteCSV ¶
WriteCSV writes records to a CSV file WriteCSV는 레코드를 CSV 파일에 씁니다
Example 예제:
records := [][]string{
{"Name", "Age", "City"},
{"Alice", "30", "Seoul"},
{"Bob", "25", "Busan"},
}
err := fileutil.WriteCSV("data.csv", records)
if err != nil {
log.Fatal(err)
}
func WriteFile ¶
WriteFile writes data to a file, creating the directory if it doesn't exist WriteFile은 파일에 데이터를 쓰고, 디렉토리가 존재하지 않으면 생성합니다
Example 예제:
err := fileutil.WriteFile("path/to/file.txt", []byte("Hello, World!"))
if err != nil {
log.Fatal(err)
}
func WriteJSON ¶
WriteJSON marshals a value to JSON and writes it to a file WriteJSON은 값을 JSON으로 마샬하고 파일에 씁니다
Example 예제:
config := Config{Name: "app", Version: "1.0.0"}
err := fileutil.WriteJSON("config.json", config)
if err != nil {
log.Fatal(err)
}
func WriteLines ¶
WriteLines writes a slice of lines to a file, creating the directory if it doesn't exist WriteLines는 줄의 슬라이스를 파일에 쓰고, 디렉토리가 존재하지 않으면 생성합니다
Example 예제:
lines := []string{"Line 1", "Line 2", "Line 3"}
err := fileutil.WriteLines("path/to/file.txt", lines)
if err != nil {
log.Fatal(err)
}
func WriteString ¶
WriteString writes a string to a file, creating the directory if it doesn't exist WriteString은 파일에 문자열을 쓰고, 디렉토리가 존재하지 않으면 생성합니다
Example 예제:
err := fileutil.WriteString("path/to/file.txt", "Hello, World!")
if err != nil {
log.Fatal(err)
}
Types ¶
type CopyOption ¶
type CopyOption func(*copyOptions)
CopyOption is a functional option for file copy operations CopyOption은 파일 복사 작업을 위한 함수형 옵션입니다
func WithFilter ¶
func WithFilter(fn func(path string, info os.FileInfo) bool) CopyOption
WithFilter sets a filter function to include/exclude files during copy WithFilter는 복사 중 파일을 포함/제외하는 필터 함수를 설정합니다
Example 예제:
err := fileutil.CopyDir(src, dst, fileutil.WithFilter(func(path string, info os.FileInfo) bool {
return !strings.HasPrefix(info.Name(), ".")
}))
func WithOverwrite ¶
func WithOverwrite(overwrite bool) CopyOption
WithOverwrite sets whether to overwrite existing files WithOverwrite는 기존 파일을 덮어쓸지 여부를 설정합니다
Example 예제:
err := fileutil.CopyFile(src, dst, fileutil.WithOverwrite(true))
func WithPreservePermissions ¶
func WithPreservePermissions(preserve bool) CopyOption
WithPreservePermissions sets whether to preserve file permissions WithPreservePermissions는 파일 권한을 보존할지 여부를 설정합니다
Example 예제:
err := fileutil.CopyFile(src, dst, fileutil.WithPreservePermissions(true))
func WithPreserveTimestamps ¶
func WithPreserveTimestamps(preserve bool) CopyOption
WithPreserveTimestamps sets whether to preserve file timestamps WithPreserveTimestamps는 파일 타임스탬프를 보존할지 여부를 설정합니다
Example 예제:
err := fileutil.CopyFile(src, dst, fileutil.WithPreserveTimestamps(true))
func WithProgress ¶
func WithProgress(fn func(written, total int64)) CopyOption
WithProgress sets a progress callback function WithProgress는 진행 상황 콜백 함수를 설정합니다
Example 예제:
err := fileutil.CopyFile(src, dst, fileutil.WithProgress(func(written, total int64) {
fmt.Printf("Progress: %d/%d bytes\n", written, total)
}))