登录
首页 >  Golang >  Go问答

在Go语言中实现文件的层次结构引用

来源:stackoverflow

时间:2024-03-03 13:15:27 478浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《在Go语言中实现文件的层次结构引用》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我正在尝试使用 os.open(filedir) 读取文件,然后将该文件上传到 s3 存储桶。这是我到目前为止所拥有的。

func addfiletos3(s *session.session, filedir string) error {
   file, err := os.open(filedir)
    if err != nil {
        return err
    }
    defer file.close()
    // get file size and read the file content into a buffer
    fileinfo, _ := file.stat()
    var size int64 = fileinfo.size()
    buffer := make([]byte, size)
    file.read(buffer)
    // code to upload to s3
    return nil

我的目录结构是这样的

|--project-root
  |--test
    |--functional
     |--assets
      |-- good
       |--fileineed

但是我的代码正在里面运行

|--project-root
  |--services
    |--service
     |--test
      |--myGoCode

如何传入正确的 filedir?我需要一个可以在本地运行并且在部署代码时运行的解决方案。我查看了包 path/filepath 但我不确定是先获取绝对路径,然后再沿着层次结构还是其他路径。


解决方案


您可以添加以下小函数来获取预期的文件路径。

var (
    _, file, _, _ = runtime.Caller(0)
    baseDir = filepath.Dir(file)
    projectDir = filepath.Join(baseDir, "../../../")
)

func getFileINeedDirectory() string {
    fileINeedDir := path.Join(projectDir, "test/functional/assets/good/fileINeed")

    return fileINeedDir // project-dir/test/functional/assets/good/fileINeed
}

好了,本文到此结束,带大家了解了《在Go语言中实现文件的层次结构引用》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>