From e600055457426be0efb6463e5502851ce04f34b4 Mon Sep 17 00:00:00 2001 From: Jimmy Pettersson Date: Wed, 17 Sep 2014 11:59:15 +0200 Subject: [PATCH 1/2] Implemented GetDefault --- context.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/context.go b/context.go index 294d1cce..e44583b4 100644 --- a/context.go +++ b/context.go @@ -8,11 +8,12 @@ import ( "bytes" "errors" "fmt" + "log" + "net/http" + "github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/render" "github.com/julienschmidt/httprouter" - "log" - "net/http" ) const ( @@ -185,6 +186,16 @@ func (c *Context) MustGet(key string) interface{} { return value } +// GetDefault returns the value for the given key or a default value if the key does not exist. +func (c *Context) GetDefault(key string, defaultVal interface{}) interface{} { + item, err := c.Get(key) + if err != nil { + return defaultVal + } + + return item +} + /************************************/ /******** ENCOGING MANAGEMENT********/ /************************************/ From c78c27d8c21861fd619fe233a85f3210a49b9e7f Mon Sep 17 00:00:00 2001 From: Jimmy Pettersson Date: Wed, 17 Sep 2014 11:59:36 +0200 Subject: [PATCH 2/2] Added tests for GetDefault --- context_test.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/context_test.go b/context_test.go index 6df824cb..0b575a1e 100644 --- a/context_test.go +++ b/context_test.go @@ -54,6 +54,17 @@ func TestContextSetGet(t *testing.T) { if v != "bar" { t.Errorf("Value should be bar, was %s", v) } + + // GetDefault + v = c.GetDefault("foo", "baz") + if v != "bar" { + t.Errorf("Value should be bar, was %s", v) + } + + v = c.GetDefault("badKey", "baz") + if v != "baz" { + t.Errorf("Value should be baz, was %s", v) + } }) r.ServeHTTP(w, req)