Golang:如何解析文件名参数?

huangapple go评论83阅读模式
英文:

Golang: how can filename arguments be parsed?

问题

我正在使用golang编写一个命令行实用程序,它接受一个文件作为参数。我应该如何准确地将这个参数转换为可用的文件?似乎有很多情况需要处理:

  • 给定了一个绝对路径,我应该直接使用它
  • 给定了一个相对路径,我应该使用path.Join()将其与当前工作目录连接起来
  • 路径中使用了“.”和“../”,我认为我仍然应该使用path.Join(),而Go会简化路径?

Go是否提供了处理这个问题的任何方法?我是否应该根据第一个字符是否为“/”来进行分支?这似乎是一个笨拙的解决方案,但也许它总是有效的,所以应该这样做?

英文:

I am writing a command line utility in golang, which takes a file as an argument. How can I accurately turn this argument into a useable file? It seems there are many cases to handle:

  • An absolute path has been given, and I should use it as is
  • A relative path has been given, and I should path.Join() it with the current working directory
  • "."'s and "../"'s are used in the path, and I believe I should still use path.Join() and Go will simplify the path?

Does Go provide anything to handle this? Should I just branch based on whether the first character is '/'? That seems like a hacky solution, but perhaps it always works and so should be done?

答案1

得分: 1

操作系统会为您解释路径。您不需要对路径名称做任何操作。您可以简单地这样做:

os.Open("./path/to/file")
os.Open("another/file")
os.Open("../some_file")

等等

英文:

The operating system interprets paths for you. You don't need to do anything with path names. You can simply do something like this:

os.Open("./path/to/file")
os.Open("another/file")
os.Open("../some_file")

et cetera

答案2

得分: 0

除了你不想将 . 视为文件之外,没有太多需要担心的事情。

在一个可信任的环境中*,用户确实可以指向任何文件,os 包会处理它。不需要使用 filepath.Join

  • 如果给出了绝对路径,它将打开它。(即以 / 开头)
  • 如果没有,它将相对于当前工作目录查找。(包括 ../

(*) 在一个非受信任的环境中(例如 Web 服务器),您将希望验证授权的路径。

英文:

Taking aside that you don't want to see . as a file, there's not that much to worry about.

In a trusted environment*, where the user can indeed point to <i>any</i> file, the os package will take care of it. No need to filepath.Join anything.

  • If an absolute path is given, it will open it. (i.e.: starting with /)
  • If not, then it will see it relative to the current working directory. (including . and ./)

(*) In a non-trusted environment (a web server for example), you will want to validate the path given for authorization.

答案3

得分: 0

操作系统为您做了很多工作。然而,传递的参数可能对应一个目录。您应该检查os.FileInfo.IsDir,或者实现由path.filepath.Walk()接受的path.filepath.WalkFunc()来进行批量操作。后者是一种常见的方法。

英文:

OS does hard work for you. However passed argument possible can correspond a directory. You should either check os.FileInfo.IsDir, or implement path.filepath.WalkFunc() taken by path.filepath.Walk() for batch operations. Latter is quite a common approach.

huangapple
  • 本文由 发表于 2015年1月13日 17:00:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/27918263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定