I Spy Code - GO

Directory from path

Question:

How do a directory name from a path in golang?

Answer:

The function filepath.Dir() returns all but the last element of path, typically the paths directory.

Here is a golang example that shows how to get the directory name from a path:

Source: (example.go)

package main
 
import (
   "fmt"
   "path/filepath"
)
 
func main() {
   dir := filepath.Dir("/some-path/to-file/hello.go")
   fmt.Println("Directory:",dir)
}
 

Output:

$ go run example.go
Directory: /some-path/to-file

References:

https://golang.org/pkg/path/filepath/#Dir