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
+6.3k Golang : How to stop user from directly running an executable file?
+12.8k Elastic Search : Mapping date format and sort by date
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format
+4.4k PHP : Hide PHP version information from curl
+18.6k Golang : Reset or rewind io.Reader or io.Writer
+6.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+10.6k Golang : Convert(cast) bigint to string
+6k Golang : How to iterate a slice without using for loop?
+4.1k Golang : Check if a word is countable or not
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+6.4k Golang : How to convert strange string to JSON with json.MarshalIndent
+48.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate