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
+38.3k Golang : How to check if a string contains another sub-string?
+3.5k Golang : How to fix html/template : "somefile" is undefined error?
+4.2k Javascript : Put image into Chrome browser's console
+16.2k Golang : Test file read write permission example
+20.4k Golang : Storing cookies in http.CookieJar example
+12.5k Golang : Read data from config file and assign to variables
+13.8k Golang : Get all upper case or lower case characters from string example
+9.9k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+5.8k Golang : Extract or copy items from map based on value
+21.6k Golang : Find files by extension
+13k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+5.2k Golang : Set or add headers for many or different handlers