-1

I'm trying to use os.open(fileDir) to read a file, then upload that file to an s3 bucket. Here's what I have so far.

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

My directory structure is like

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

But my code is running inside

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

How do a I pass in the correct fileDir? I need a solution that works locally and when the code gets deployed. I looked at the package path/filepath but I wasn't sure whether to get the absolute path first, then go down the hierarchy or something else.

Victor Cui
  • 1,393
  • 2
  • 15
  • 35
  • 1
    The source doe layout is useless to find a file. The executable may run anywhere. Make the path to your assets a configuration option (like a command line flag). – Volker Sep 11 '20 at 18:25
  • what do you mean by the executable may run anywhere? – Victor Cui Sep 11 '20 at 18:30
  • 1
    @VictorCui Paths are relative to the [working directory](https://en.wikipedia.org/wiki/Working_directory). Applications should not assume that the working directory has any relationship to a source code directory. The solution to this problem is to specify the location of the files (or some directory relative to the files) using a command line flag, configuration setting, etc. – Charlie Tumahai Sep 11 '20 at 20:20
  • I decided to use the solution posted by @Oleksiy here: https://stackoverflow.com/questions/31873396/is-it-possible-to-get-the-current-root-of-package-structure-as-a-string-in-golan – Victor Cui Sep 11 '20 at 20:53

1 Answers1

-1

You can add the following small function to get the expected file path.

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
}
Masudur Rahman
  • 1,585
  • 8
  • 16