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
+5.1k Golang : Create new color from command line parameters
+4.9k Golang : How to verify input is rune?
+18.2k Golang : Check if os.Stdin input data is piped or from terminal
+10.6k Golang : Decompress zlib file example
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+5k Golang : Missing Subversion command
+19.3k Golang : Clean up null characters from input data
+8.3k Golang : Convert(cast) string to int64
+10.9k Golang : Encrypt and decrypt data with x509 crypto
+4.6k Linux/Unix/PHP : Restart PHP-FPM
+8.9k Golang : Print how to use flag for your application example
+9k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)