GolangNote

Golang笔记

golang gencode 序列化/反序列化数据

Permalink

andyleap/gencode 是一个快速的且体积很小的序列化库。

首先定义数据结构:test.schema

Go: 定义数据结构
1
2
3
4
struct Person {
    Name string
    Age uint8
}

然后通过gencode 命令行生成test.schema.gen.go:

Bash: gencode
1
$ gencode go -schema test.schema -package main

下面是结合bolt 来存储数据:

Go: 结合bolt 来存储数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/boltdb/bolt"
)

func main() {

	db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte("person"))
		if err != nil {
			return err
		}
		return nil
	})

	person := Person{
		Name: "testname",
		Age:  20,
	}

	db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("person"))

		buf, _ := person.Marshal(nil)
		fmt.Println(buf, string(buf))
		b.Put([]byte(person.Name), buf)

		fmt.Printf("Gencode encoded size: %v\n", len(buf))

		return nil
	})

	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("person"))

		if err := b.ForEach(func(k, v []byte) error {
			fmt.Printf("%s is %s.\n", k, v)
			p := Person{}
			p.Unmarshal(v)
			fmt.Println(p)
			return nil
		}); err != nil {
			return err
		}

		return nil
	})

}

输出:

plaintext: 输出结果
1
2
3
4
[8 116 101 115 116 110 97 109 101 20]testname
Gencode encoded size: 10
testname istestname.
{testname 20}

因为 gencode 不会写入字段的名字,所以体积很小,正因为如此,用 gencode 序列化和反序列化数据时应该注意,数据结构不能动态改变。

andyleap/gencode https://github.com/andyleap/gencode

本文网址: https://golangnote.com/topic/172.html 转摘请注明来源

Related articles

golang共享数据用Mutex 或 Channel

在go 里,多线程对共享数据的操作一般要使用Mutex 或 Channel 来加锁或隔离通信。下面是一个使用Mutex 和 Channel 比较的例子。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Write a Comment to "golang gencode 序列化/反序列化数据"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms