I wish to create a file (equivalent to "mkdir filename") using Go's os.Create(filename) method. But I don't have write permission to the folder. Is there a Go method for "sudo mkdir filename"? I can't find any reference to this in the official documentation or elsewhere.
golang executable files are executed from the context of the user running the executable file. If you execute go run main.go
it will run as "you". If you execute sudo go run main.go
it will run as root.
So just write your application as if you have sudo. And make sure to run sudo go run main.go
.
Sample program for writing files: https://www.php.cn/link/69ddb50142a89123ba6f870ab07e6fbb
package main import ( "fmt" "os" ) func main() { // Choose your own perms here file, err := os.OpenFile("myfile.txt", os.O_CREATE|os.O_WRONLY, 0644) if err != nil { panic(err) } _, err = file.WriteString("Hello World!") if err != nil { panic(err) } file.Close() data, err := os.ReadFile("myfile.txt") if err != nil { panic(err) } fmt.Println(string(data)) }
The above is the detailed content of Create files using sudo. For more information, please follow other related articles on the PHP Chinese website!