Hprose 过滤器 - 压缩传输
优质
小牛编辑
130浏览
2023-12-01
上面的例子,我们只使用了一个过滤器。在本例中,我们展示多个过滤器组合使用的效果。
compress_filter.go
- package main
- import (
- "compress/gzip"
- "io/ioutil"
- "github.com/hprose/hprose-golang/io"
- "github.com/hprose/hprose-golang/rpc"
- )
- // CompressFilter ...
- type CompressFilter struct{}
- // InputFilter ...
- func (CompressFilter) InputFilter(data []byte, context rpc.Context) []byte {
- b := io.NewByteReader(data)
- reader, _ := gzip.NewReader(b)
- defer reader.Close()
- data, _ = ioutil.ReadAll(reader)
- return data
- }
- // OutputFilter ...
- func (CompressFilter) OutputFilter(data []byte, context rpc.Context) []byte {
- b := &io.ByteWriter{}
- writer := gzip.NewWriter(b)
- writer.Write(data)
- writer.Flush()
- return b.Bytes()
- }
size_filter.go
- package main
- import (
- "fmt"
- "github.com/hprose/hprose-golang/rpc"
- )
- // SizeFilter ...
- type SizeFilter struct {
- Message string
- }
- // InputFilter ...
- func (sf SizeFilter) InputFilter(data []byte, context rpc.Context) []byte {
- fmt.Printf("%v input size: %d\r\n", sf.Message, len(data))
- return data
- }
- // OutputFilter ...
- func (sf SizeFilter) OutputFilter(data []byte, context rpc.Context) []byte {
- fmt.Printf("%v output size: %d\r\n", sf.Message, len(data))
- return data
- }
main.go
- package main
- import (
- "fmt"
- "github.com/hprose/hprose-golang/rpc"
- )
- // TestService is ...
- type TestService struct {
- Test func([]int) ([]int, error)
- }
- func main() {
- server := rpc.NewTCPServer("")
- server.AddFunction("test", func(data []int) []int {
- return data
- }).
- AddFilter(
- SizeFilter{"Non compressed data on server"},
- CompressFilter{},
- SizeFilter{"Compressed data on server"},
- )
- server.Debug = true
- server.Handle()
- client := rpc.NewClient(server.URI())
- client.AddFilter(
- SizeFilter{"Non compressed data on client"},
- CompressFilter{},
- SizeFilter{"Compressed data on client"},
- )
- var testService *TestService
- client.UseService(&testService)
- args := make([]int, 100000)
- for i := range args {
- args[i] = i
- }
- result, err := testService.Test(args)
- fmt.Println(len(result), err)
- client.Close()
- server.Close()
- }
运行该程序,你会看到运行结果:
Non compressed data on client output size: 688893
Compressed data on client output size: 213244
Compressed data on server input size: 213244
Non compressed data on server input size: 688893
Non compressed data on server output size: 688881
Compressed data on server output size: 213223
Compressed data on client input size: 213223
Non compressed data on client input size: 688881
100000 <nil>
加密跟这个类似,这里就不再单独举加密的例子了。