コード例 #1
0
// JsonMarshaller is an example of a MarshalMethod that is passed to NewEncode().
//
// If a different data marshaller is desired, such as XML, YAML, etc.  Use this as a template.
func JsonMarshaller(in interface{}, out *rpb.RpbContent) error {
	jsondata, err := json.Marshal(in)
	if err != nil {
		return err
	}
	out.Value = jsondata
	out.ContentType = []byte("application/json")
	return nil
}
コード例 #2
0
func (c *StructMarshal) process(carry string, e reflect.Value, out *rpb.RpbContent) {
	for i := 0; i < e.NumField(); i++ {
		if !e.Field(i).CanSet() {
			continue
		}

		val := e.Field(i).Interface()
		fld := e.Type().Field(i)
		knd := e.Field(i).Kind()
		tag := fld.Tag

		// Skip anonymous fields
		if fld.Anonymous {
			continue
		}

		// Continue to process nested structs
		if knd == reflect.Struct {
			c.process(fld.Name+"_", e.Field(i), out)
		}

		if tag.Get(c.tag) == "" {
			continue
		}

		if tdata := tag.Get("riak"); tdata != "" {
			for _, tfield := range strings.Split(tdata, ",") {
				switch tfield {
				case "index":
					index := &rpb.RpbPair{}
					var key string
					switch knd {
					case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
						key = carry + fld.Name + "_int"
						switch knd {
						case reflect.Int:
							index.Value = []byte(strconv.Itoa(int(val.(int))))
							break
						case reflect.Int8:
							index.Value = []byte(strconv.Itoa(int(val.(int8))))
							break
						case reflect.Int16:
							index.Value = []byte(strconv.Itoa(int(val.(int16))))
							break
						case reflect.Int32:
							index.Value = []byte(strconv.Itoa(int(val.(int32))))
							break
						case reflect.Int64:
							index.Value = []byte(strconv.Itoa(int(val.(int64))))
							break
						}
						index.Key = []byte(strings.ToLower(key))
						break
					case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
						key = carry + fld.Name + "_int"
						switch knd {
						case reflect.Uint:
							index.Value = []byte(strconv.Itoa(int(val.(uint))))
							break
						case reflect.Uint8:
							index.Value = []byte(strconv.Itoa(int(val.(uint8))))
							break
						case reflect.Uint16:
							index.Value = []byte(strconv.Itoa(int(val.(uint16))))
							break
						case reflect.Uint32:
							index.Value = []byte(strconv.Itoa(int(val.(uint32))))
							break
						case reflect.Uint64:
							index.Value = []byte(strconv.Itoa(int(val.(uint64))))
							break
						}
						index.Key = []byte(strings.ToLower(key))
						break
					case reflect.String:
						key = carry + fld.Name + "_bin"
						index.Key = []byte(strings.ToLower(key))
						index.Value = []byte(val.(string))
						break
					case reflect.Slice:
						if fld.Type == typeOfBytes {
							key = carry + fld.Name + "_bin"
							index.Key = []byte(strings.ToLower(key))
							index.Value = []byte(val.([]byte))
						}
						break
					}
					out.Indexes = append(out.Indexes, index)
					break
				}
			}
		}
	}
}