Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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)

like image 685
Jon Bristow Avatar asked Nov 08 '22 21:11

Jon Bristow


1 Answers

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)
    }
}
like image 97
Liyan Chang Avatar answered Dec 06 '22 17:12

Liyan Chang