Ejemplo n.º 1
0
func (store *BoltStore) put(bucket *bolt.Bucket, key string, value interface{}) error {
	var err error
	if is_value_basic(value) {
		if key == "" {
			return fmt.Errorf("key is absent")
		}
		byts, err := store.coder.Encode(value)
		if err != nil {
			return err
		}
		return bucket.Put([]byte(key), byts)
	}

	if key != "" {
		bucket, err = bucket.CreateBucketIfNotExists([]byte(key))
		if err != nil {
			return err
		}
	}

	switch value_type_kind(value) {
	case reflect.Slice:
		vs := reflect.ValueOf(value)
		for i := 0; i < vs.Len(); i++ {
			if err := store.put(bucket, strconv.Itoa(i), vs.Index(i).Interface()); err != nil {
				return err
			}
		}
		return nil
	case reflect.Map:
		vs, err := cast.ToStringMapE(value)
		if err != nil {
			return err
		}
		for k, v := range vs {
			if err := store.put(bucket, k, v); err != nil {
				return err
			}
		}
		return nil
	case reflect.Struct:
		vt := reflect.TypeOf(value)
		vv := reflect.ValueOf(value)
		for i := 0; i < vt.NumField(); i++ {
			vfield := vt.Field(i)
			if tag := vfield.Tag.Get("object"); tag != "" {
				if err := store.put(bucket, tag, vv.Field(i).Interface()); err != nil {
					return err
				}
			}
		}
		return nil
	}
	return fmt.Errorf("unsupport store value type")
}
Ejemplo n.º 2
0
func (ns *Namespace) SetValue(value interface{}) error {
	if is_value_basic(value) {
		return errors.New("value is basic type")
	}

	switch value_type_kind(value) {
	case reflect.Slice:
		vs := reflect.ValueOf(value)
		for i := 0; i < vs.Len(); i++ {
			if err := ns.Set(strconv.Itoa(i), vs.Index(i).Interface()); err != nil {
				return err
			}
		}
		return nil
	case reflect.Map:
		objs, err := cast.ToStringMapE(value)
		if err != nil {
			return err
		}

		for k, v := range objs {
			if err := ns.Set(k, v); err != nil {
				return err
			}
		}
		return nil
	case reflect.Struct:
		vt := reflect.TypeOf(value)
		vv := reflect.ValueOf(value)
		for i := 0; i < vt.NumField(); i++ {
			vfield := vt.Field(i)
			if tag := vfield.Tag.Get("object"); tag != "" {
				if err := ns.Set(tag, vv.Field(i).Interface()); err != nil {
					return err
				}
			}
		}
		return nil
	}
	return errors.New("unknow error")
}