首页  >  文章  >  后端开发  >  在 Golang 中查看目录是否可写的跨平台方法?

在 Golang 中查看目录是否可写的跨平台方法?

WBOY
WBOY转载
2024-02-10 12:51:18602浏览

在 Golang 中查看目录是否可写的跨平台方法?

在Golang中,要查看目录是否可写的跨平台方法,可以使用`os.FileMode`来实现。首先,通过`os.Stat`函数获取目录的文件信息。然后,使用`file.Mode().Perm()`方法获取文件的权限。最后,使用`file.Mode().IsDir()`方法判断是否为目录。如果目录的权限为`0777`,则表示可写;如果权限为`0444`或`0555`,则表示只读;如果权限为其他值,则表示不可写。这种方法适用于跨平台的目录可写性检查。

问题内容

我有一个程序正在尝试使用 golang 将文件写入目录。我需要它能够在 macos、linux 和 windows(至少)中工作。

golang 提供了以下测试 - 但它似乎仅限于 linux(来自下面链接的 so 问题):

func IsWritable(path string) (isWritable bool, err error) {
    isWritable = false
    info, err := os.Stat(path)
    if err != nil {
        fmt.Println("Path doesn't exist")
        return
    }

    err = nil
    if !info.IsDir() {
        fmt.Println("Path isn't a directory")
        return
    }

    // Check if the user bit is enabled in file permission
    if info.Mode().Perm() & (1 << (uint(7))) == 0 {
        fmt.Println("Write permission bit is not set on this file for user")
        return
    }

    var stat syscall.Stat_t
    if err = syscall.Stat(path, &stat); err != nil {
        fmt.Println("Unable to get stat")
        return
    }

    err = nil
    if uint32(os.Geteuid()) != stat.Uid {
        isWritable = false
        fmt.Println("User doesn't have permission to write to this directory")
        return
    }

    isWritable = true
    return
}

我看到了这个答案[1],但是这个问题已经有 10 年了,有没有比条件编译更好的方法来完成这个任务?

摘要:我只想让 go 进程了解它是否可以写入给定目录。

[1]如何判断文件夹是否存在且可写?

解决方法

这就是我在没有条件编译的情况下实现目标的方法,因为操作系统之间的权限和特权可能不同。

  • 我尝试使用 os.createtemp 在该目录中创建一个临时文件。如果函数没有返回错误,则表明路径或权限没有问题,我们可以在该目录中创建文件。

这是代码

func IsWritable(path string) (bool, error) {
    tmpFile := "tmpfile"

    file, err := os.CreateTemp(path, tmpFile)
    if err != nil {
        return false, err
    }

    defer os.Remove(file.Name())
    defer file.Close()

    return true, nil
}


func main() {
     path := "absolute-directory-path"

    isWritable, err := IsWritable(path)
    if err != nil {
       panic(err)
    }

    if isWritable {
      // statements
    }

}

以上是在 Golang 中查看目录是否可写的跨平台方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除