github.com/astaxie/beego@v1.12.3/cache/conv.go (about)

     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  
    15  package cache
    16  
    17  import (
    18  	"fmt"
    19  	"strconv"
    20  )
    21  
    22  // GetString convert interface to string.
    23  func GetString(v interface{}) string {
    24  	switch result := v.(type) {
    25  	case string:
    26  		return result
    27  	case []byte:
    28  		return string(result)
    29  	default:
    30  		if v != nil {
    31  			return fmt.Sprint(result)
    32  		}
    33  	}
    34  	return ""
    35  }
    36  
    37  // GetInt convert interface to int.
    38  func GetInt(v interface{}) int {
    39  	switch result := v.(type) {
    40  	case int:
    41  		return result
    42  	case int32:
    43  		return int(result)
    44  	case int64:
    45  		return int(result)
    46  	default:
    47  		if d := GetString(v); d != "" {
    48  			value, _ := strconv.Atoi(d)
    49  			return value
    50  		}
    51  	}
    52  	return 0
    53  }
    54  
    55  // GetInt64 convert interface to int64.
    56  func GetInt64(v interface{}) int64 {
    57  	switch result := v.(type) {
    58  	case int:
    59  		return int64(result)
    60  	case int32:
    61  		return int64(result)
    62  	case int64:
    63  		return result
    64  	default:
    65  
    66  		if d := GetString(v); d != "" {
    67  			value, _ := strconv.ParseInt(d, 10, 64)
    68  			return value
    69  		}
    70  	}
    71  	return 0
    72  }
    73  
    74  // GetFloat64 convert interface to float64.
    75  func GetFloat64(v interface{}) float64 {
    76  	switch result := v.(type) {
    77  	case float64:
    78  		return result
    79  	default:
    80  		if d := GetString(v); d != "" {
    81  			value, _ := strconv.ParseFloat(d, 64)
    82  			return value
    83  		}
    84  	}
    85  	return 0
    86  }
    87  
    88  // GetBool convert interface to bool.
    89  func GetBool(v interface{}) bool {
    90  	switch result := v.(type) {
    91  	case bool:
    92  		return result
    93  	default:
    94  		if d := GetString(v); d != "" {
    95  			value, _ := strconv.ParseBool(d)
    96  			return value
    97  		}
    98  	}
    99  	return false
   100  }