github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/conversion.go (about) 1 /* 2 Copyright 2014 The Kubernetes Authors All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 // Defines conversions between generic types and structs to map query strings 18 // to struct objects. 19 package runtime 20 21 import ( 22 "reflect" 23 "strconv" 24 "strings" 25 26 "k8s.io/kubernetes/pkg/conversion" 27 ) 28 29 // JSONKeyMapper uses the struct tags on a conversion to determine the key value for 30 // the other side. Use when mapping from a map[string]* to a struct or vice versa. 31 func JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string) { 32 if s := destTag.Get("json"); len(s) > 0 { 33 return strings.SplitN(s, ",", 2)[0], key 34 } 35 if s := sourceTag.Get("json"); len(s) > 0 { 36 return key, strings.SplitN(s, ",", 2)[0] 37 } 38 return key, key 39 } 40 41 // DefaultStringConversions are helpers for converting []string and string to real values. 42 var DefaultStringConversions = []interface{}{ 43 convertStringSliceToString, 44 convertStringSliceToInt, 45 convertStringSliceToBool, 46 convertStringSliceToInt64, 47 } 48 49 func convertStringSliceToString(input *[]string, out *string, s conversion.Scope) error { 50 if len(*input) == 0 { 51 *out = "" 52 } 53 *out = (*input)[0] 54 return nil 55 } 56 57 func convertStringSliceToInt(input *[]string, out *int, s conversion.Scope) error { 58 if len(*input) == 0 { 59 *out = 0 60 } 61 str := (*input)[0] 62 i, err := strconv.Atoi(str) 63 if err != nil { 64 return err 65 } 66 *out = i 67 return nil 68 } 69 70 // converStringSliceToBool will convert a string parameter to boolean. 71 // Only the absence of a value, a value of "false", or a value of "0" resolve to false. 72 // Any other value (including empty string) resolves to true. 73 func convertStringSliceToBool(input *[]string, out *bool, s conversion.Scope) error { 74 if len(*input) == 0 { 75 *out = false 76 return nil 77 } 78 switch strings.ToLower((*input)[0]) { 79 case "false", "0": 80 *out = false 81 default: 82 *out = true 83 } 84 return nil 85 } 86 87 func convertStringSliceToInt64(input *[]string, out *int64, s conversion.Scope) error { 88 if len(*input) == 0 { 89 *out = 0 90 } 91 str := (*input)[0] 92 i, err := strconv.ParseInt(str, 10, 64) 93 if err != nil { 94 return err 95 } 96 *out = i 97 return nil 98 }