find the name of a directory in go

To find the name of a directory in Go, you can use the filepath and strings packages.

First, use the filepath.Split() function to split the file path into its directory and file name components:

main.go
package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    path := "/path/to/directory/file.txt"
    dir, _ := filepath.Split(path)
    fmt.Println(dir) // prints "/path/to/directory/"
}
202 chars
13 lines

Then, you can use the strings.TrimSuffix() function to remove the trailing slash and get just the directory name:

main.go
package main

import (
    "fmt"
    "path/filepath"
    "strings"
)

func main() {
    path := "/path/to/directory/file.txt"
    dir, _ := filepath.Split(path)
    dir = strings.TrimSuffix(dir, "/")
    fmt.Println(dir) // prints "/path/to/directory"
}
254 chars
15 lines

If you need to handle the case where the path ends with a backslash on Windows, you can use the path/filepath package's VolumeName and IsPathSeparator functions to deal with that edge case.

gistlibby LogSnag