golang 使用gzip对json例子

package main

import (

"bytes"

"compress/gzip"

"encoding/json"

"fmt"

"io"

"log"

)

// User 结构体定义

type User struct {

ID int `json:"id"`

Name string `json:"name"`

Age int `json:"age"`

Fee float64 `json:"fee"`

}

// gzipCompress 将任何类型的接口压缩为 Gzip 格式

func gzipCompress(v interface{}) (\[\]byte, error) {

// 将结构体转换为JSON字节切片

jsonData, err := json.Marshal(v)

if err != nil {

return nil, err

}

var buf bytes.Buffer

// 创建Gzip Writer

w := gzip.NewWriter(&buf)

if _, err := w.Write(jsonData); err != nil {

return nil, err

}

// 关闭Gzip Writer

if err := w.Close(); err != nil {

return nil, err

}

return buf.Bytes(), nil

}

// gzipDecompress 解压缩 Gzip 数据,填充到目标结构体

func gzipDecompress(compressedData \[\]byte, v interface{}) error {

r, err := gzip.NewReader(bytes.NewReader(compressedData))

if err != nil {

return err

}

defer r.Close()

// 读取解压缩后的数据

decompressedData, err := io.ReadAll(r)

if err != nil {

return err

}

// 将JSON数据解码到目标结构体

return json.Unmarshal(decompressedData, v)

}

// 主函数

func main() {

// 创建示例用户数据

user := User{

ID: 1,

Name: "Alice",

Age: 30,

Fee: 1500.00,

}

// 压缩JSON数据

compressedData, err := gzipCompress(user)

if err != nil {

log.Fatal(err)

}

fmt.Printf("Compressed Data (Gzip bytes): %v\n", compressedData)

// 解压缩回原始的用户数据

var decompressedUser User

if err := gzipDecompress(compressedData, &decompressedUser); err != nil {

log.Fatal(err)

}

// 输出解压缩后的数据

fmt.Printf("Decompressed User: %+v\n", decompressedUser)

}

输出:

Compressed Data (Gzip bytes): 31 139 8 0 0 0 0 0 0 255 170 86 202 76 81 178 50 212 81 202 75 204 77 85 178 82 114 204 201 76 78 85 210 81 74 76 79 85 178 50 54 208 81 74 75 77 85 178 50 52 53 48 168 5 4 0 0 255 255 212 252 187 47 43 0 0 0

Decompressed User: {ID:1 Name:Alice Age:30 Fee:1500}

相关推荐
SomeOtherTime3 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood3 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青4 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
饮水桶_T8 小时前
JAVA IO流笔记
开发语言·数据结构·算法
Felven10 小时前
C. Brr Brrr Patapim
c语言·开发语言
路溪非溪11 小时前
python标准库使用总结
开发语言·python
SomeOtherTime13 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
zh_xuan13 小时前
kotlin常见面试题
开发语言·kotlin·面试题
草莓熊Lotso15 小时前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试
huaqianzkh16 小时前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#