How to Work with File Permissions in Go

Use os.Stat to read and os.Chmod to change file permissions in Go.

Use the os package to read file permissions with os.Stat and modify them with os.Chmod, passing a fs.FileMode value.

package main

import (
	"fmt"
	"os"
)

func main() {
	info, err := os.Stat("file.txt")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Current permissions:", info.Mode().Perm())

	err = os.Chmod("file.txt", 0600)
	if err != nil {
		fmt.Println(err)
		return
	}
}