Skip to content

Commit

Permalink
Added better error handling in consul closing #6.
Browse files Browse the repository at this point in the history
  • Loading branch information
ashcrow committed Jun 16, 2015
1 parent 689cf0c commit 0133ec1
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 8 deletions.
33 changes: 27 additions & 6 deletions consul.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,39 @@ func (c Consul) PutKey(name string, value string, opts KeyOptions) (KeyValue, er
// TODO(ashcrow): We should probably allow 0 in the future
if opts.TTL != 0 {
// This means we need a session created as it controls the TTL
// TODO(ashcrow): error checking through here
ep := c.Endpoint + ":" + strconv.Itoa(c.Port) + "/v1/session/create"
jd, _ := json.Marshal(Session{TTL: strconv.Itoa(opts.TTL) + "s", Behavior: "delete"})
jd, err := json.Marshal(Session{TTL: strconv.Itoa(opts.TTL) + "s", Behavior: "delete"})
if err != nil {
kv.Error = 7
return kv, errors.New(Errors[kv.Error])
}
sess_req, _ := http.NewRequest("PUT", ep, bytes.NewReader(jd))
sess_resp, _ := c.Client.Do(sess_req)
sess_resp, err := c.Client.Do(sess_req)
if err != nil {
kv.Error = 8
return kv, errors.New(Errors[kv.Error])
}

defer sess_resp.Body.Close()
body, _ := ioutil.ReadAll(sess_resp.Body)
body, err := ioutil.ReadAll(sess_resp.Body)
if err != nil {
kv.Error = 3
return kv, errors.New(Errors[kv.Error])
}

var result map[string]string
json.Unmarshal(body, &result)
if err := json.Unmarshal(body, &result); err != nil {
kv.Error = 4
return kv, errors.New(Errors[kv.Error])
}
opts.CSession = result["ID"]
}
req, _ := http.NewRequest("PUT", c.makeURI(name, opts), strings.NewReader(value))
req, err := http.NewRequest("PUT", c.makeURI(name, opts), strings.NewReader(value))
if err != nil {
kv.Error = 8
return kv, errors.New(Errors[kv.Error])
}

resp, err := c.Client.Do(req)
if err != nil {
kv.Error = 1
Expand Down
4 changes: 2 additions & 2 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func ExampleEtcd_GetKey() {
etcd, _ := NewClient(
"etcd",
EtcdDefaultConfig,
)
)
keyval, _ := etcd.GetKey("keyname", KeyOptions{})

fmt.Println(reflect.TypeOf(keyval))
Expand All @@ -52,7 +52,7 @@ func ExampleEtcd_PutKey() {
etcd, _ := NewClient(
"etcd",
EtcdDefaultConfig,
)
)
keyval, _ := etcd.PutKey("keyname", "a value", KeyOptions{})

fmt.Println(reflect.TypeOf(keyval))
Expand Down
2 changes: 2 additions & 0 deletions shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ var Errors map[int]string = map[int]string{
4: "Unable to decode the value response",
5: "Server did not save the new key",
6: "Unable to delete key on the server",
7: "Unable to encode JSON",
8: "Unable to put key on the server",
}

// Interface to be a valid KeyValueStore
Expand Down

0 comments on commit 0133ec1

Please sign in to comment.