diff --git a/content/en/docs/hertz/tutorials/third-party/middleware/swagger.md b/content/en/docs/hertz/tutorials/third-party/middleware/swagger.md index 749fdd83e6d..0a7b5130f86 100644 --- a/content/en/docs/hertz/tutorials/third-party/middleware/swagger.md +++ b/content/en/docs/hertz/tutorials/third-party/middleware/swagger.md @@ -3,7 +3,7 @@ title: "Swagger" date: 2025-12-04 weight: 8 keywords: ["Swagger", "RESTful API"] -description: "Hertz middleware to automatically generate RESTful API documentation with Swagger 2.0." +description: "Generate RESTful API documentation with the official Swagger toolchain and HTTP adaptor." --- > **⚠️ Deprecated** @@ -28,26 +28,29 @@ github.com/swaggo/files go install github.com/swaggo/swag/cmd/swag@latest ``` -3. Replace swagger handler - -If the project has already been set up, replace the code below. +3. Use hertz adaptor ```go -// Before (using hertz-contrib/swagger) +// Before (deprecated: hertz-contrib/swagger) import "github.com/hertz-contrib/swagger" import swaggerFiles "github.com/swaggo/files" url := swagger.URL("http://localhost:8888/swagger/doc.json") h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, url)) +``` -// After (using http adaptor) +```go +// After (recommended: adaptor) import "github.com/cloudwego/hertz/pkg/common/adaptor" import httpSwagger "github.com/swaggo/http-swagger" h.GET("/swagger/*any", adaptor.HertzHandler(httpSwagger.WrapHandler)) ``` -If starting a new project, follow the sample code below as an example. +## Example Usage + +The following example demonstrates how to integrate Swagger documentation and Swagger UI +into a Hertz application using the Hertz HTTP adaptor. ```go package main @@ -105,13 +108,13 @@ func main() { } ``` -4. Generate Swagger docs +1. Generate Swagger docs ```sh swag init ``` -5. Run program +2. Run program Start the Hertz server. @@ -121,10 +124,11 @@ go run main.go On a web browser, go to http://localhost:8888/swagger/index.html or whichever address that is configured to see the Swagger UI. -6. Provide custom Swagger UI +### Custom Swagger UI For users who want to create their own custom UI, they will need to download the Swagger UI dist files, and serve the UI files as static assets. -Copy the following files from [swagger-ui/dist](https://github.com/swagger-api/swagger-ui/tree/master/dist) and place them in `swagger-ui/`. + +1. Copy the following files from [swagger-ui/dist](https://github.com/swagger-api/swagger-ui/tree/master/dist) and place them in `swagger-ui/`. - https://github.com/swagger-api/swagger-ui/blob/master/dist/favicon-16x16.png - https://github.com/swagger-api/swagger-ui/blob/master/dist/favicon-32x32.png @@ -132,7 +136,7 @@ Copy the following files from [swagger-ui/dist](https://github.com/swagger-api/s - https://github.com/swagger-api/swagger-ui/blob/master/dist/swagger-ui-bundle.js - https://github.com/swagger-api/swagger-ui/blob/master/dist/swagger-ui-standalone-preset.js -Create an `index.html` file in the same directory with the following template. The original configuration options present in the old `hertz-contrib/swagger` middleware can be directly configured in the HTML file. +2. Create an `index.html` file in the same directory with the following template. The original configuration options present in the old `hertz-contrib/swagger` middleware can be directly configured in the HTML file. **Note: The HTML file below is just a sample and should be modified accordingly to the user's needs.** @@ -259,7 +263,7 @@ project/ └── go.sum ``` -7. Serve static files +3. Serve static files Add this line into `main.go` @@ -274,7 +278,7 @@ h.Spin() // Rest of code ``` -8. Run program +4. Run program ```sh go run main.go @@ -288,7 +292,7 @@ Hertz middleware to automatically generate RESTful API documentation with Swagge The implementation of the [swagger](https://github.com/hertz-contrib/swagger) extension refers to the implementation of [Gin](https://github.com/swaggo/gin-swagger). -## Usage +### Usage 1. Add comments to your API source code, See [Declarative Comments Format](https://github.com/swaggo/swag/blob/master/README.md#declarative-comments-format). @@ -341,7 +345,7 @@ import "github.com/hertz-contrib/swagger" // hertz-swagger middleware import "github.com/swaggo/files" // swagger embed files ``` -## Example +### Example Now assume you have implemented a simple api as following: @@ -450,11 +454,11 @@ Demo project tree, `swag init` is run at relative `.`. └── main.go ``` -## Multiple APIs +### Multiple APIs This feature was introduced in swag v1.7.9. -## Configuration +### Configuration You can configure Swagger using different configuration options. diff --git a/content/en/docs/hertz/tutorials/third-party/protocol/websocket.md b/content/en/docs/hertz/tutorials/third-party/protocol/websocket.md index a2e48680439..51c0b871d03 100644 --- a/content/en/docs/hertz/tutorials/third-party/protocol/websocket.md +++ b/content/en/docs/hertz/tutorials/third-party/protocol/websocket.md @@ -6,13 +6,6 @@ keywords: ["WebSocket", "HTTP", "hijack", "TCP"] description: "Hertz implements support for Gorilla WebSocket based on hijack." --- -WebSocket is a type of full-duplex communication that can be performed on a single TCP connection and is located at the application layer of the OSI model. -WebSocket makes data exchange between client and server easier, allowing the server to actively push data to the client. -In the WebSocket API, the browser and the server only need to complete a handshake that a persistent connection can be created between the two, and two-way data transmission can be performed. - -Hertz provides support for WebSocket and adapts it in Hertz by referring to [gorilla/websocket](https://github.com/gorilla/websocket) using `hijack`. -The usage and parameters are basically the same. - > **⚠️ Deprecated** > > The `hertz-contrib/websocket` middleware is now deprecated. @@ -20,6 +13,16 @@ The usage and parameters are basically the same. > > See the migration guide below. +## Overview + +WebSocket is a type of full-duplex communication that can be performed on a single TCP connection and is located at the application layer of the OSI model. +WebSocket makes data exchange between client and server easier, allowing the server to actively push data to the client. +In the WebSocket API, the browser and the server only need to complete a handshake that a persistent connection can be created between the two, and two-way data transmission can be performed. + +Historically, Hertz provided WebSocket support via [`hertz-contrib/websocket`](https://github.com/hertz-contrib/websocket), which adapts +[`gorilla/websocket`](https://github.com/gorilla/websocket) using HTTP connection hijacking. +This approach is now deprecated in favor of using the official Gorilla WebSocket implementation directly via the Hertz HTTP Adaptor. + ## Migration Guide 1. Remove deprecated dependencies @@ -31,7 +34,7 @@ github.com/hertz-contrib/websocket 2. Use hertz adaptor ```go -// Before (using hertz-contrib/websocket) +// Before (deprecated: hertz-contrib/websocket) import "github.com/hertz-contrib/websocket" var upgrader = websocket.HertzUpgrader{} func echo(_ context.Context, c *app.RequestContext) { @@ -40,9 +43,12 @@ func echo(_ context.Context, c *app.RequestContext) { }) } h.GET("/echo", echo) +``` -// After (using hertz adaptor) +```go +// After (recommended: gorilla/websocket + adaptor) import "github.com/gorilla/websocket" +import "github.com/cloudwego/hertz/pkg/common/adaptor" var upgrader = websocket.Upgrader{} func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) @@ -114,13 +120,15 @@ func main() { var homeTemplate = "" ``` -## Install (Deprecated) +## Legacy Documentation (Deprecated) + +### Install ```shell go get github.com/hertz-contrib/websocket ``` -## Example +### Example ```go package main @@ -189,7 +197,7 @@ go run server.go In the example code above, the server includes a simple web client. To use this client, open [http://127.0.0.1:8080]() in your browser and follow the instructions on the page. -## Config +### Config The following is the optional configuration parameters for using Hertz WebSocket. @@ -205,7 +213,7 @@ This section is organized around the `websocket.HertzUpgrader` structure. | `CheckOrigin` | Used to set a check function for Origin header for the request. If the Origin header of the request is acceptable, CheckOrigin returns true. | | `EnableCompression` | Used to set whether the server should attempt to negotiate compression for each message (RFC 7692). Setting this value to true does not guarantee that compression will be supported. | -### WriteBufferPool +#### WriteBufferPool If this value is not set, an additional write buffer is initialized and allocated to the connection for the current lifetime. The buffer pool is most useful when the application has a moderate amount of writes on a large number of connections. @@ -246,13 +254,13 @@ var upgrader = websocket.HertzUpgrader{ } ``` -### Subprotocols +#### Subprotocols WebSocket simply defines a mechanism for exchanging arbitrary messages. What those messages mean, what kind of messages the client can expect at any given point in time, or what kind of messages they are allowed to send, depends entirely on the implementing application. So you need an agreement between the server and the client about these things. The subprotocol parameters simply allow the client and server to formally exchange this information. You can make up any name for any protocol you want. The server can simply check that the client has followed that protocol during the handshake. -### Error +#### Error If Error is nil, then use the API provided by Hertz to generate the HTTP error response. @@ -273,7 +281,7 @@ var upgrader = websocket.HertzUpgrader{ } ``` -### CheckOrigin +#### CheckOrigin CheckOrigin returns true if the request Origin header is acceptable. If CheckOrigin is nil, then a safe default is used: return false if the Origin request header is present and the origin host is not equal to request Host header. @@ -302,13 +310,13 @@ func fastHTTPCheckSameOrigin(c *app.RequestContext) bool { } ``` -### EnableCompression +#### EnableCompression The server accepts one or more extension fields that are included in the `Sec-WebSocket-Extensions` header field extensions requested by the client. When EnableCompression is true, the server matches the extensions it currently supports with its extensions, and supports compression if the match is successful. Currently only the "no context takeover" mode is supported, as described in the `HertzUpgrader.Upgrade`. -### SetReadTimeout/SetWriteTimeout +#### SetReadTimeout/SetWriteTimeout When using websockets for reading and writing, the read timeout or write timeout can be set similarly as follows. @@ -330,7 +338,7 @@ func echo(_ context.Context, c *app.RequestContext) { } ``` -## NoHijackConnPool +### NoHijackConnPool > The hijack conn used for Hertz connection hijacking is pooled and therefore does not support asynchronous operations when the hijacked connection is used in a websocket. diff --git a/content/zh/docs/hertz/tutorials/third-party/middleware/swagger.md b/content/zh/docs/hertz/tutorials/third-party/middleware/swagger.md index a3d1643dec1..3bf19fb6ffc 100644 --- a/content/zh/docs/hertz/tutorials/third-party/middleware/swagger.md +++ b/content/zh/docs/hertz/tutorials/third-party/middleware/swagger.md @@ -3,7 +3,7 @@ title: "Swagger" date: 2025-12-04 weight: 8 keywords: ["Swagger", "RESTful API"] -description: "用 Swagger 2.0 来自动生成 RESTful API 文档的 Hertz 中间件。" +description: "使用官方 Swagger 工具链和 HTTP Adaptor 生成 RESTful API 文档" --- > **⚠️ 已废弃** @@ -28,26 +28,28 @@ github.com/swaggo/files go install github.com/swaggo/swag/cmd/swag@latest ``` -3. 替换 Swagger handler - -如果项目已经设置好,替换下面的代码。 +3. 利用 hertz adaptor ```go -// 旧版本(使用 hertz-contrib/swagger) +// 旧版本(已废弃:hertz-contrib/swagger) import "github.com/hertz-contrib/swagger" import swaggerFiles "github.com/swaggo/files" url := swagger.URL("http://localhost:8888/swagger/doc.json") h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, url)) +``` -// 新版本(使用 http adaptor) +```go +// 新版本(推荐:adaptor) import "github.com/cloudwego/hertz/pkg/common/adaptor" import httpSwagger "github.com/swaggo/http-swagger" h.GET("/swagger/*any", adaptor.HertzHandler(httpSwagger.WrapHandler)) ``` -如果是新项目,请参考以下示例代码: +## 示例用法 + +本示例演示了如何使用 HTTP Adaptor 在 Hertz 应用中集成 Swagger UI。 ```go package main @@ -105,13 +107,13 @@ func main() { } ``` -4. 更新 Swagger 注释 +1. 更新 Swagger 注释 ```sh swag init ``` -5. 运行程序 +2. 运行程序 启动 Hertz 服务器。 @@ -121,10 +123,11 @@ go run main.go 在浏览器中访问 http://localhost:8888/swagger/index.html 或配置的地址,即可查看 Swagger UI。 -6. 使用自定义 Swagger UI +### 自定义 Swagger UI 对于想要创建自己的自定义 UI 的用户,他们需要下载 Swagger UI 分发文件,并将 UI 文件作为静态资源提供。 -从 [swagger-ui/dist](https://github.com/swagger-api/swagger-ui/tree/master/dist) 中复制以下文件到 `swagger-ui/` + +1. 从 [swagger-ui/dist](https://github.com/swagger-api/swagger-ui/tree/master/dist) 中复制以下文件到 `swagger-ui/` - https://github.com/swagger-api/swagger-ui/blob/master/dist/favicon-16x16.png - https://github.com/swagger-api/swagger-ui/blob/master/dist/favicon-32x32.png @@ -132,7 +135,7 @@ go run main.go - https://github.com/swagger-api/swagger-ui/blob/master/dist/swagger-ui-bundle.js - https://github.com/swagger-api/swagger-ui/blob/master/dist/swagger-ui-standalone-preset.js -在同一目录下创建一个 `index.html` 文件,示例模板如下。旧版 hertz-contrib/swagger 中的配置项都可以直接在 HTML 文件里设置。 +2. 在同一目录下创建一个 `index.html` 文件,示例模板如下。旧版 hertz-contrib/swagger 中的配置项都可以直接在 HTML 文件里设置。 **注意:以下 HTML 文件仅为示例,应根据用户需求进行修改。** @@ -259,7 +262,7 @@ project/ └── go.sum ``` -7. 提供静态资源服务 +3. 提供静态资源服务 在 `main.go` 中加入 @@ -274,7 +277,7 @@ h.Spin() // 其他代码 ``` -8. 运行程序 +4. 运行程序 ```sh go run main.go @@ -288,7 +291,7 @@ go run main.go 参考了 gin 的 [实现](https://github.com/swaggo/gin-swagger),对 Hertz 进行了适配。 -## 使用用法 +### 使用用法 1. 在你的 API 源代码中添加注释,参考 [Declarative Comments Format](https://github.com/swaggo/swag/blob/master/README.md#declarative-comments-format)。 @@ -340,7 +343,7 @@ import "github.com/hertz-contrib/swagger" // hertz-swagger middleware import "github.com/swaggo/files" // swagger embed files ``` -## 示例代码 +### 示例代码 现在假设你已经实现了一个简单的 api,如下所示: @@ -451,11 +454,11 @@ func main() { └── main.go ``` -## 支持多个 API +### 支持多个 API 这个功能是在 swag v1.7.9 中引入的。 -## 配置 +### 配置 你可以使用不同的配置选项来配置 Swagger。 diff --git a/content/zh/docs/hertz/tutorials/third-party/protocol/websocket.md b/content/zh/docs/hertz/tutorials/third-party/protocol/websocket.md index 16cab987e29..1feb6d11ed2 100644 --- a/content/zh/docs/hertz/tutorials/third-party/protocol/websocket.md +++ b/content/zh/docs/hertz/tutorials/third-party/protocol/websocket.md @@ -6,10 +6,6 @@ keywords: ["WebSocket", "HTTP", "hijack", "TCP"] description: "Hertz 基于 hijack 的方式实现了对 WebSocket 的支持。" --- -WebSocket 是一种可以在单个 TCP 连接上进行全双工通信,位于 OSI 模型的应用层。WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就可以创建持久性的连接,并进行双向数据传输。 - -Hertz 提供了 WebSocket 的支持,参考 [gorilla/websocket](http://github.com/gorilla/websocket) 库使用 `hijack` 的方式在 Hertz 进行了适配,用法和参数基本保持一致 - > **⚠️ 已废弃** > > `hertz-contrib/websocket` 中间件已被废弃。 @@ -17,6 +13,13 @@ Hertz 提供了 WebSocket 的支持,参考 [gorilla/websocket](http://github.c > > 迁移指南如下。 +## 概览 + +WebSocket 是一种可以在单个 TCP 连接上进行全双工通信,位于 OSI 模型的应用层。WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就可以创建持久性的连接,并进行双向数据传输。 + +早期,Hertz 通过 [`hertz-contrib/websocket`](https://github.com/hertz-contrib/websocket) 提供 WebSocket 支持,该实现基于 HTTP 连接劫持(hijack)对 [`gorilla/websocket`](https://github.com/gorilla/websocket) 进行了适配。 +目前该方案已被弃用,推荐直接通过 Hertz HTTP Adaptor 使用官方的 Gorilla WebSocket 实现。 + ## 迁移指南 1. 移除已废弃的依赖项 @@ -28,7 +31,7 @@ github.com/hertz-contrib/websocket 2. 利用 hertz adaptor ```go -// 旧版本(使用 hertz-contrib/websocket) +// 旧版本(已废弃:hertz-contrib/websocket) import "github.com/hertz-contrib/websocket" var upgrader = websocket.HertzUpgrader{} func echo(_ context.Context, c *app.RequestContext) { @@ -37,9 +40,12 @@ func echo(_ context.Context, c *app.RequestContext) { }) } h.GET("/echo", echo) +``` -// 新版本(使用 hertz adaptor) +```go +// 新版本(推荐:gorilla/websocket + adaptor) import "github.com/gorilla/websocket" +import "github.com/cloudwego/hertz/pkg/common/adaptor" var upgrader = websocket.Upgrader{} func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) @@ -111,13 +117,15 @@ func main() { var homeTemplate = "" ``` -## 安装(已废弃) +## 旧版文档(已废弃) + +### 安装 ```shell go get github.com/hertz-contrib/websocket ``` -## 示例代码 +### 示例代码 ```go package main @@ -186,7 +194,7 @@ go run server.go 上述示例代码中,服务器包括一个简单的网络客户端。要使用该客户端,在浏览器中打开 [http://127.0.0.1:8080](),并按照页面上的指示操作。 -## 配置 +### 配置 以下是 Hertz WebSocket 使用过程中可选的配置参数。 @@ -202,7 +210,7 @@ go run server.go | `CheckOrigin` | 用于设置针对请求的 Origin 头的校验函数,如果请求的 Origin 头是可接受的,CheckOrigin 返回 true。 | | `EnableCompression` | 用于设置服务器是否应该尝试协商每个消息的压缩(RFC 7692)。将此值设置为 true 并不能保证压缩会被支持。 | -### WriteBufferPool +#### WriteBufferPool 如果该值没有被设置,则额外初始化写缓冲区,并在当前生命周期内分配给该连接。当应用程序在大量的连接上有适度的写入量时,缓冲池是最有用的。 @@ -243,13 +251,13 @@ var upgrader = websocket.HertzUpgrader{ } ``` -### Subprotocols +#### Subprotocols WebSocket 只是定义了一种交换任意消息的机制。这些消息是什么意思,客户端在任何特定的时间点可以期待什么样的消息,或者他们被允许发送什么样的消息,完全取决于实现应用程序。 所以你需要在服务器和客户端之间就这些事情达成协议。子协议参数只是让客户端和服务端正式地交换这些信息。你可以为你想要的任何协议编造任何名字。服务器可以简单地检查客户在握手过程中是否遵守了该协议。 -### Error +#### Error 如果 Error 为 nil,则使用 Hertz 提供的 API 来生成 HTTP 错误响应。 @@ -270,7 +278,7 @@ var upgrader = websocket.HertzUpgrader{ } ``` -### CheckOrigin +#### CheckOrigin 如果 CheckOrigin 为 nil,则使用一个安全的默认值:如果 Origin 请求头存在,并且源主机不等于请求主机头,则返回 false。CheckOrigin 函数应该仔细验证请求的来源,以防止跨站请求伪造。 @@ -296,13 +304,13 @@ func fastHTTPCheckSameOrigin(c *app.RequestContext) bool { } ``` -### EnableCompression +#### EnableCompression 服务端接受一个或者多个扩展字段,这些扩展字段是包含客户端请求的 `Sec-WebSocket-Extensions` 头字段扩展中的。当 EnableCompression 为 true 时,服务端根据当前自身支持的扩展与其进行匹配,如果匹配成功则支持压缩。 目前仅支持“无上下文接管”模式,详见 `HertzUpgrader.Upgrade` 的实现。 -### SetReadTimeout/SetWriteTimeout +#### SetReadTimeout/SetWriteTimeout 当使用 websocket 进行读写的时候,可以通过类似如下方式设置读超时或写超时的时间。 @@ -324,7 +332,7 @@ func echo(_ context.Context, c *app.RequestContext) { } ``` -## NoHijackConnPool +### NoHijackConnPool > Hertz 连接劫持时所使用的 hijack conn 是池化管理的,因此被劫持的连接在 websocket 中使用的时候,不支持异步操作。