You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/en/docs/hertz/tutorials/basic-feature/middleware/gzip.md
+89-2Lines changed: 89 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
---
2
2
title: "Gzip Compress"
3
-
date: 2022-09-25
3
+
date: 2022-10-19
4
4
weight: 4
5
5
keywords: ["Gzip", "Compress"]
6
6
description: "Hertz provides an implementation of Gzip."
@@ -17,6 +17,8 @@ go get github.com/hertz-contrib/gzip
17
17
18
18
## Example
19
19
20
+
### Gzip
21
+
20
22
```go
21
23
package main
22
24
@@ -41,9 +43,94 @@ func main() {
41
43
}
42
44
```
43
45
46
+
### Gzip Stream
47
+
48
+
If the user has a need for gzip compression combined with chunked streaming writing, they can use this middleware. The behavior of this middleware is to chunk each chunk, compress it with gzip, and then send it to the client. Each chunk is a separate compressed data, so each chunk received by the client can be independently decompressed and used.
49
+
50
+
> Note: Using this middleware will hijack the response writer and may have an impact on other interfaces. Therefore, it is only necessary to use this middleware on interfaces with streaming gzip requirements.
51
+
52
+
```go
53
+
package main
54
+
55
+
import (
56
+
"context"
57
+
"fmt"
58
+
"io/ioutil"
59
+
"strings"
60
+
"time"
61
+
62
+
"github.com/cloudwego/hertz/pkg/app"
63
+
"github.com/cloudwego/hertz/pkg/app/client"
64
+
"github.com/cloudwego/hertz/pkg/app/server"
65
+
"github.com/cloudwego/hertz/pkg/common/compress"
66
+
"github.com/cloudwego/hertz/pkg/protocol"
67
+
"github.com/cloudwego/hertz/pkg/protocol/consts"
68
+
"github.com/hertz-contrib/gzip"
69
+
)
70
+
71
+
funcmain() {
72
+
h:= server.Default(server.WithHostPorts(":8081"))
73
+
74
+
// Note: Using this middleware will hijack the response writer and may have an impact on other interfaces.
75
+
// Therefore, it is only necessary to use this middleware on interfaces with streaming gzip requirements.
76
+
h.GET("/ping", gzip.GzipStream(gzip.DefaultCompression), func(ctx context.Context, c *app.RequestContext) {
77
+
fori:=0; i < 10; i++ {
78
+
c.Write([]byte(fmt.Sprintf("chunk %d: %s\n", i, strings.Repeat("hi~", i)))) // nolint: errcheck
0 commit comments