This repository was archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
106 lines (90 loc) · 2.4 KB
/
utils.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package databricks
import (
"fmt"
"net/http"
"net/url"
"os"
"runtime"
"github.com/bgentry/go-netrc/netrc"
"github.com/mitchellh/go-homedir"
)
type netrcRoundTripper struct{}
// RoundTrip implements the http.RoundTripper interface.
func (r netrcRoundTripper) RoundTrip(
req *http.Request,
) (*http.Response, error) {
if err := addAuthFromNetrc(req.URL); err != nil {
return nil, err
}
return http.DefaultClient.Do(req)
}
// NetrcHTTPClient adds auth from NETRC.
var NetrcHTTPClient = &http.Client{
Transport: netrcRoundTripper{},
}
// NewBearerHTTPClient uses a token as an authorization bearer.
// See:
// https://docs.databricks.com/api/latest/authentication.html#pass-token-to-bearer-authentication
func NewBearerHTTPClient(token string) *http.Client {
client := *http.DefaultClient
client.Transport = bearerRoundTripper{token: token}
return &client
}
type bearerRoundTripper struct {
token string
}
// RoundTrip implements the http.RoundTripper interface.
func (r bearerRoundTripper) RoundTrip(
req *http.Request,
) (*http.Response, error) {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", r.token))
return http.DefaultClient.Do(req)
}
// addAuthFromNetrc adds auth information to the URL from the user's
// netrc file if it can be found. This will only add the auth info
// if the URL doesn't already have auth info specified and the
// the username is blank.
func addAuthFromNetrc(u *url.URL) error {
// If the URL already has auth information, do nothing
if u.User != nil && u.User.Username() != "" {
return nil
}
// Get the netrc file path
path := os.Getenv("NETRC")
if path == "" {
filename := ".netrc"
if runtime.GOOS == "windows" {
filename = "_netrc"
}
var err error
path, err = homedir.Expand("~/" + filename)
if err != nil {
return err
}
}
// If the file is not a file, then do nothing
if fi, err := os.Stat(path); err != nil {
// File doesn't exist, do nothing
if os.IsNotExist(err) {
return nil
}
// Some other error!
return err
} else if fi.IsDir() {
// File is directory, ignore
return nil
}
// Load up the netrc file
net, err := netrc.ParseFile(path)
if err != nil {
return fmt.Errorf("Error parsing netrc file at %q: %s", path, err)
}
machine := net.FindMachine(u.Host)
if machine == nil {
// Machine not found, no problem
return nil
}
// Set the user info
u.User = url.UserPassword(machine.Login, machine.Password)
return nil
}