-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathutil.go
60 lines (49 loc) · 1.01 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
)
func contents(str string) (string, error) {
// Check for the empty string
if str == "" {
return str, nil
}
isFilePath := false
// See if the string is referencing a URL
if u, err := url.Parse(str); err == nil {
switch u.Scheme {
case "http", "https":
res, err := http.Get(str)
if err != nil {
return "", err
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return "", fmt.Errorf("could not read response: %w", err)
}
return string(b), nil
case "file":
// Fall through to file loading
str = u.Path
isFilePath = true
}
}
// See if the string is referencing a file
_, err := os.Stat(str)
if err == nil {
b, err := os.ReadFile(str)
if err != nil {
return "", fmt.Errorf("could not load file %s: %w", str, err)
}
return string(b), nil
}
if isFilePath {
return "", fmt.Errorf("could not load file %s: %w", str, err)
}
// Its a regular string
return str, nil
}