From 622b3b2351cd5dc8a2c0647d869e512759f03870 Mon Sep 17 00:00:00 2001 From: Cody Soyland Date: Fri, 3 Jan 2014 17:27:19 -0600 Subject: [PATCH] Add timeouts. --- hold/hold.go | 24 +++++++++++++++++++----- hold/hold_test.go | 8 ++++---- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/hold/hold.go b/hold/hold.go index dd10c7070..5819e1134 100644 --- a/hold/hold.go +++ b/hold/hold.go @@ -1,6 +1,11 @@ package hold -import "github.com/nu7hatch/gouuid" +import ( + "errors" + "time" + + "github.com/nu7hatch/gouuid" +) type holdchan chan interface{} type gethold struct { @@ -31,15 +36,24 @@ func (self *Holder) GetChan(id *uuid.UUID) holdchan { return <-reply } -func (self *Holder) Get(id *uuid.UUID) interface{} { +func (self *Holder) Get(id *uuid.UUID, timeout int) (interface{}, error) { ch := self.GetChan(id) - return <-ch + select { + case val := <-ch: + return val, nil + case <-time.After(time.Duration(timeout) * time.Second): + self.DelChan(id) + return nil, errors.New("Timeout getting from holder") + } } -func (self *Holder) Set(id *uuid.UUID, value interface{}) { +func (self *Holder) Set(id *uuid.UUID, value interface{}, timeout int) { ch := self.GetChan(id) go func() { - ch <- value + select { + case ch <- value: + case <-time.After(time.Duration(timeout) * time.Second): + } self.DelChan(id) }() } diff --git a/hold/hold_test.go b/hold/hold_test.go index a57edcc8f..93c9e9623 100644 --- a/hold/hold_test.go +++ b/hold/hold_test.go @@ -11,17 +11,17 @@ import ( func TestHoldChan(t *testing.T) { Convey("set then get", t, func() { id, _ := uuid.NewV4() - Hold.Set(id, "derp") - derp := Hold.Get(id) + Hold.Set(id, "derp", 10) + derp, _ := Hold.Get(id, 10) So(derp, ShouldEqual, "derp") }) Convey("get then set", t, func() { id, _ := uuid.NewV4() go func() { time.Sleep(time.Second / 10) - Hold.Set(id, "derpsy") + Hold.Set(id, "derpsy", 10) }() - derp := Hold.Get(id) + derp, _ := Hold.Get(id, 10) So(derp, ShouldEqual, "derpsy") }) }