How to resolve relative path to absolute path in golang?

Is there an api like 'path.resolve' in node? Or can something do the same?

Example (nodejs code): path.resolve("~/sample.sh") It should turn out:/home/currentuser/sample.sh

+4
source share
1 answer

Permission ~(home user designation) is a different story, and it is usually a shell that permits this. For more information, see Expand the tilde in your home directory .

If you want to do this from Go code, you can use the function user.Current()to get detailed information about the current user, including his home folder, which will be User.HomeDir. But still you have to handle it yourself.

The following is the original answer.


path.Join() filepath.Join().

:

base := "/home/bob"
fmt.Println(path.Join(base, "work/go", "src/github.com"))

:

/home/bob/work/go/src/github.com

path.Clean() filepath.Clean() "" . .. .

filepath.Abs() ( , ). filepath.Abs() Clean() .

:

fmt.Println(filepath.Abs("/home/bob/../alice"))

:

/home/alice <nil>

Go Playground.

. :

+2

Source: https://habr.com/ru/post/1689186/


All Articles