yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/hcso/client/responses/responses.go (about)

     1  // Copyright 2019 Yunion
     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 responses
    16  
    17  import (
    18  	"regexp"
    19  	"strings"
    20  
    21  	"yunion.io/x/jsonutils"
    22  )
    23  
    24  type ListResult struct {
    25  	Data     []jsonutils.JSONObject
    26  	Total    int
    27  	Limit    int
    28  	Offset   int
    29  	NextLink string
    30  }
    31  
    32  func ListResult2JSONWithKey(result *ListResult, key string) jsonutils.JSONObject {
    33  	obj := jsonutils.NewDict()
    34  	if result.Total > 0 {
    35  		obj.Add(jsonutils.NewInt(int64(result.Total)), "total")
    36  	}
    37  	if result.Limit > 0 {
    38  		obj.Add(jsonutils.NewInt(int64(result.Limit)), "limit")
    39  	}
    40  	if result.Offset > 0 {
    41  		obj.Add(jsonutils.NewInt(int64(result.Offset)), "offset")
    42  	}
    43  	arr := jsonutils.NewArray(result.Data...)
    44  	obj.Add(arr, key)
    45  	return obj
    46  }
    47  
    48  func ListResult2JSON(result *ListResult) jsonutils.JSONObject {
    49  	return ListResult2JSONWithKey(result, "data")
    50  }
    51  
    52  func JSON2ListResult(result jsonutils.JSONObject) *ListResult {
    53  	total, _ := result.Int("total")
    54  	limit, _ := result.Int("limit")
    55  	offset, _ := result.Int("offset")
    56  	data, _ := result.GetArray("data")
    57  	return &ListResult{Data: data, Total: int(total), Limit: int(limit), Offset: int(offset)}
    58  }
    59  
    60  // 将key中的冒号替换成
    61  func TransColonToDot(obj jsonutils.JSONObject) (jsonutils.JSONObject, error) {
    62  	re, _ := regexp.Compile("[a-zA-Z0-9](:+)[^\"]+\"\\s*:\\s*")
    63  
    64  	if obj == nil {
    65  		return obj, nil
    66  	}
    67  
    68  	newStr := re.ReplaceAllStringFunc(obj.String(), func(s string) string {
    69  		count := strings.Count(s, ":")
    70  		if count > 1 {
    71  			return strings.Replace(s, ":", ".", count-1)
    72  		}
    73  		return s
    74  	})
    75  
    76  	return jsonutils.ParseString(newStr)
    77  }