Skip to content

Commit

Permalink
http(feat): add fallback executor support
Browse files Browse the repository at this point in the history
This allows _trying_ to execute a command on a daemon, failing, and falling back
on another executor.
  • Loading branch information
Stebalien committed Jun 14, 2019
1 parent ba094a0 commit ca0ae17
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions http/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type client struct {
httpClient *http.Client
ua string
apiPrefix string
fallback cmds.Executor
}

type ClientOpt func(*client)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit ca0ae17

Please sign in to comment.