keys.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. //go:generate codecgen -d 1819 -r "Node|Response|Nodes" -o keys.generated.go keys.go
  16. import (
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net/http"
  21. "net/url"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/coreos/etcd/pkg/pathutil"
  26. "github.com/ugorji/go/codec"
  27. "golang.org/x/net/context"
  28. )
  29. const (
  30. ErrorCodeKeyNotFound = 100
  31. ErrorCodeTestFailed = 101
  32. ErrorCodeNotFile = 102
  33. ErrorCodeNotDir = 104
  34. ErrorCodeNodeExist = 105
  35. ErrorCodeRootROnly = 107
  36. ErrorCodeDirNotEmpty = 108
  37. ErrorCodeUnauthorized = 110
  38. ErrorCodePrevValueRequired = 201
  39. ErrorCodeTTLNaN = 202
  40. ErrorCodeIndexNaN = 203
  41. ErrorCodeInvalidField = 209
  42. ErrorCodeInvalidForm = 210
  43. ErrorCodeRaftInternal = 300
  44. ErrorCodeLeaderElect = 301
  45. ErrorCodeWatcherCleared = 400
  46. ErrorCodeEventIndexCleared = 401
  47. )
  48. type Error struct {
  49. Code int `json:"errorCode"`
  50. Message string `json:"message"`
  51. Cause string `json:"cause"`
  52. Index uint64 `json:"index"`
  53. }
  54. func (e Error) Error() string {
  55. return fmt.Sprintf("%v: %v (%v) [%v]", e.Code, e.Message, e.Cause, e.Index)
  56. }
  57. var (
  58. ErrInvalidJSON = errors.New("client: response is invalid json. The endpoint is probably not valid etcd cluster endpoint.")
  59. ErrEmptyBody = errors.New("client: response body is empty")
  60. )
  61. // PrevExistType is used to define an existence condition when setting
  62. // or deleting Nodes.
  63. type PrevExistType string
  64. const (
  65. PrevIgnore = PrevExistType("")
  66. PrevExist = PrevExistType("true")
  67. PrevNoExist = PrevExistType("false")
  68. )
  69. var (
  70. defaultV2KeysPrefix = "/v2/keys"
  71. )
  72. // NewKeysAPI builds a KeysAPI that interacts with etcd's key-value
  73. // API over HTTP.
  74. func NewKeysAPI(c Client) KeysAPI {
  75. return NewKeysAPIWithPrefix(c, defaultV2KeysPrefix)
  76. }
  77. // NewKeysAPIWithPrefix acts like NewKeysAPI, but allows the caller
  78. // to provide a custom base URL path. This should only be used in
  79. // very rare cases.
  80. func NewKeysAPIWithPrefix(c Client, p string) KeysAPI {
  81. return &httpKeysAPI{
  82. client: c,
  83. prefix: p,
  84. }
  85. }
  86. type KeysAPI interface {
  87. // Get retrieves a set of Nodes from etcd
  88. Get(ctx context.Context, key string, opts *GetOptions) (*Response, error)
  89. // Set assigns a new value to a Node identified by a given key. The caller
  90. // may define a set of conditions in the SetOptions. If SetOptions.Dir=true
  91. // then value is ignored.
  92. Set(ctx context.Context, key, value string, opts *SetOptions) (*Response, error)
  93. // Delete removes a Node identified by the given key, optionally destroying
  94. // all of its children as well. The caller may define a set of required
  95. // conditions in an DeleteOptions object.
  96. Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error)
  97. // Create is an alias for Set w/ PrevExist=false
  98. Create(ctx context.Context, key, value string) (*Response, error)
  99. // CreateInOrder is used to atomically create in-order keys within the given directory.
  100. CreateInOrder(ctx context.Context, dir, value string, opts *CreateInOrderOptions) (*Response, error)
  101. // Update is an alias for Set w/ PrevExist=true
  102. Update(ctx context.Context, key, value string) (*Response, error)
  103. // Watcher builds a new Watcher targeted at a specific Node identified
  104. // by the given key. The Watcher may be configured at creation time
  105. // through a WatcherOptions object. The returned Watcher is designed
  106. // to emit events that happen to a Node, and optionally to its children.
  107. Watcher(key string, opts *WatcherOptions) Watcher
  108. }
  109. type WatcherOptions struct {
  110. // AfterIndex defines the index after-which the Watcher should
  111. // start emitting events. For example, if a value of 5 is
  112. // provided, the first event will have an index >= 6.
  113. //
  114. // Setting AfterIndex to 0 (default) means that the Watcher
  115. // should start watching for events starting at the current
  116. // index, whatever that may be.
  117. AfterIndex uint64
  118. // Recursive specifies whether or not the Watcher should emit
  119. // events that occur in children of the given keyspace. If set
  120. // to false (default), events will be limited to those that
  121. // occur for the exact key.
  122. Recursive bool
  123. }
  124. type CreateInOrderOptions struct {
  125. // TTL defines a period of time after-which the Node should
  126. // expire and no longer exist. Values <= 0 are ignored. Given
  127. // that the zero-value is ignored, TTL cannot be used to set
  128. // a TTL of 0.
  129. TTL time.Duration
  130. }
  131. type SetOptions struct {
  132. // PrevValue specifies what the current value of the Node must
  133. // be in order for the Set operation to succeed.
  134. //
  135. // Leaving this field empty means that the caller wishes to
  136. // ignore the current value of the Node. This cannot be used
  137. // to compare the Node's current value to an empty string.
  138. //
  139. // PrevValue is ignored if Dir=true
  140. PrevValue string
  141. // PrevIndex indicates what the current ModifiedIndex of the
  142. // Node must be in order for the Set operation to succeed.
  143. //
  144. // If PrevIndex is set to 0 (default), no comparison is made.
  145. PrevIndex uint64
  146. // PrevExist specifies whether the Node must currently exist
  147. // (PrevExist) or not (PrevNoExist). If the caller does not
  148. // care about existence, set PrevExist to PrevIgnore, or simply
  149. // leave it unset.
  150. PrevExist PrevExistType
  151. // TTL defines a period of time after-which the Node should
  152. // expire and no longer exist. Values <= 0 are ignored. Given
  153. // that the zero-value is ignored, TTL cannot be used to set
  154. // a TTL of 0.
  155. TTL time.Duration
  156. // Refresh set to true means a TTL value can be updated
  157. // without firing a watch or changing the node value. A
  158. // value must not be provided when refreshing a key.
  159. Refresh bool
  160. // Dir specifies whether or not this Node should be created as a directory.
  161. Dir bool
  162. // NoValueOnSuccess specifies whether the response contains the current value of the Node.
  163. // If set, the response will only contain the current value when the request fails.
  164. NoValueOnSuccess bool
  165. }
  166. type GetOptions struct {
  167. // Recursive defines whether or not all children of the Node
  168. // should be returned.
  169. Recursive bool
  170. // Sort instructs the server whether or not to sort the Nodes.
  171. // If true, the Nodes are sorted alphabetically by key in
  172. // ascending order (A to z). If false (default), the Nodes will
  173. // not be sorted and the ordering used should not be considered
  174. // predictable.
  175. Sort bool
  176. // Quorum specifies whether it gets the latest committed value that
  177. // has been applied in quorum of members, which ensures external
  178. // consistency (or linearizability).
  179. Quorum bool
  180. }
  181. type DeleteOptions struct {
  182. // PrevValue specifies what the current value of the Node must
  183. // be in order for the Delete operation to succeed.
  184. //
  185. // Leaving this field empty means that the caller wishes to
  186. // ignore the current value of the Node. This cannot be used
  187. // to compare the Node's current value to an empty string.
  188. PrevValue string
  189. // PrevIndex indicates what the current ModifiedIndex of the
  190. // Node must be in order for the Delete operation to succeed.
  191. //
  192. // If PrevIndex is set to 0 (default), no comparison is made.
  193. PrevIndex uint64
  194. // Recursive defines whether or not all children of the Node
  195. // should be deleted. If set to true, all children of the Node
  196. // identified by the given key will be deleted. If left unset
  197. // or explicitly set to false, only a single Node will be
  198. // deleted.
  199. Recursive bool
  200. // Dir specifies whether or not this Node should be removed as a directory.
  201. Dir bool
  202. }
  203. type Watcher interface {
  204. // Next blocks until an etcd event occurs, then returns a Response
  205. // representing that event. The behavior of Next depends on the
  206. // WatcherOptions used to construct the Watcher. Next is designed to
  207. // be called repeatedly, each time blocking until a subsequent event
  208. // is available.
  209. //
  210. // If the provided context is cancelled, Next will return a non-nil
  211. // error. Any other failures encountered while waiting for the next
  212. // event (connection issues, deserialization failures, etc) will
  213. // also result in a non-nil error.
  214. Next(context.Context) (*Response, error)
  215. }
  216. type Response struct {
  217. // Action is the name of the operation that occurred. Possible values
  218. // include get, set, delete, update, create, compareAndSwap,
  219. // compareAndDelete and expire.
  220. Action string `json:"action"`
  221. // Node represents the state of the relevant etcd Node.
  222. Node *Node `json:"node"`
  223. // PrevNode represents the previous state of the Node. PrevNode is non-nil
  224. // only if the Node existed before the action occurred and the action
  225. // caused a change to the Node.
  226. PrevNode *Node `json:"prevNode"`
  227. // Index holds the cluster-level index at the time the Response was generated.
  228. // This index is not tied to the Node(s) contained in this Response.
  229. Index uint64 `json:"-"`
  230. // ClusterID holds the cluster-level ID reported by the server. This
  231. // should be different for different etcd clusters.
  232. ClusterID string `json:"-"`
  233. }
  234. type Node struct {
  235. // Key represents the unique location of this Node (e.g. "/foo/bar").
  236. Key string `json:"key"`
  237. // Dir reports whether node describes a directory.
  238. Dir bool `json:"dir,omitempty"`
  239. // Value is the current data stored on this Node. If this Node
  240. // is a directory, Value will be empty.
  241. Value string `json:"value"`
  242. // Nodes holds the children of this Node, only if this Node is a directory.
  243. // This slice of will be arbitrarily deep (children, grandchildren, great-
  244. // grandchildren, etc.) if a recursive Get or Watch request were made.
  245. Nodes Nodes `json:"nodes"`
  246. // CreatedIndex is the etcd index at-which this Node was created.
  247. CreatedIndex uint64 `json:"createdIndex"`
  248. // ModifiedIndex is the etcd index at-which this Node was last modified.
  249. ModifiedIndex uint64 `json:"modifiedIndex"`
  250. // Expiration is the server side expiration time of the key.
  251. Expiration *time.Time `json:"expiration,omitempty"`
  252. // TTL is the time to live of the key in second.
  253. TTL int64 `json:"ttl,omitempty"`
  254. }
  255. func (n *Node) String() string {
  256. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d, TTL: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex, n.TTL)
  257. }
  258. // TTLDuration returns the Node's TTL as a time.Duration object
  259. func (n *Node) TTLDuration() time.Duration {
  260. return time.Duration(n.TTL) * time.Second
  261. }
  262. type Nodes []*Node
  263. // interfaces for sorting
  264. func (ns Nodes) Len() int { return len(ns) }
  265. func (ns Nodes) Less(i, j int) bool { return ns[i].Key < ns[j].Key }
  266. func (ns Nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] }
  267. type httpKeysAPI struct {
  268. client httpClient
  269. prefix string
  270. }
  271. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
  272. act := &setAction{
  273. Prefix: k.prefix,
  274. Key: key,
  275. Value: val,
  276. }
  277. if opts != nil {
  278. act.PrevValue = opts.PrevValue
  279. act.PrevIndex = opts.PrevIndex
  280. act.PrevExist = opts.PrevExist
  281. act.TTL = opts.TTL
  282. act.Refresh = opts.Refresh
  283. act.Dir = opts.Dir
  284. act.NoValueOnSuccess = opts.NoValueOnSuccess
  285. }
  286. doCtx := ctx
  287. if act.PrevExist == PrevNoExist {
  288. doCtx = context.WithValue(doCtx, &oneShotCtxValue, &oneShotCtxValue)
  289. }
  290. resp, body, err := k.client.Do(doCtx, act)
  291. if err != nil {
  292. return nil, err
  293. }
  294. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  295. }
  296. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  297. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
  298. }
  299. func (k *httpKeysAPI) CreateInOrder(ctx context.Context, dir, val string, opts *CreateInOrderOptions) (*Response, error) {
  300. act := &createInOrderAction{
  301. Prefix: k.prefix,
  302. Dir: dir,
  303. Value: val,
  304. }
  305. if opts != nil {
  306. act.TTL = opts.TTL
  307. }
  308. resp, body, err := k.client.Do(ctx, act)
  309. if err != nil {
  310. return nil, err
  311. }
  312. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  313. }
  314. func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
  315. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
  316. }
  317. func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
  318. act := &deleteAction{
  319. Prefix: k.prefix,
  320. Key: key,
  321. }
  322. if opts != nil {
  323. act.PrevValue = opts.PrevValue
  324. act.PrevIndex = opts.PrevIndex
  325. act.Dir = opts.Dir
  326. act.Recursive = opts.Recursive
  327. }
  328. doCtx := context.WithValue(ctx, &oneShotCtxValue, &oneShotCtxValue)
  329. resp, body, err := k.client.Do(doCtx, act)
  330. if err != nil {
  331. return nil, err
  332. }
  333. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  334. }
  335. func (k *httpKeysAPI) Get(ctx context.Context, key string, opts *GetOptions) (*Response, error) {
  336. act := &getAction{
  337. Prefix: k.prefix,
  338. Key: key,
  339. }
  340. if opts != nil {
  341. act.Recursive = opts.Recursive
  342. act.Sorted = opts.Sort
  343. act.Quorum = opts.Quorum
  344. }
  345. resp, body, err := k.client.Do(ctx, act)
  346. if err != nil {
  347. return nil, err
  348. }
  349. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  350. }
  351. func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
  352. act := waitAction{
  353. Prefix: k.prefix,
  354. Key: key,
  355. }
  356. if opts != nil {
  357. act.Recursive = opts.Recursive
  358. if opts.AfterIndex > 0 {
  359. act.WaitIndex = opts.AfterIndex + 1
  360. }
  361. }
  362. return &httpWatcher{
  363. client: k.client,
  364. nextWait: act,
  365. }
  366. }
  367. type httpWatcher struct {
  368. client httpClient
  369. nextWait waitAction
  370. }
  371. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  372. for {
  373. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  374. if err != nil {
  375. return nil, err
  376. }
  377. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  378. if err != nil {
  379. if err == ErrEmptyBody {
  380. continue
  381. }
  382. return nil, err
  383. }
  384. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  385. return resp, nil
  386. }
  387. }
  388. // v2KeysURL forms a URL representing the location of a key.
  389. // The endpoint argument represents the base URL of an etcd
  390. // server. The prefix is the path needed to route from the
  391. // provided endpoint's path to the root of the keys API
  392. // (typically "/v2/keys").
  393. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  394. // We concatenate all parts together manually. We cannot use
  395. // path.Join because it does not reserve trailing slash.
  396. // We call CanonicalURLPath to further cleanup the path.
  397. if prefix != "" && prefix[0] != '/' {
  398. prefix = "/" + prefix
  399. }
  400. if key != "" && key[0] != '/' {
  401. key = "/" + key
  402. }
  403. ep.Path = pathutil.CanonicalURLPath(ep.Path + prefix + key)
  404. return &ep
  405. }
  406. type getAction struct {
  407. Prefix string
  408. Key string
  409. Recursive bool
  410. Sorted bool
  411. Quorum bool
  412. }
  413. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  414. u := v2KeysURL(ep, g.Prefix, g.Key)
  415. params := u.Query()
  416. params.Set("recursive", strconv.FormatBool(g.Recursive))
  417. params.Set("sorted", strconv.FormatBool(g.Sorted))
  418. params.Set("quorum", strconv.FormatBool(g.Quorum))
  419. u.RawQuery = params.Encode()
  420. req, _ := http.NewRequest("GET", u.String(), nil)
  421. return req
  422. }
  423. type waitAction struct {
  424. Prefix string
  425. Key string
  426. WaitIndex uint64
  427. Recursive bool
  428. }
  429. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  430. u := v2KeysURL(ep, w.Prefix, w.Key)
  431. params := u.Query()
  432. params.Set("wait", "true")
  433. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  434. params.Set("recursive", strconv.FormatBool(w.Recursive))
  435. u.RawQuery = params.Encode()
  436. req, _ := http.NewRequest("GET", u.String(), nil)
  437. return req
  438. }
  439. type setAction struct {
  440. Prefix string
  441. Key string
  442. Value string
  443. PrevValue string
  444. PrevIndex uint64
  445. PrevExist PrevExistType
  446. TTL time.Duration
  447. Refresh bool
  448. Dir bool
  449. NoValueOnSuccess bool
  450. }
  451. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  452. u := v2KeysURL(ep, a.Prefix, a.Key)
  453. params := u.Query()
  454. form := url.Values{}
  455. // we're either creating a directory or setting a key
  456. if a.Dir {
  457. params.Set("dir", strconv.FormatBool(a.Dir))
  458. } else {
  459. // These options are only valid for setting a key
  460. if a.PrevValue != "" {
  461. params.Set("prevValue", a.PrevValue)
  462. }
  463. form.Add("value", a.Value)
  464. }
  465. // Options which apply to both setting a key and creating a dir
  466. if a.PrevIndex != 0 {
  467. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  468. }
  469. if a.PrevExist != PrevIgnore {
  470. params.Set("prevExist", string(a.PrevExist))
  471. }
  472. if a.TTL > 0 {
  473. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  474. }
  475. if a.Refresh {
  476. form.Add("refresh", "true")
  477. }
  478. if a.NoValueOnSuccess {
  479. params.Set("noValueOnSuccess", strconv.FormatBool(a.NoValueOnSuccess))
  480. }
  481. u.RawQuery = params.Encode()
  482. body := strings.NewReader(form.Encode())
  483. req, _ := http.NewRequest("PUT", u.String(), body)
  484. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  485. return req
  486. }
  487. type deleteAction struct {
  488. Prefix string
  489. Key string
  490. PrevValue string
  491. PrevIndex uint64
  492. Dir bool
  493. Recursive bool
  494. }
  495. func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
  496. u := v2KeysURL(ep, a.Prefix, a.Key)
  497. params := u.Query()
  498. if a.PrevValue != "" {
  499. params.Set("prevValue", a.PrevValue)
  500. }
  501. if a.PrevIndex != 0 {
  502. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  503. }
  504. if a.Dir {
  505. params.Set("dir", "true")
  506. }
  507. if a.Recursive {
  508. params.Set("recursive", "true")
  509. }
  510. u.RawQuery = params.Encode()
  511. req, _ := http.NewRequest("DELETE", u.String(), nil)
  512. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  513. return req
  514. }
  515. type createInOrderAction struct {
  516. Prefix string
  517. Dir string
  518. Value string
  519. TTL time.Duration
  520. }
  521. func (a *createInOrderAction) HTTPRequest(ep url.URL) *http.Request {
  522. u := v2KeysURL(ep, a.Prefix, a.Dir)
  523. form := url.Values{}
  524. form.Add("value", a.Value)
  525. if a.TTL > 0 {
  526. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  527. }
  528. body := strings.NewReader(form.Encode())
  529. req, _ := http.NewRequest("POST", u.String(), body)
  530. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  531. return req
  532. }
  533. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  534. switch code {
  535. case http.StatusOK, http.StatusCreated:
  536. if len(body) == 0 {
  537. return nil, ErrEmptyBody
  538. }
  539. res, err = unmarshalSuccessfulKeysResponse(header, body)
  540. default:
  541. err = unmarshalFailedKeysResponse(body)
  542. }
  543. return
  544. }
  545. func unmarshalSuccessfulKeysResponse(header http.Header, body []byte) (*Response, error) {
  546. var res Response
  547. err := codec.NewDecoderBytes(body, new(codec.JsonHandle)).Decode(&res)
  548. if err != nil {
  549. return nil, ErrInvalidJSON
  550. }
  551. if header.Get("X-Etcd-Index") != "" {
  552. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  553. if err != nil {
  554. return nil, err
  555. }
  556. }
  557. res.ClusterID = header.Get("X-Etcd-Cluster-ID")
  558. return &res, nil
  559. }
  560. func unmarshalFailedKeysResponse(body []byte) error {
  561. var etcdErr Error
  562. if err := json.Unmarshal(body, &etcdErr); err != nil {
  563. return ErrInvalidJSON
  564. }
  565. return etcdErr
  566. }