Commit ca0ae174 authored by Steven Allen's avatar Steven Allen

http(feat): add fallback executor support

This allows _trying_ to execute a command on a daemon, failing, and falling back
on another executor.
parent ba094a02
...@@ -27,6 +27,7 @@ type client struct { ...@@ -27,6 +27,7 @@ type client struct {
httpClient *http.Client httpClient *http.Client
ua string ua string
apiPrefix string apiPrefix string
fallback cmds.Executor
} }
type ClientOpt func(*client) type ClientOpt func(*client)
...@@ -43,6 +44,15 @@ func ClientWithAPIPrefix(apiPrefix string) ClientOpt { ...@@ -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 { func NewClient(address string, opts ...ClientOpt) cmds.Executor {
if !strings.HasPrefix(address, "http://") { if !strings.HasPrefix(address, "http://") {
address = "http://" + address address = "http://" + address
...@@ -79,6 +89,10 @@ func (c *client) Execute(req *cmds.Request, re cmds.ResponseEmitter, env cmds.En ...@@ -79,6 +89,10 @@ func (c *client) Execute(req *cmds.Request, re cmds.ResponseEmitter, env cmds.En
res, err := c.send(req) res, err := c.send(req)
if err != nil { if err != nil {
if isConnRefused(err) { 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`") 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 return err
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment