检验数据流是否完整

数据是任何业务不可脱离的基础,对于牵涉众多数据的金融行业更为重要,如何保证业务数据传输时的完整对于金融业的App极其重要。本次的代码是简单的测试数据流的完整性

type Packet struct {
	header Header
	body   []byte
	tailer Tailer
}
type Header struct {
	bodylen  uint32
	msgtype  uint32
	add      uint32
	userdata uint32
}
type Tailer struct {
	checkcode uint32
}

func TestPacketSize(t *testing.T) {
	datapoint := new(Packet)
	log.Println("packet size is ", unsafe.Sizeof(datapoint))
	var data Packet
	log.Println("packet size is ", unsafe.Sizeof(data)) //body []byte default size is 24

	p := NewPacket(1, []byte("this is test data"))
	log.Println("p size is ", unsafe.Sizeof(p))               // 8
	log.Println("p.header size is ", unsafe.Sizeof(p.header)) //8 add 12 userdata 16
	log.Println("p.body length is ", len(p.body))             //17
	log.Println("p.header.bodylen is ", p.header.bodylen)     //17
}
func TestIsComplete(t *testing.T) {
	p := NewPacket(1, []byte("this is test data"))
	log.Println("p size is ", unsafe.Sizeof(p))
	log.Println("p is ", p)
	buf := PacketData(1, []byte("this is test data"))
	log.Println("buf size is ", unsafe.Sizeof(buf))
	log.Println("buf is ", buf)
	checkbuf := PacketData(p.header.msgtype, p.body)
	out := IsComplete(buf, checkbuf)
	if len(out) == 0 {
		log.Println("there are some error of this packet data")
	} else {
		log.Println("out length is ", len(out))
		log.Println("out is ", out)
	}
	var outbuf []byte
	log.Println("outbuf length is ", len(outbuf))
	log.Println("outbuf is ", outbuf)

}
func IsComplete(buf, checkbuf []byte) (outbuf []byte) {
	length := len(buf)
	if length != len(checkbuf) {
		log.Println("data is not complete")
		return
	} else {
		if buf[length-1] != checkbuf[length-1] {
			log.Println("checkcode is wrong")
			return
		} else {
			for i := 0; i < length; i++ {
				if buf[i] != checkbuf[i] {
					log.Println("data may be complete,but it's wrong data")
					return
				}
			}
			outbuf = buf[16 : length-4]
			return
		}

	}
}

func NewPacket(msg uint32, b []byte) *Packet {
	length := len(b)
	log.Println("body length is ", length) //17
	return &Packet{
		header: Header{
			msgtype:  msg,
			bodylen:  uint32(length),
			add:      1,
			userdata: 2,
		},
		body: b,
	}
}

func GenerateCheckCode(indata []byte) (out uint32) {
	for _, v := range indata {
		out += uint32(v)
	}
	out = out % 256
	return
}
func PacketData(msgtype uint32, data []byte) (buf []byte) {
	header := make([]byte, 16)
	binary.BigEndian.PutUint32(header[0:4], msgtype)
	bodylen := uint32(len(data))
	binary.BigEndian.PutUint32(header[4:8], bodylen)
	userdata1 := uint32(1)
	binary.BigEndian.PutUint32(header[8:12], userdata1)
	userdata2 := uint32(2)
	binary.BigEndian.PutUint32(header[12:16], userdata2)
	buf = make([]byte, bodylen+20)
	copy(buf[0:16], header[0:16])
	copy(buf[16:], data[:])
	tail := make([]byte, 4)
	check := GenerateCheckCode(buf)
	binary.BigEndian.PutUint32(tail[0:4], check)
	copy(buf[bodylen+16:], tail[:])
	return
}

运行结果
在这里插入图片描述