github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/repo/common/common.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  func MapGetKV(v map[string]interface{}, key string) (interface{}, error) {
     9  	var ok bool
    10  	var mcursor map[string]interface{}
    11  	var cursor interface{} = v
    12  
    13  	parts := strings.Split(key, ".")
    14  	for i, part := range parts {
    15  		sofar := strings.Join(parts[:i], ".")
    16  
    17  		mcursor, ok = cursor.(map[string]interface{})
    18  		if !ok {
    19  			return nil, fmt.Errorf("%s key is not a map", sofar)
    20  		}
    21  
    22  		cursor, ok = mcursor[part]
    23  		if !ok {
    24  			return nil, fmt.Errorf("%s key has no attributes", sofar)
    25  		}
    26  	}
    27  	return cursor, nil
    28  }
    29  
    30  func MapSetKV(v map[string]interface{}, key string, value interface{}) error {
    31  	var ok bool
    32  	var mcursor map[string]interface{}
    33  	var cursor interface{} = v
    34  
    35  	parts := strings.Split(key, ".")
    36  	for i, part := range parts {
    37  		mcursor, ok = cursor.(map[string]interface{})
    38  		if !ok {
    39  			sofar := strings.Join(parts[:i], ".")
    40  			return fmt.Errorf("%s key is not a map", sofar)
    41  		}
    42  
    43  		// last part? set here
    44  		if i == (len(parts) - 1) {
    45  			mcursor[part] = value
    46  			break
    47  		}
    48  
    49  		cursor, ok = mcursor[part]
    50  		if !ok || cursor == nil { // create map if this is empty or is null
    51  			mcursor[part] = map[string]interface{}{}
    52  			cursor = mcursor[part]
    53  		}
    54  	}
    55  	return nil
    56  }