这里增加一点难度,顺便可以检测一下这个项目的扩展性。
新的需求:支持字符串的回文,反转,随机化
简单设计:添加一个操作包,主要完成上述需求,每个函数实现一个功能。主函数链接操作包和服务包,完成上述功能。
代码实现:
package protocol
import (
"bytes"
"encoding/binary"
)
const (
MsgLength = 4
)
type Protocol struct {
msgBuf []byte
}
func New() *Protocol {
pro := &Protocol{msgBuf: make([]byte, 0)}
return pro
}
func (pro *Protocol) PushStream(buf []byte) {
pro.msgBuf = append(pro.msgBuf, buf...)
}
func (pro *Protocol) Enpack(message []byte) []byte {
Header := make([]byte, 0)
return append(append(Header, IntToBytes(len(message))...), message...)
}
func (pro *Protocol) Depack() []string {
Msg := make([]string, 0)
buffer := pro.msgBuf
BufLen := len(pro.msgBuf)
i := 0
for i < BufLen {
if BufLen < i+MsgLength {
break
}
msgLen := BytesToInt(buffer[i : i+MsgLength])
if msgLen > 0 && msgLen < 2<<32 {
if BufLen < i+MsgLength+msgLen {
break
}
data := buffer[i+MsgLength : i+MsgLength+msgLen]
Msg = append(Msg, string(data))
i += MsgLength + msgLen
}
}
if i == BufLen {
pro.msgBuf = make([]byte, 0)
} else {
pro.msgBuf = buffer[i:]
}
return Msg
}
func IntToBytes(n int) []byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
func BytesToInt(b []byte) int {
bytesBuffer := bytes.NewBuffer(b)
var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
return int(x)
}
总结:现在项目各个模块已经完成,就差一个main一个串联类,单元测试和功能性测试已经测过。但是代码整体构造太乱,没有一定的逻辑并由于对于golang语言的特性熟悉,太难写出好的代码。学以致用,使用混乱没有完美的使用这些知识,代码需要重构。暂时不给出核心代码。