github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/cache/conv.go (about) 1 // The package is migrated from beego, you can get from following link: 2 // import( 3 // 4 // "github.com/beego/beego/v2/client/cache" 5 // 6 // ) 7 // Copyright 2023. All Rights Reserved. 8 // 9 // Licensed under the Apache License, Version 2.0 (the "License"); 10 // you may not use this file except in compliance with the License. 11 // You may obtain a copy of the License at 12 // 13 // http://www.apache.org/licenses/LICENSE-2.0 14 // 15 // Unless required by applicable law or agreed to in writing, software 16 // distributed under the License is distributed on an "AS IS" BASIS, 17 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 // See the License for the specific language governing permissions and 19 // limitations under the License. 20 package cache 21 22 import ( 23 "fmt" 24 "strconv" 25 ) 26 27 // GetString converts interface to string. 28 func GetString(v interface{}) string { 29 switch result := v.(type) { 30 case string: 31 return result 32 case []byte: 33 return string(result) 34 default: 35 if v != nil { 36 return fmt.Sprint(result) 37 } 38 } 39 return "" 40 } 41 42 // GetInt converts interface to int. 43 func GetInt(v interface{}) int { 44 switch result := v.(type) { 45 case int: 46 return result 47 case int32: 48 return int(result) 49 case int64: 50 return int(result) 51 default: 52 if d := GetString(v); d != "" { 53 value, _ := strconv.Atoi(d) 54 return value 55 } 56 } 57 return 0 58 } 59 60 // GetInt64 converts interface to int64. 61 func GetInt64(v interface{}) int64 { 62 switch result := v.(type) { 63 case int: 64 return int64(result) 65 case int32: 66 return int64(result) 67 case int64: 68 return result 69 default: 70 71 if d := GetString(v); d != "" { 72 value, _ := strconv.ParseInt(d, 10, 64) 73 return value 74 } 75 } 76 return 0 77 } 78 79 // GetFloat64 converts interface to float64. 80 func GetFloat64(v interface{}) float64 { 81 switch result := v.(type) { 82 case float64: 83 return result 84 default: 85 if d := GetString(v); d != "" { 86 value, _ := strconv.ParseFloat(d, 64) 87 return value 88 } 89 } 90 return 0 91 } 92 93 // GetBool converts interface to bool. 94 func GetBool(v interface{}) bool { 95 switch result := v.(type) { 96 case bool: 97 return result 98 default: 99 if d := GetString(v); d != "" { 100 value, _ := strconv.ParseBool(d) 101 return value 102 } 103 } 104 return false 105 }