使用`ReadFile`函数读取具有文件方案的URL作为文件名的惯用方式是什么?

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

What is the idiomatic way to read urls with a file scheme as filenames for ReadFile?

问题

有没有一种习惯用法可以从系统中读取文件,而不是从路径开始(使用文件方案的URL)?

我首先尝试了这个:

fileUrlStr := "file:///path/to/file.json"
jsonBuffer, _ := ioutil.ReadFile(fileUrlStr)

这是我目前的(基本工作的)版本,但我担心可能有一些我忽略的问题,所以我希望有一种更可靠的方法来做到这一点:

fileUrlStr := "file:///path/to/file.json"
fileUrl, _ := url.Parse(fileUrlStr)
jsonBuffer, _ := ioutil.ReadFile(fileUrl.Path)

(如果我可以同时支持 file:///Users/jdoe/temp.jsonfile:///c:/WINDOWS/clock.json 而不必添加针对它们的代码路径,那就更好了)

英文:

Is there an idiomatic way to read a file from the system starting from a (file scheme) url and not a path?

I tried this first:

fileUrlStr := "file:///path/to/file.json"
jsonBuffer, _ := ioutil.ReadFile(fileUrlStr)

This is my current (mostly working version) but I'm concerned there are some gotchas that I'm missing, so I'm hoping there's a more tried and true way to do it:

fileUrlStr := "file:///path/to/file.json"
fileUrl, _ := url.Parse(fileUrlStr)
jsonBuffer, _ := ioutil.ReadFile(fileUrl.Path)

(Bonus if I can support both file:///Users/jdoe/temp.json and file:///c:/WINDOWS/clock.json without having to add code-paths accounting for them)

答案1

得分: 3

使用net/url,你正在使用的解决方案是正确的。

它可以正确处理跨平台的主机名和路径,并且还可以让你检查URL方案是否为文件方案。

package main

import (
	"fmt"
	"net/url"
)

func main() {

	for _, path := range []string{
		"file:///path/to/file.json",
		"file:///c:/WINDOWS/clock.json",
		"file://localhost/path/to/file.json",
		"file://localhost/c:/WINDOWS/clock.avi",

		// A case that you probably don't need to handle given the rarity,
		// but is a known legacy win32 issue when translating \\remotehost\share\dir\file.txt 
		"file:////remotehost/share/dir/file.txt",

	} {
		u, _ := url.ParseRequestURI(path)
		fmt.Printf("url:%v\nscheme:%v host:%v Path:%v\n\n", u, u.Scheme, u.Host, u.Path)
	}
}
英文:

Using net/url, the solution that you were using, is the correct one.

It's properly deals with hostnames and paths across platforms and also gives you a chance to check the url scheme is the file scheme.

package main

import (
	"fmt"
	"net/url"
)

func main() {

	for _, path := range []string{
		"file:///path/to/file.json",
		"file:///c:/WINDOWS/clock.json",
		"file://localhost/path/to/file.json",
		"file://localhost/c:/WINDOWS/clock.avi",
		
		// A case that you probably don't need to handle given the rarity,
		// but is a known legacy win32 issue when translating \\remotehost\share\dir\file.txt 
		"file:////remotehost/share/dir/file.txt",

	} {
		u, _ := url.ParseRequestURI(path)
		fmt.Printf("url:%v\nscheme:%v host:%v Path:%v\n\n", u, u.Scheme, u.Host, u.Path)
	}
}

huangapple
  • 本文由 发表于 2017年6月1日 04:44:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/44294363.html
匿名

发表评论

匿名网友

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

确定