Home > Backend Development > Golang > Create files using sudo

Create files using sudo

王林
Release: 2024-02-06 09:21:10
forward
1315 people have browsed it

使用 sudo 创建文件

Question content

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.


Correct answer


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))
}
Copy after login

The above is the detailed content of Create files using sudo. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template