Skip to content

Commit 22e2ede

Browse files
author
Your Name
committed
Add DefaultShell as required by ipfs#69
1 parent be6da7c commit 22e2ede

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

shell.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,42 @@ func NewShellWithClient(url string, c *gohttp.Client) *Shell {
8484
}
8585
}
8686

87+
// Get shell from environmental variables, default api path or gateway.
88+
func DefaultShell() (*Shell, error) {
89+
urls := make([]string, 1)
90+
if ipfsAPI := os.Getenv("IPFS_API"); ipfsAPI != "" {
91+
urls = append(urls, ipfsAPI)
92+
}
93+
ipfsPath := os.Getenv("IPFS_PATH")
94+
if ipfsPath == "" {
95+
if homePath, err := homedir.Dir(); err == nil {
96+
ipfsPath = homePath
97+
}
98+
}
99+
if ipfsPath != "" {
100+
apifile := path.Join(ipfsPath, ".ipfs", "api")
101+
if data, err := ioutil.ReadFile(apifile); err == nil {
102+
url := strings.Trim(string(data), "\n\t ")
103+
urls = append(urls, url)
104+
}
105+
}
106+
urls = append(urls, "/ip4/127.0.0.1/tcp/5001", "https://ipfs.io")
107+
108+
// do not repeat encountered addresses
109+
encountered := map[string]bool{}
110+
for _, url := range urls {
111+
if encountered[url] != true {
112+
encountered[url] = true
113+
sh := NewShell(url)
114+
_, _, err := sh.Version()
115+
if err == nil {
116+
return sh, nil
117+
}
118+
}
119+
}
120+
return nil, errors.New("No default node is working")
121+
}
122+
87123
func (s *Shell) SetTimeout(d time.Duration) {
88124
s.httpcli.Timeout = d
89125
}

0 commit comments

Comments
 (0)