Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 22 additions & 18 deletions content/en/docs/hertz/tutorials/third-party/middleware/swagger.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand All @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -121,18 +124,19 @@ 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
- https://github.com/swagger-api/swagger-ui/blob/master/dist/swagger-ui.css
- 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.**

Expand Down Expand Up @@ -259,7 +263,7 @@ project/
└── go.sum
```

7. Serve static files
3. Serve static files

Add this line into `main.go`

Expand All @@ -274,7 +278,7 @@ h.Spin()
// Rest of code
```

8. Run program
4. Run program

```sh
go run main.go
Expand All @@ -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).

Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -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.

Expand Down
46 changes: 27 additions & 19 deletions content/en/docs/hertz/tutorials/third-party/protocol/websocket.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,23 @@ 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.
> Hertz recommends all users to migrate to the official `gorilla/websocket` toolchain using the [Hertz HTTP Adaptor](../../basic-feature/http-adaptor/).
>
> 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
Expand All @@ -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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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.

Expand Down Expand Up @@ -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.

Expand All @@ -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.

Expand Down Expand Up @@ -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.

Expand All @@ -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.

Expand Down
Loading