mirror of https://github.com/gin-gonic/gin.git
Setting Get metadata method to return both an interface as well as an error to remove panic.
This commit is contained in:
parent
5eb0e10a78
commit
108bfb4470
|
@ -38,14 +38,14 @@ func main() {
|
||||||
}))
|
}))
|
||||||
|
|
||||||
authorized.POST("admin", func(c *gin.Context) {
|
authorized.POST("admin", func(c *gin.Context) {
|
||||||
user := c.Get("user").(string)
|
user, _ := c.Get("user")
|
||||||
|
|
||||||
// Parse JSON
|
// Parse JSON
|
||||||
var json struct {
|
var json struct {
|
||||||
Value string `json:"value" binding:"required"`
|
Value string `json:"value" binding:"required"`
|
||||||
}
|
}
|
||||||
if c.EnsureBody(&json) {
|
if c.EnsureBody(&json) {
|
||||||
DB[user] = json.Value
|
DB[user.(string)] = json.Value
|
||||||
c.JSON(200, gin.H{"status": "ok"})
|
c.JSON(200, gin.H{"status": "ok"})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
17
gin.go
17
gin.go
|
@ -8,7 +8,6 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/julienschmidt/httprouter"
|
"github.com/julienschmidt/httprouter"
|
||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
|
||||||
"math"
|
"math"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path"
|
"path"
|
||||||
|
@ -283,18 +282,14 @@ func (c *Context) Set(key string, item interface{}) {
|
||||||
|
|
||||||
// Returns the value for the given key.
|
// Returns the value for the given key.
|
||||||
// It panics if the value doesn't exist.
|
// It panics if the value doesn't exist.
|
||||||
func (c *Context) Get(key string) interface{} {
|
func (c *Context) Get(key string) (interface{}, error) {
|
||||||
var ok bool
|
|
||||||
var item interface{}
|
|
||||||
if c.Keys != nil {
|
if c.Keys != nil {
|
||||||
item, ok = c.Keys[key]
|
item, ok := c.Keys[key]
|
||||||
} else {
|
if ok {
|
||||||
item, ok = nil, false
|
return item, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if !ok || item == nil {
|
return nil, errors.New("Key does not exist.")
|
||||||
log.Panicf("Key %s doesn't exist", key)
|
|
||||||
}
|
|
||||||
return item
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/************************************/
|
/************************************/
|
||||||
|
|
Loading…
Reference in New Issue