[go] 파일 경로 간 상대 경로 계산하기

우선 main.go 파일과 subdir/example.txt 파일이 있는 폴더 구조를 가정해봅시다.

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	basePath := "/path/to/current/folder"
	targetPath := "/path/to/current/folder/subdir/example.txt"
	relPath, err := filepath.Rel(basePath, targetPath)
	if err != nil {
		fmt.Println("Failed to calculate relative path:", err)
		return
	}	
    fmt.Println("Relative path:", relPath)
}

위 코드에서 filepath.Rel 함수를 사용하여 basePathtargetPath 사이의 상대 경로를 구합니다. 출력 결과는 subdir/example.txt가 나와야 합니다.

참고문헌: