compressor

package module
v0.0.0-...-c96df02 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2024 License: MIT Imports: 10 Imported by: 0

README

Compressor

Compressor is a lightweight middleware for compressing response data. It can be used with gin and orbit frameworks to improve network transmission efficiency.

Compressor utilizes the CodecWriter interface to compress response data. It currently supports the gzip and deflate algorithms. You can also implement your own CodecWriter to support other compression algorithms.

Compressor is built on top of the Go standard library and other powerful packages:

Installation

go get github.com/shengyanli1982/orbit-contrib/pkg/compressor

Quick Start

Config

The Compressor has a config object that can be used to configure the batch process behavior. The config object provides the following methods for configuration:

  • WithCompressLevel: Sets the compression level. The default level is 6.
  • WithWriterCreateFunc: Sets the writer create function. The default function is DefaultWriterCreateFunc.
  • WithMatchFunc: Sets the match function. The default function is DefaultLimitMatchFunc.
  • WithIpWhitelist: Sets the IP whitelist. The default whitelist is DefaultIpWhitelist.
Compressor
1. GZip

The gzip algorithm is the default algorithm used by the Compressor.

Methods

  • HandlerFunc: Returns a gin.HandlerFunc for orbit or gin.
  • Stop: Stops the compressor. This is an empty function and does not need to be called.

Example

package main

import (
	"compress/gzip"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/gin-gonic/gin"
	cr "github.com/shengyanli1982/orbit-contrib/pkg/compressor"
)

var (
	// 测试URL
	// Test URL
	testUrl = "/test"
)

// testRequestFunc 是一个测试请求的函数
// testRequestFunc is a function to test the request
func testRequestFunc(idx int, router *gin.Engine, conf *cr.Config, url string) {
	// 创建一个新的请求
	// Create a new request
	req := httptest.NewRequest(http.MethodGet, url, nil)

	// 创建一个新的响应记录器
	// Create a new response recorder
	resp := httptest.NewRecorder()

	// 使用路由器处理HTTP请求
	// Use the router to handle the HTTP request
	router.ServeHTTP(resp, req)

	// 获取响应体内容
	// Get the content of the response body
	bodyContent := resp.Body.String()

	// 创建一个新的gzip读取器
	// Create a new gzip reader
	gr, _ := gzip.NewReader(resp.Body)
	defer gr.Close()

	// 读取响应的全部内容
	// Read all the content of the response
	plaintext, _ := io.ReadAll(gr)

	// 打印请求的信息
	// Print the information of the request
	fmt.Println("[Request]", idx, resp.Code, url, string(plaintext), bodyContent)
}

func main() {
	// 创建一个新的配置
	// Create a new configuration
	conf := cr.NewConfig()

	// 创建一个新的压缩器
	// Create a new compressor
	compr := cr.NewCompressor(conf)

	// 在函数返回时停止压缩器
	// Stop the compressor when the function returns
	defer compr.Stop()

	// 创建一个新的路由器
	// Create a new router
	router := gin.New()

	// 使用压缩器的处理函数
	// Use the handler function of the compressor
	router.Use(compr.HandlerFunc())

	// 添加一个GET路由
	// Add a GET route
	router.GET(testUrl, func(c *gin.Context) {
		c.String(http.StatusOK, "OK")
	})

	// 测试 10 次请求
	// Test 10 requests
	for i := 0; i < 10; i++ {
		// 调用测试请求函数,传入索引、路由器、配置和测试URL
		// Call the test request function, passing in the index, router, configuration, and test URL
		testRequestFunc(i, router, conf, testUrl)
	}

	// 等待所有请求任务执行完毕
	// Wait for all request tasks to complete
	time.Sleep(time.Second)
}

Result

$ go run demo.go
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /test                     --> main.main.func1 (2 handlers)
[Request] 0 200 /test OK �����-�6�
[Request] 1 200 /test OK �����-�6�
[Request] 2 200 /test OK �����-�6�
[Request] 3 200 /test OK �����-�6�
[Request] 4 200 /test OK �����-�6�
[Request] 5 200 /test OK �����-�6�
[Request] 6 200 /test OK �����-�6�
[Request] 7 200 /test OK �����-�6�
[Request] 8 200 /test OK �����-�6�
[Request] 9 200 /test OK �����-�6�
2. Deflate

Methods

  • HandlerFunc: Returns a gin.HandlerFunc for orbit or gin.
  • Stop: Stops the compressor. It is an empty function and does not need to be called.

Example

package main

import (
	"compress/flate"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/gin-gonic/gin"
	cr "github.com/shengyanli1982/orbit-contrib/pkg/compressor"
)

