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 库推荐

Google 的翻译越来越好了,官方的Golang SDK 已经很完美,这里介绍的是几个非官方发布的有特色的库。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms