diff --git a/README.md b/README.md index 72a87a1..7575c4f 100644 --- a/README.md +++ b/README.md @@ -284,14 +284,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) @@ -305,10 +305,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/examples/example_basic.go b/examples/example_basic.go index 77a8cec..5040357 100644 --- a/examples/example_basic.go +++ b/examples/example_basic.go @@ -38,7 +38,7 @@ func main() { })) authorized.POST("admin", func(c *gin.Context) { - user := c.Get(gin.AuthUserKey).(string) + user := c.MustGet(gin.AuthUserKey).(string) // Parse JSON var json struct { diff --git a/gin.go b/gin.go index 03bf8e5..5a17f52 100644 --- a/gin.go +++ b/gin.go @@ -355,20 +355,24 @@ 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. -func (c *Context) Get(key string) interface{} { - var ok bool - var item interface{} +// 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] - } else { - item, ok = nil, false + item, ok := c.Keys[key] + if ok { + return item, nil + } } - if !ok || item == nil { + 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 item + return value } /************************************/