var (
	// 测试URL
	// Test URL
	testUrl = "/test"
)

// testNewDeflateWriterFunc 是一个创建新的DeflateWriter的函数
// testNewDeflateWriterFunc is a function to create a new DeflateWriter
func testNewDeflateWriterFunc(config *cr.Config, rw gin.ResponseWriter) any {
	return cr.NewDeflateWriter(config, rw)
}

// testRequestFunc 是一个测试请求的函数
// testRequestFunc is a function to test the request
func testRequestFunc(idx int, router *gin.Engine, conf *cr.Config, url string) {
	// 创建一个新的请求
	// Create a new request
	req := httptest.NewRequest(http.MethodGet, url, nil)

	// 创建一个新的记录器
	// Create a new recorder
	resp := httptest.NewRecorder()

	// 服务HTTP
	// Serve HTTP
	router.ServeHTTP(resp, req)

	// 获取响应体内容
	// Get the body content of the response
	bodyContent := resp.Body.String()

	// 创建一个新的flate读取器
	// Create a new flate reader
	gr := flate.NewReader(resp.Body)
	defer gr.Close()

	// 读取所有的明文
	// Read all plaintext
	plaintext, _ := io.ReadAll(gr)

	// 打印请求信息
	// Print request information
	fmt.Println("[Request]", idx, resp.Code, url, string(plaintext), bodyContent)
}

func main() {
	// 创建新的配置
	// Create new configuration
	conf := cr.NewConfig().WithWriterCreateFunc(testNewDeflateWriterFunc)

	// 创建新的压缩器
	// Create new compressor
	compr := cr.NewCompressor(conf)

	// 停止压缩器
	// Stop the compressor
	defer compr.Stop()

	// 创建新的路由器
	// Create new router
	router := gin.New()

	// 使用压缩器的处理函数
	// Use the handler function of the compressor
	router.Use(compr.HandlerFunc())

	// 添加GET路由
	// Add GET route
	router.GET(testUrl, func(c *gin.Context) {
		c.String(http.StatusOK, "OK")
	})

	// 测试 10 次请求
	// Test 10 requests
	for i := 0; i < 10; i++ {
		// 调用测试请求函数,传入索引、路由器、配置和测试URL
		// Call the test request function, passing in the index, router, configuration, and test URL
		testRequestFunc(i, router, conf, testUrl)
	}

	// 等待所有请求任务执行完毕
	// Wait for all request tasks to complete
	time.Sleep(time.Second)
}

Result

$ go run demo.go
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /test                     --> main.main.func1 (2 handlers)
[Request] 0 200 /test OK ����
[Request] 1 200 /test OK ����
[Request] 2 200 /test OK ����
[Request] 3 200 /test OK ����
[Request] 4 200 /test OK ����
[Request] 5 200 /test OK ����
[Request] 6 200 /test OK ����
[Request] 7 200 /test OK ����
[Request] 8 200 /test OK ����
[Request] 9 200 /test OK ����

Documentation

Index

Constants

View Source
const (
	// GZip 内容编码
	// GZip content encoding
	GZipContentEncoding = "gzip"

	// Deflate 内容编码
	// Deflate content encoding
	DeflateContentEncoding = "deflate"
)

定义 GZip 和 Deflate 的内容编码常量 Define content encoding constants for GZip and Deflate

View Source
const (
	// DefaultBestCompression 是默认的最佳压缩等级,值为 9
	// DefaultBestCompression is the default best compression level, the value is 9
	DefaultBestCompression = 9

	// DefaultCompression 是默认的压缩等级,值为 6
	// DefaultCompression is the default compression level, the value is 6
	DefaultCompression = 6

	// DefaultSpeed 是默认的快速压缩等级,值为 3
	// DefaultSpeed is the default fast speed compression level, the value is 3
	DefaultSpeed = 3

	// DefaultBestSpeed 是默认的最佳速度压缩等级,值为 1
	// DefaultBestSpeed is the default best speed compression level, the value is 1
	DefaultBestSpeed = 1

	// DefaultNoCompression 是没有压缩,值为 0
	// DefaultNoCompression is no compression, the value is 0
	DefaultNoCompression = 0
)

Variables

View Source
var DefaultWriterCreateFunc = func(config *Config, rw gin.ResponseWriter) any {

	return NewGZipWriter(config, rw)
}

DefaultWriterCreateFunc 是一个默认的创建压缩写入器的函数,它返回一个 GZipWriter 实例 DefaultWriterCreateFunc is a default function to create a compression writer, it returns a GZipWriter instance

Functions

This section is empty.

Types

type CodecWriter

type CodecWriter interface {
	// 继承了 gin.ResponseWriter 接口,可以进行 HTTP 响应的写入操作
	// Inherits the gin.ResponseWriter interface, which can perform write operations for HTTP responses
	gin.ResponseWriter

	// Write 将字节切片写入响应。返回写入的字节数和可能的错误。
	// Write writes a byte slice to the response. Returns the number of bytes written and the possible error.
	Write(msg []byte) (int, error)

	// WriteString 将字符串写入响应。返回写入的字节数和可能的错误。
	// WriteString writes a string to the response. Returns the number of bytes written and the possible error.
	WriteString(msg string) (int, error)

	// WriteHeader 设置响应的状态码
	// WriteHeader sets the status code of the response
	WriteHeader(code int)

	// ResetCompressWriter 重置压缩编码器的写入器。参数 w 是新的写入器,返回可能的错误。
	// ResetCompressWriter resets the writer of the compression encoder. The parameter w is the new writer, and the possible error is returned.
	ResetCompressWriter(w io.Writer) error

	// ResetResponseWriter 重置响应写入器。参数 rw 是新的响应写入器,返回可能的错误。
	// ResetResponseWriter resets the response writer. The parameter rw is the new response writer, and the possible error is returned.
	ResetResponseWriter(rw gin.ResponseWriter) error

	// ContentEncoding 返回响应的 Content-Encoding
	// ContentEncoding returns the Content-Encoding of the response
	ContentEncoding() string

	// Stop 停止压缩编码器的操作
	// Stop stops the operation of the compression encoder
	Stop()
}

CodecWriter 是一个接口,定义了压缩编码器的写入操作。 CodecWriter is an interface that defines the write operations of a compression encoder.

type Compressor

type Compressor struct {
	// contains filtered or unexported fields
}

Compressor 是一个通用压缩器,包含配置和同步池 Compressor is a common compressor, containing configuration and sync pool

func NewCompressor

func NewCompressor(config *Config) *Compressor

NewCompressor 创建一个新的压缩器,包含有效的配置和同步池 NewCompressor creates a new compressor, including valid configuration and sync pool

func (*Compressor) HandlerFunc

func (c *Compressor) HandlerFunc() gin.HandlerFunc

HandlerFunc 返回一个 gin.HandlerFunc,用于处理请求 HandlerFunc returns a gin.HandlerFunc for processing requests

func (*Compressor) Stop

func (c *Compressor) Stop()

Stop 停止压缩器的操作,这个函数目前是空的,没有具体的实现 Stop stops the operation of the compressor, this function is currently empty, without specific implementation

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config 是一个配置结构体,包含压缩等级、IP白名单、匹配函数和创建压缩写入器的函数 Config is a struct of config, including compression level, IP whitelist, match function and function to create a compression writer

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 创建一个默认的配置实例,实际上就是调用 NewConfig 函数 DefaultConfig creates a default config instance, which is actually calling the NewConfig function

func NewConfig

func NewConfig() *Config

NewConfig 创建一个新的配置实例,包括默认的压缩等级、IP白名单、匹配函数和创建压缩写入器的函数 NewConfig creates a new config instance, including default compression level, IP whitelist, match function and function to create a compression writer

func (*Config) WithCompressLevel

func (c *Config) WithCompressLevel(level int) *Config

WithCompressLevel 设置压缩等级,并返回配置实例 WithCompressLevel sets the compression level and returns the config instance

func (*Config) WithIpWhitelist

func (c *Config) WithIpWhitelist(whitelist []string) *Config

WithIpWhitelist 设置 IP 白名单,并返回配置实例 WithIpWhitelist sets the IP whitelist and returns the config instance

func (*Config) WithMatchFunc

func (c *Config) WithMatchFunc(fn com.HttpRequestHeaderMatchFunc) *Config

WithMatchFunc 设置匹配函数,并返回配置实例 WithMatchFunc sets the match function and returns the config instance

func (*Config) WithWriterCreateFunc

func (c *Config) WithWriterCreateFunc(fn WriterCreateFunc) *Config

WithWriterCreateFunc 设置创建压缩写入器的函数,并返回配置实例 WithWriterCreateFunc sets the function to create a compression writer and returns the config instance

type DeflateWriter

type DeflateWriter struct {
	// 继承 gin 的 ResponseWriter
	// Inherits gin's ResponseWriter
	gin.ResponseWriter
	// contains filtered or unexported fields
}

DeflateWriter 是一个 Deflate 压缩的 ResponseWriter DeflateWriter is a ResponseWriter for Deflate compression

func NewDeflateWriter

