Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Detecting symbolic link in Go

    package main
    
    import (
    	"fmt"
    	"os"
    	"path/filepath"
    )
    
    func IsSymlink(path string) (bool, error) {
    	var isSymlink bool
    	stat, err := os.Lstat(path)
    
    	if err != nil {
    		return isSymlink, err
    	}
    
    	isSymlink = (stat.Mode() & os.ModeSymlink) == os.ModeSymlink
    
    	return isSymlink, nil
    }
    
    func main() {
    	// create temporary file
    	tmpFile, err := os.CreateTemp("", "tmpfile")
    
    	if err != nil {
    		panic(err)
    	}
    
    	defer os.Remove(tmpFile.Name())
    
    	fmt.Println("Temp file name:", tmpFile.Name())
    
    	symlinkPath := filepath.Join(os.TempDir(), "tmpsymlink")
    
    	// create symlink
    	err = os.Symlink(tmpFile.Name(), symlinkPath)
    
    	if err != nil {
    		panic(err)
    	}
    
    	defer os.Remove(symlinkPath)
    
    	// check if file is symlink
    	isSymlink, err := IsSymlink(symlinkPath)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Printf("'%s' is symlink: %v", symlinkPath, isSymlink)
    
    }
    
    // $ go run main.go 
    // Temp file name: /tmp/tmpfile1471080551
    // '/tmp/tmpsymlink' is symlink: true

    An example of determining whether a file is a symlink.