1 // Copyright 2020 Huawei Technologies Co.,Ltd.
2 //
3 // Licensed to the Apache Software Foundation (ASF) under one
4 // or more contributor license agreements. See the NOTICE file
5 // distributed with this work for additional information
6 // regarding copyright ownership. The ASF licenses this file
7 // to you under the Apache License, Version 2.0 (the
8 // "License"); you may not use this file except in compliance
9 // with the License. You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing,
14 // software distributed under the License is distributed on an
15 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 // KIND, either express or implied. See the License for the
17 // specific language governing permissions and limitations
18 // under the License.
19 20 package converter
21 22 import (
23 "reflect"
24 "strconv"
25 "strings"
26 27 "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/utils"
28 )
29 30 type Converter interface {
31 CovertStringToInterface(value string) (interface{}, error)
32 CovertStringToPrimitiveTypeAndSetField(field reflect.Value, value string, isPtr bool) error
33 }
34 35 func StringConverterFactory(vType string) Converter {
36 switch vType {
37 case "string":
38 return StringConverter{}
39 case "int32":
40 return Int32Converter{}
41 case "int64":
42 return Int64Converter{}
43 case "float32":
44 return Float32Converter{}
45 case "float64":
46 return Float32Converter{}
47 case "bool":
48 return BooleanConverter{}
49 default:
50 return nil
51 }
52 }
53 54 func ConvertInterfaceToString(value interface{}) string {
55 if value == nil {
56 return ""
57 }
58 switch value.(type) {
59 case float64:
60 return strconv.FormatFloat(value.(float64), 'f', -1, 64)
61 case float32:
62 return strconv.FormatFloat(float64(value.(float32)), 'f', -1, 64)
63 case int:
64 return strconv.Itoa(value.(int))
65 case uint:
66 return strconv.Itoa(int(value.(uint)))
67 case int8:
68 return strconv.Itoa(int(value.(int8)))
69 case uint8:
70 return strconv.Itoa(int(value.(uint8)))
71 case int16:
72 return strconv.Itoa(int(value.(int16)))
73 case uint16:
74 return strconv.Itoa(int(value.(uint16)))
75 case int32:
76 return strconv.Itoa(int(value.(int32)))
77 case uint32:
78 return strconv.Itoa(int(value.(uint32)))
79 case int64:
80 return strconv.FormatInt(value.(int64), 10)
81 case uint64:
82 return strconv.FormatUint(value.(uint64), 10)
83 case bool:
84 return strconv.FormatBool(value.(bool))
85 case string:
86 return value.(string)
87 case []byte:
88 return string(value.([]byte))
89 default:
90 b, err := utils.Marshal(value)
91 if err != nil {
92 return ""
93 }
94 return strings.Trim(string(b[:]), "\"")
95 }
96 }
97