How can I resolve symlinks in Go?
Currently I call readlink -f
but I want something more idiomatic.
package main
import (
"os/exec"
"fmt"
)
func resolve(p string) string {
cmd := exec.Command("readlink", "-f", p)
out, _ := cmd.Output()
return (string(out))
}
func main() {
fmt.Printf(resolve("/initrd.img"))
}
Use os.Lstat:
func Lstat(name string) (fi FileInfo, err error)
Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type *PathError.
EDIT:
Then returned os.FileInfo
will only allow you to check if 'name' is a link or not (fi.Mode() & os.ModeSymlink != 0
). If it is, then use os.Readlink to get the pointee:
func Readlink(name string) (string, error)
Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.