diff --git a/CHANGELOG.md b/CHANGELOG.md index 21d90ff6..5da8cc5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ - [PR #151](https://github.com/rqlite/rqlite/pull/151): Support configurable Raft heartbeat timeout. - [PR #149](https://github.com/rqlite/rqlite/pull/149): Support configurable Raft snapshot thresholds. - [PR #148](https://github.com/rqlite/rqlite/pull/148): Support pprof information over HTTP. +- [PR #154](https://github.com/rqlite/rqlite/pull/154): CLI now redirects to leader if necessary. ## 3.2.1 (May 22nd 2016) - [PR #143](https://github.com/rqlite/rqlite/pull/143): Use DELETE as HTTP method to remove nodes. diff --git a/cmd/rqlite/main.go b/cmd/rqlite/main.go index 417c9226..2bc2c740 100644 --- a/cmd/rqlite/main.go +++ b/cmd/rqlite/main.go @@ -11,6 +11,8 @@ import ( "github.com/mkideal/cli" ) +const maxRedirect = 21 + type argT struct { cli.Helper Protocol string `cli:"s,scheme" usage:"protocol scheme(http or https)" dft:"http"` @@ -73,17 +75,34 @@ func makeJSONBody(line string) string { func sendRequest(ctx *cli.Context, urlStr string, line string, ret interface{}) error { data := makeJSONBody(line) - resp, err := http.Post(urlStr, "application/json", strings.NewReader(data)) - if err != nil { - return err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - if err := json.Unmarshal(body, ret); err != nil { - return fmt.Errorf(string(body)) + url := urlStr + + nRedirect := 0 + for { + resp, err := http.Post(url, "application/json", strings.NewReader(data)) + if err != nil { + return err + } + defer resp.Body.Close() + + // Check for redirect. + if resp.StatusCode == http.StatusMovedPermanently { + nRedirect++ + if nRedirect > maxRedirect { + return fmt.Errorf("maximum leader redirect limit exceeded") + } + url = resp.Header["Location"][0] + continue + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return err + } + + if err := json.Unmarshal(body, ret); err != nil { + return err + } + return nil } - return nil }