Esempio n. 1
0
// Read read data from reader and unmarshal to specific struct.
// |  4 bytes | 4 bytes | .........
// |  version |   len   | payload |
func Read(r io.Reader, v interface{}) error {
	// read prefix head version
	var ver uint32
	if err := binary.Read(r, binary.BigEndian, &ver); err != nil {
		return err
	}
	if ver != version {
		return fmt.Errorf("invalid request")
	}

	var len uint32
	if err := binary.Read(r, binary.BigEndian, &len); err != nil {
		return err
	}

	if len > maxReqPkgSize {
		return fmt.Errorf("request data length > %v, check if your request is legal", maxReqPkgSize)
	}

	d := make([]byte, len)
	if err := binary.Read(r, binary.BigEndian, &d); err != nil {
		return err
	}
	switch r := v.(type) {
	case *Request:
		if err := json.Unmarshal(d, v); err != nil {
			logger.Error(err.Error())
			return err
		}
		return nil
	case *Response:
		r.Body = bytes.NewBuffer(d)
		return nil
	default:
		return errors.New("unknow read type")
	}
}