github.com/pavlo67/common@v0.5.3/common/f/f.go (about)

     1  package f
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"reflect"
     7  )
     8  
     9  func J(v interface{}) string {
    10  	jsonBytes, err := json.Marshal(v)
    11  	if err != nil {
    12  		return fmt.Sprintf("%+v", v)
    13  	}
    14  
    15  	return string(jsonBytes)
    16  }
    17  
    18  func JB(v interface{}) []byte {
    19  	jsonBytes, err := json.Marshal(v)
    20  	if err != nil {
    21  		return []byte(fmt.Sprintf("%+v", v))
    22  	}
    23  
    24  	return jsonBytes
    25  }
    26  
    27  type KeyValue struct {
    28  	Name  string
    29  	Value interface{}
    30  }
    31  
    32  func NonEmptyStructValues(data interface{}) []KeyValue {
    33  
    34  	structIterator := reflect.ValueOf(data)
    35  	if structIterator.Kind() != reflect.Struct {
    36  		return nil
    37  	}
    38  
    39  	var keyValues []KeyValue
    40  	for i := 0; i < structIterator.NumField(); i++ {
    41  		field := structIterator.Type().Field(i).Name
    42  		val := structIterator.Field(i).Interface()
    43  
    44  		// Check if the field is zero-valued, meaning it won't be updated
    45  		if !reflect.DeepEqual(val, reflect.Zero(structIterator.Field(i).Type()).Interface()) {
    46  			// fmt.Printf("%v is non-zero, adding to update\n", field)
    47  			keyValues = append(keyValues, KeyValue{
    48  				Name:  field,
    49  				Value: val,
    50  			})
    51  		}
    52  	}
    53  
    54  	return keyValues
    55  }