1 Star 1 Fork 0

flash520/utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
flash520 提交于 2021-07-22 00:59 . add: sumx pack
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
)
type pack struct {
Version []byte
Length int64
Data []byte
}
func main() {
var err error
Pack := pack{
Version: []byte("v1"),
Length: int64(4),
Data: []byte("data"),
}
writer := new(bytes.Buffer)
err = Pack.Pack(writer)
if err != nil {
fmt.Println("打包错误,err: ", err)
return
}
Result := pack{}
err = Result.Unpack(writer)
if err != nil {
fmt.Println("解包错误,err: ", err)
return
}
Result.Data = make([]byte, Result.Length)
err = binary.Read(writer, binary.BigEndian, &Result.Data)
Result.String()
fmt.Println()
}
func (p *pack) Pack(buf io.Writer) error {
var err error
err = binary.Write(buf, binary.BigEndian, &p.Version)
err = binary.Write(buf, binary.BigEndian, &p.Length)
err = binary.Write(buf, binary.BigEndian, &p.Data)
return err
}
func (p *pack) Unpack(r io.Reader) error {
var err error
p.Version = make([]byte, 2)
err = binary.Read(r, binary.BigEndian, &p.Version)
err = binary.Read(r, binary.BigEndian, &p.Length)
//p.Data = make([]byte, p.Length)
//err = binary.Read(r, binary.BigEndian, &p.Data)
return err
}
func (p *pack) String() {
fmt.Printf("Version: %s, Length: %d, Data: %s\n",
p.Version,
p.Length,
string(p.Data),
)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/flash520/utils.git
git@gitee.com:flash520/utils.git
flash520
utils
utils
v1.4.5

搜索帮助