conv.go 2.0 KB

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