diff --git a/http/client.go b/http/client.go index e17256eba37b3ee7ded9e6895514a39003a9e37b..3ac2925c4f0e0da4b01e0dc92206077d452d67d4 100644 --- a/http/client.go +++ b/http/client.go @@ -27,6 +27,7 @@ type client struct { httpClient *http.Client ua string apiPrefix string + fallback cmds.Executor } type ClientOpt func(*client) @@ -43,6 +44,15 @@ func ClientWithAPIPrefix(apiPrefix string) ClientOpt { } } +// ClientWithFallback adds a fallback executor to the client. +// +// Note: This may run the PreRun function twice. +func ClientWithFallback(exe cmds.Executor) ClientOpt { + return func(c *client) { + c.fallback = exe + } +} + func NewClient(address string, opts ...ClientOpt) cmds.Executor { if !strings.HasPrefix(address, "http://") { address = "http://" + address @@ -79,6 +89,10 @@ func (c *client) Execute(req *cmds.Request, re cmds.ResponseEmitter, env cmds.En res, err := c.send(req) if err != nil { if isConnRefused(err) { + if c.fallback != nil { + // XXX: this runs the PreRun twice + return c.fallback.Execute(req, re, env) + } err = fmt.Errorf("cannot connect to the api. Is the daemon running? To run as a standalone CLI command remove the api file in `$IPFS_PATH/api`") } return err