github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/providers/component-protocol/cptype/extra.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     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 cptype
    16  
    17  import (
    18  	"strconv"
    19  
    20  	"github.com/erda-project/erda-infra/pkg/strutil"
    21  )
    22  
    23  // Extra is a magic fields, and will be flat if specified in protocol.
    24  type Extra struct {
    25  	Extra ExtraMap `json:"extra,omitempty"`
    26  }
    27  
    28  // ExtraMap .
    29  type ExtraMap map[string]interface{}
    30  
    31  // Uint64 .
    32  func (e Extra) Uint64(key string) uint64 {
    33  	return e.Extra.Uint64(key)
    34  }
    35  
    36  // String .
    37  func (e Extra) String(key string) string {
    38  	return e.Extra.String(key)
    39  }
    40  
    41  // Uint64 .
    42  func (em ExtraMap) Uint64(key string) uint64 {
    43  	if len(em) == 0 {
    44  		return 0
    45  	}
    46  	v, ok := em[key]
    47  	if !ok {
    48  		return 0
    49  	}
    50  	switch vv := v.(type) {
    51  	case float64:
    52  		return uint64(vv)
    53  	case string:
    54  		r, _ := strconv.ParseUint(vv, 10, 64)
    55  		return r
    56  	}
    57  	return 0
    58  }
    59  
    60  // String .
    61  func (em ExtraMap) String(key string) string {
    62  	if len(em) == 0 {
    63  		return ""
    64  	}
    65  	v, ok := em[key]
    66  	if !ok {
    67  		return ""
    68  	}
    69  	return strutil.String(v)
    70  }
    71  
    72  // Get .
    73  func (em ExtraMap) Get(key string) interface{} {
    74  	if len(em) == 0 {
    75  		return nil
    76  	}
    77  	v, ok := em[key]
    78  	if !ok {
    79  		return nil
    80  	}
    81  	return v
    82  }