Golang : Test file read write permission example
Problem :
You need to test if a file has the correct write or read permission before performing write or read operation. How to do that?
Solution :
Use os.OpenFile()
function and check the error with os.IsPermission() to see if a file has permission denied error.
For example :
To test if a file has write permission : (do not run this program as root or super user)
package main
import (
"fmt"
"os"
)
func main() {
fileName := "file.txt"
file, err := os.OpenFile(fileName, os.O_WRONLY, 0666)
if err != nil {
if os.IsPermission(err) {
fmt.Println("Unable to write to ", fileName)
fmt.Println(err)
os.Exit(1)
}
}
file.Close()
}
To test if a file has read permission : (do not run this program as root or super user)
package main
import (
"fmt"
"os"
)
func main() {
fileName := "file.txt"
file, err = os.OpenFile(fileName, os.O_RDONLY, 0666)
if err != nil {
if os.IsPermission(err) {
fmt.Println("Unable to read from ", fileName)
fmt.Println(err)
os.Exit(1)
}
}
file.Close()
}
References :
https://golang.org/pkg/os/#IsPermission
https://www.socketloop.com/tutorials/golang-check-if-a-file-exist-or-not
See also : Golang : Get file permission
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16k Golang : Read a file line by line
+7.5k Golang : Check if one string(rune) is permutation of another string(rune)
+19.6k Golang : Fix cannot download, $GOPATH not set error
+10.6k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+20.4k Golang : How to get struct tag and use field name to retrieve data?
+8.7k Golang : Convert(cast) []byte to io.Reader type
+6k AWS S3 : Prevent Hotlinking policy
+7.5k Golang : How to convert strange string to JSON with json.MarshalIndent
+14k Golang : Image to ASCII art example
+9.5k Golang : How to get garbage collection data?
+6.7k Elasticsearch : Shutdown a local node
+25.6k Golang : Convert long hexadecimal with strconv.ParseUint example