func NewDeflateWriter(config *Config, rw gin.ResponseWriter) *DeflateWriter

NewDeflateWriter 创建一个新的 DeflateWriter 实例 NewDeflateWriter creates a new DeflateWriter instance

func (*DeflateWriter) ContentEncoding

func (dw *DeflateWriter) ContentEncoding() string

DeflateWriter 的 ContentEncoding 方法,返回内容编码 ContentEncoding method of DeflateWriter, returns the content encoding

func (*DeflateWriter) ResetCompressWriter

func (dw *DeflateWriter) ResetCompressWriter(w io.Writer) error

DeflateWriter 的 ResetCompressWriter 方法,重置压缩写入器 ResetCompressWriter method of DeflateWriter, resets the compression writer

func (*DeflateWriter) ResetResponseWriter

func (dw *DeflateWriter) ResetResponseWriter(rw gin.ResponseWriter) error

DeflateWriter 的 ResetResponseWriter 方法,重置响应写入器 ResetResponseWriter method of DeflateWriter, resets the response writer

func (*DeflateWriter) Stop

func (dw *DeflateWriter) Stop()

DeflateWriter 的 Stop 方法,关闭写入器 Stop method of DeflateWriter, closes the writer

func (*DeflateWriter) Write

func (dw *DeflateWriter) Write(msg []byte) (int, error)

DeflateWriter 的 Write 方法,删除 "Content-Length" 头部,然后写入消息 Write method of DeflateWriter, deletes the "Content-Length" header, then writes the message

func (*DeflateWriter) WriteHeader

func (dw *DeflateWriter) WriteHeader(code int)

DeflateWriter 的 WriteHeader 方法,删除 "Content-Length" 头部,然后写入状态码 WriteHeader method of DeflateWriter, deletes the "Content-Length" header, then writes the status code

func (*DeflateWriter) WriteString

func (dw *DeflateWriter) WriteString(msg string) (int, error)

DeflateWriter 的 WriteString 方法,将字符串转换为字节并写入 WriteString method of DeflateWriter, converts the string to bytes and writes it

type GZipWriter

type GZipWriter struct {
	// 继承 gin 的 ResponseWriter
	// Inherits gin's ResponseWriter
	gin.ResponseWriter
	// contains filtered or unexported fields
}

GZipWriter 是一个 GZip 压缩的 ResponseWriter GZipWriter is a ResponseWriter for GZip compression

func NewGZipWriter

func NewGZipWriter(config *Config, rw gin.ResponseWriter) *GZipWriter

NewGZipWriter 创建一个新的 GZipWriter 实例 NewGZipWriter creates a new GZipWriter instance

func (*GZipWriter) ContentEncoding

func (gw *GZipWriter) ContentEncoding() string

GZipWriter 的 ContentEncoding 方法,返回内容编码 ContentEncoding method of GZipWriter, return the content encoding

func (*GZipWriter) ResetCompressWriter

func (gw *GZipWriter) ResetCompressWriter(w io.Writer) error

GZipWriter 的 ResetCompressWriter 方法,重置压缩写入器 ResetCompressWriter method of GZipWriter, resets the compression writer

func (*GZipWriter) ResetResponseWriter

func (gw *GZipWriter) ResetResponseWriter(rw gin.ResponseWriter) error

GZipWriter 的 ResetResponseWriter 方法,重置响应写入器 ResetResponseWriter method of GZipWriter, resets the response writer

func (*GZipWriter) Stop

func (gw *GZipWriter) Stop()

GZipWriter 的 Stop 方法,关闭写入器 Stop method of GZipWriter, close the writer

func (*GZipWriter) Write

func (gw *GZipWriter) Write(msg []byte) (int, error)

GZipWriter 的 Write 方法,删除 "Content-Length" 头部,然后写入消息 Write method of GZipWriter, deletes the "Content-Length" header, then writes the message

func (*GZipWriter) WriteHeader

func (gw *GZipWriter) WriteHeader(code int)

GZipWriter 的 WriteHeader 方法,删除 "Content-Length" 头部,然后写入状态码 WriteHeader method of GZipWriter, deletes the "Content-Length" header, then writes the status code

func (*GZipWriter) WriteString

func (gw *GZipWriter) WriteString(msg string) (int, error)

GZipWriter 的 WriteString 方法,将字符串转换为字节并写入 WriteString method of GZipWriter, converts the string to bytes and writes it

type WriterCreateFunc

type WriterCreateFunc func(config *Config, rw gin.ResponseWriter) any

WriterCreateFunc 是一个创建压缩写入器的函数类型 WriterCreateFunc is a function type to create a compression writer

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL