github.com/DaAlbrecht/cf-cli@v0.0.0-20231128151943-1fe19bb400b9/types/optional_object.go (about)

     1  package types
     2  
     3  import "encoding/json"
     4  
     5  // OptionalObject is for situations where we want to differentiate between an
     6  // empty object, and the object not having been set. An example would be an
     7  // optional command line option where we want to tell the difference between
     8  // it being set to an empty object, and it not being specified at all.
     9  type OptionalObject struct {
    10  	IsSet bool
    11  	Value map[string]interface{}
    12  }
    13  
    14  func NewOptionalObject(v map[string]interface{}) OptionalObject {
    15  	if v == nil {
    16  		// This ensures that when IsSet==true, we always have an empty map as the value which
    17  		// marshals to `{}` and not a nil map which marshals to `null`
    18  		v = make(map[string]interface{})
    19  	}
    20  
    21  	return OptionalObject{
    22  		IsSet: true,
    23  		Value: v,
    24  	}
    25  }
    26  
    27  func (o *OptionalObject) UnmarshalJSON(rawJSON []byte) error {
    28  	var receiver map[string]interface{}
    29  	if err := json.Unmarshal(rawJSON, &receiver); err != nil {
    30  		return err
    31  	}
    32  
    33  	*o = NewOptionalObject(receiver)
    34  	return nil
    35  }
    36  
    37  func (o OptionalObject) MarshalJSON() ([]byte, error) {
    38  	return json.Marshal(o.Value)
    39  }
    40  
    41  func (o OptionalObject) OmitJSONry() bool {
    42  	return !o.IsSet
    43  }