From abe076b8f8961378daecca4d8309929302f3c37a Mon Sep 17 00:00:00 2001 From: Nick Gerakines Date: Thu, 3 Jul 2014 18:16:41 -0400 Subject: [PATCH] Adding MustGet method. Updating README. --- README.md | 14 +++++++------- gin.go | 13 +++++++++++-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 53efb203..7c36793e 100644 --- a/README.md +++ b/README.md @@ -275,14 +275,14 @@ func main() { func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() - + // Set example variable c.Set("example", "12345") - + // before request - + c.Next() - + // after request latency := time.Since(t) log.Print(latency) @@ -292,10 +292,10 @@ func Logger() gin.HandlerFunc { func main() { r := gin.New() r.Use(Logger()) - + r.GET("/test", func(c *gin.Context){ - example := r.Get("example").(string) - + example := c.MustGet("example").(string) + // it would print: "12345" log.Println(example) }) diff --git a/gin.go b/gin.go index e29fe9dc..48a2b6db 100644 --- a/gin.go +++ b/gin.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/julienschmidt/httprouter" "html/template" + "log" "math" "net/http" "path" @@ -280,8 +281,7 @@ func (c *Context) Set(key string, item interface{}) { c.Keys[key] = item } -// Returns the value for the given key. -// It panics if the value doesn't exist. +// Get returns the value for the given key or an error if the key does not exist. func (c *Context) Get(key string) (interface{}, error) { if c.Keys != nil { item, ok := c.Keys[key] @@ -292,6 +292,15 @@ func (c *Context) Get(key string) (interface{}, error) { return nil, errors.New("Key does not exist.") } +// MustGet returns the value for the given key or panics if the value doesn't exist. +func (c *Context) MustGet(key string) interface{} { + value, err := c.Get(key) + if err != nil || value == nil { + log.Panicf("Key %s doesn't exist", key) + } + return value +} + /************************************/ /******** ENCOGING MANAGEMENT********/ /************************************/