github.com/Jeffail/benthos/v3@v3.65.0/lib/broker/config_utils.go (about)

     1  package broker
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  //------------------------------------------------------------------------------
     8  
     9  // GetGenericType returns the type of a generically parsed config structure.
    10  func GetGenericType(boxedConfig interface{}) string {
    11  	switch unboxed := boxedConfig.(type) {
    12  	case map[string]interface{}:
    13  		if t, ok := unboxed["type"].(string); ok {
    14  			return t
    15  		}
    16  	case map[interface{}]interface{}:
    17  		if t, ok := unboxed["type"].(string); ok {
    18  			return t
    19  		}
    20  	}
    21  	return ""
    22  }
    23  
    24  // RemoveGenericType removes the type of a generically parsed config structure.
    25  func RemoveGenericType(boxedConfig interface{}) {
    26  	switch unboxed := boxedConfig.(type) {
    27  	case map[string]interface{}:
    28  		delete(unboxed, "type")
    29  	case map[interface{}]interface{}:
    30  		delete(unboxed, "type")
    31  	}
    32  }
    33  
    34  // ComplementGenericConfig copies fields from one generic config to another, but
    35  // avoids overriding existing values in the destination config.
    36  func ComplementGenericConfig(target, complement interface{}) error {
    37  	switch t := target.(type) {
    38  	case map[string]interface{}:
    39  		cMap, ok := complement.(map[string]interface{})
    40  		if !ok {
    41  			return fmt.Errorf("ditto config type mismatch: %T != %T", target, complement)
    42  		}
    43  		for k, v := range cMap {
    44  			if tv, exists := t[k]; !exists {
    45  				t[k] = v
    46  			} else {
    47  				_ = ComplementGenericConfig(tv, v)
    48  			}
    49  		}
    50  	case map[interface{}]interface{}:
    51  		cMap, ok := complement.(map[interface{}]interface{})
    52  		if !ok {
    53  			return fmt.Errorf("ditto config type mismatch: %T != %T", target, complement)
    54  		}
    55  		for k, v := range cMap {
    56  			if tv, exists := t[k]; !exists {
    57  				t[k] = v
    58  			} else {
    59  				_ = ComplementGenericConfig(tv, v)
    60  			}
    61  		}
    62  	}
    63  	return nil
    64  }
    65  
    66  //------------------------------------------------------------------------------