Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get root folder of project, two level up

Tags:

path

go

Im inside deep folder inside file and I want to get the dir which is 2 level up, I see the following api but not sure how to add something like "../../" , any idea?

  dir, err := os.Getwd()

for example I get the following

/Users/i02222333/go/src/myapp/src/test

And I need

/Users/i02222333/go/src/myapp

I can cut the string with the path with some manipulation but my question is if there is better solution to do it with golang ?


1 Answers

You can get the directory name of '../../' using the path package like this:

package main

import (
    "fmt"
    "os"
    "path"
)

func main() {
    dirname, err := os.Getwd()
    if err != nil {
        panic(err)
    }

    fmt.Printf("Current directory: %v\n", dirname)
    dir, err := os.Open(path.Join(dirname, "../../"))
    if err != nil {
        panic(err)
    }

    fmt.Printf("Name of ../../: %v\n", dir.Name())
}

Here is an example of my output:

$ go run main.go
Current directory: /Users/jack/go/src/stackoverflow/example/directory
Name of ../../: /Users/jack/go/src/stackoverflow
like image 183
Jack Avatar answered Oct 23 '25 08:10

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!