这里有一种方法,你可以向后走,阅读每一个
file.json
一路上。
项目目录结构示例:
./
- main.go
./my
- file.json > {"location": "/my"}
./my/sub
- file.json > {"location": "/my/sub"}
./my/sub/dir
- file.json > {"location": "/my/sub/dir"}
主.go
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
)
func main() {
basePath := "./"
targetPath := basePath + "my/sub/dir"
fileName := "file.json"
for {
rel, _ := filepath.Rel(basePath, targetPath)
// Exit the loop once we reach the basePath.
if rel == "." {
break
}
// Simple file reading logic.
dat, err := ioutil.ReadFile(fmt.Sprintf("%v/%v", targetPath, fileName))
if err != nil {
panic(err)
}
fmt.Println(string(dat))
// Going up!
targetPath += "/.."
}
}
输出:
{ "location": "/my/sub/dir" }
{ "location": "/my/sub" }
{ "location": "/my" }
希望你觉得这种方法有用。