Open cruvie opened 12 months ago
I think you should use Get instead of GetString directly when you are not sure about the type. To solve your problem you can do the following:
func setupRouter() *gin.Engine {
r := gin.Default()
r.GET("/GetTest", func(c *gin.Context) {
key := "myKet"
c.Set(key, 5)
//get, exists := c.Get(key)
//if exists {
// log.Println("get==", get)
//}
//value := c.GetString(key)
//log.Println("value==", value)
get, err := assertion[string](c.Get(key))
if err != nil {
log.Println(err)
return
}
log.Println("get==", get)
c.JSON(200, "ok")
})
return r
}
func assertion[T any](v any, exist bool) (T, error) {
if exist {
if got, ok := v.(T); ok {
return got, nil
} else {
return got, fmt.Errorf("can not convert type: %T to %T ", v, *new(T))
}
}
return *new(T), errors.New("not exist")
}
out
=== RUN TestHttp
2023/08/16 00:42:56 can not convert type: int to string
@kaylee595 thank you, that's a good idea, but as I said in the title gin should give me some warning or error info rather a empty value
Description
ctx.GetString(key) should show some err info when cannot convert to a resonable value rather than return a wrong value with no more err info
How to reproduce
Expectations
Actual result
Environment