github.com/whyrusleeping/gx@v0.14.3/gxutil/shell.go (about) 1 package gxutil 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "strings" 8 9 sh "github.com/ipfs/go-ipfs-api" 10 homedir "github.com/mitchellh/go-homedir" 11 ma "github.com/multiformats/go-multiaddr" 12 manet "github.com/multiformats/go-multiaddr-net" 13 log "github.com/whyrusleeping/stump" 14 ) 15 16 var UsingGateway bool 17 18 func NewShell() *sh.Shell { 19 if apivar := os.Getenv("IPFS_API"); apivar != "" { 20 log.VLog("using '%s' from IPFS_API env as api endpoint.", apivar) 21 return sh.NewShell(apivar) 22 } 23 24 ash, err := getLocalAPIShell() 25 if err == nil { 26 return ash 27 } 28 29 UsingGateway = true 30 31 log.VLog("using global ipfs gateways as api endpoint") 32 return sh.NewShell("https://ipfs.io") 33 } 34 35 func getLocalAPIShell() (*sh.Shell, error) { 36 ipath := os.Getenv("IPFS_PATH") 37 if ipath == "" { 38 home, err := homedir.Dir() 39 if err != nil { 40 return nil, err 41 } 42 43 ipath = filepath.Join(home, ".ipfs") 44 } 45 46 apifile := filepath.Join(ipath, "api") 47 48 data, err := ioutil.ReadFile(apifile) 49 if err != nil { 50 return nil, err 51 } 52 53 addr := strings.Trim(string(data), "\n\t ") 54 55 host, err := multiaddrToNormal(addr) 56 if err != nil { 57 return nil, err 58 } 59 60 local := sh.NewShell(host) 61 62 _, _, err = local.Version() 63 if err != nil { 64 return nil, err 65 } 66 67 return local, nil 68 } 69 70 func multiaddrToNormal(addr string) (string, error) { 71 maddr, err := ma.NewMultiaddr(addr) 72 if err != nil { 73 return "", err 74 } 75 76 _, host, err := manet.DialArgs(maddr) 77 if err != nil { 78 return "", err 79 } 80 81 return host, nil 82 }