### Start Download Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/file/download/README.md
Run this command to start the download server for the Hertz examples. Ensure you are in the correct directory.
```bash
go run file/download/main.go
```
--------------------------------
### Run Multiple Service Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/multiple_service/README.md
Execute this command in your terminal to run the multiple service example. Ensure you have Go installed.
```bash
go run multiple_service/main.go
```
--------------------------------
### Start YAML Render Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/render/yaml_customize/README.md
Run this command to start the YAML render server for the Hertz examples. Ensure you are in the correct project directory.
```bash
go run render/yaml_customize/main.go
```
--------------------------------
### Start JSON Render Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/render/json/README.md
Run this command to start the JSON rendering server for the Hertz examples. Access the service via your browser at http://127.0.0.1:8080.
```go
go run render/json/main.go
```
--------------------------------
### Start Registry Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/reverseproxy/discovery/README.md
Execute this command to start the registry server.
```shell
go run registry/main.go
```
--------------------------------
### Start Custom Middleware Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/middleware/custom/README.md
Execute this command to start the custom middleware server for Hertz examples. Ensure you are in the correct directory.
```bash
go run middleware/custom/main.go
```
--------------------------------
### Install Hertz and Kitex Code Generation Tools
Source: https://github.com/cloudwego/hertz-examples/blob/main/hz/struct_reuse/thrift_reuse/README.md
Install the necessary code generation tools for Hertz and Kitex using go install. Ensure these tools are available in your PATH.
```bash
go install github.com/cloudwego/hertz/cmd/hz@latest
```
```bash
go install github.com/cloudwego/kitex/tool/cmd/kitex@latest
```
--------------------------------
### Hertz Getting Query, Form, Cookie Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of retrieving query parameters, form data, and cookies in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
queryName := ctx.Query("name")
formName := ctx.FormValue("name")
cookieValue, _ := ctx.Cookie("mycookie")
ctx.JSON(200, utils.H{
"queryName": queryName,
"formName": formName,
"cookieValue": string(cookieValue),
})
})
h.Spin()
}
```
--------------------------------
### Run Hello World Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/hello/README.md
Execute the main Go file for the hello world example.
```bash
go run hello/main.go
```
--------------------------------
### Hertz GraphQL Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using GraphQL in a Hertz server.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/cloudwego/hertz/contrib/graphql"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Define your GraphQL schema and resolvers
s// schema := `type Query { hello: String }`
// resolvers := map[string]interface{}{
// "hello": func(ctx context.Context) string {
// return "Hello from GraphQL!"
// },
// }
// Register the GraphQL handler
h.GET("/graphql", graphql.GraphqlHandler(schema, resolvers))
h.POST("/graphql", graphql.GraphqlHandler(schema, resolvers))
h.Spin()
}
```
--------------------------------
### Run Hertz Examples
Source: https://github.com/cloudwego/hertz-examples/blob/main/README_CN.md
Instructions on how to run the Hertz examples. All commands should be executed from the hertz-examples directory.
--------------------------------
### Hertz Multiple Services Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating how to run multiple Hertz services concurrently.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h1 := server.Default(server.WithHostPorts("127.0.0.1:8888"))
h1.GET("/hertz1", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"service": "hertz1",
})
})
h2 := server.Default(server.WithHostPorts("127.0.0.1:9999"))
h2.GET("/hertz2", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"service": "hertz2",
})
})
go h1.Spin()
h2.Spin()
}
```
--------------------------------
### Start Upload Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/file/upload/README.md
Run this command to start the Hertz file upload server.
```bash
go run file/upload/main.go
```
--------------------------------
### Start HTML Render Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/render/html/README.md
Run this command to start the HTML rendering server. Ensure you are in the correct directory.
```bash
go run render/html/main.go
```
--------------------------------
### Hertz hlog Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using hlog and its log extension in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
hlog "github.com/hertz-contrib/hlog"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(hlog.New()) // Use hlog middleware
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
hlog.Info("This is an info message")
hlog.Warn("This is a warning message")
hlog.Error("This is an error message")
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Render Protobuf Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of rendering a Protobuf response in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"google.golang.org/protobuf/protojson"
)
type Person struct {
Name string `protobuf:"name,omitempty"`
Age int32 `protobuf:"age,omitempty"`
}
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
person := &Person{Name: "Hertz", Age: 1}
data, _ := protojson.Marshal(person)
ctx.ProtoBuf(200, data)
})
h.Spin()
}
```
--------------------------------
### Hertz Static File Service Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating serving static files in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/fs"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Serve static files from the "./static" directory
h.StaticFS("/static/", &fs.FS{Name: "static", Root: "./static"})
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Run Hertz Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/bizdemo/hertz_swagger_gen/readme_cn.md
Navigate to the project directory and execute the Go program to run the Hertz example.
```bash
cd bizdemo/hertz_swagger_gen
go run .
```
--------------------------------
### Running the Static File Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/file/staticFile/README.md
Instructions on how to build and run the static file server example.
```APIDOC
## How to Run the Static File Server
Follow these steps to run the static file server example:
1. **Navigate to the directory**: Change your current directory to the `file/staticFile` folder within the project.
```bash
cd file/staticFile
```
2. **Start the server**: Run the `main.go` file using the Go runtime.
```bash
go run main.go
```
```
--------------------------------
### Hertz Session Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the session middleware in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/sessions"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(sessions.New(sessions.Config{
CookieName: "mycookie",
// You can customize the session store, e.g., redis, memstore, etc.
// Store: redis.NewStore(redis.Config{
// Addr: "localhost:6379",
// }),
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
session := sessions.Default(ctx)
ctx.JSON(200, utils.H{
"msg": "hello world",
})
session.Set("key", "value")
session.Save()
})
h.Spin()
}
```
--------------------------------
### Start Static File Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/file/html-fs/README.md
Execute this command to start the static file server using Go.
```bash
go run main.go
```
--------------------------------
### Start Protobuf Render Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/render/protobuf/README.md
Run this command to start the protobuf render server. Access the service via your browser at http://127.0.0.1:8080/somePb.
```go
go run render/protobuf/main.go
```
--------------------------------
### Hertz Trailer Read/Write Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of reading and writing trailers for a Hertz server.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.POST("/hertz", func(c context.Context, ctx *app.RequestContext) {
// Read trailers
// trailers := ctx.Trailers()
// Write trailers
ctx.SetTrailer("my-trailer", "trailer-value")
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz File Download Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating file download functionality in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/download", func(c context.Context, ctx *app.RequestContext) {
filePath := "./uploads/example.txt" // Path to the file to download
ctx.File(filePath)
})
h.Spin()
}
```
--------------------------------
### Start Text Render Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/render/text/README.md
Run this command to start the text rendering server. Ensure you are in the correct directory.
```bash
go run render/text/main.go
```
--------------------------------
### Hertz Loadbalance Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Loadbalance middleware in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/loadbalance"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(loadbalance.New())
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Websocket Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating the use of Websocket protocol with Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/websocket"
)
func main() {
h := server.Default()
h.GET("/hertz", websocket.New(func(c context.Context, ctx *app.RequestContext) {
conn, err := websocket.Accept(ctx)
if err != nil {
return
}
for {
messageType, msg, err := conn.ReadMessage()
if err != nil {
return
}
if err := conn.WriteMessage(messageType, msg); err != nil {
return
}
}
}))
h.Spin()
}
```
--------------------------------
### Hertz Reverse Proxy Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the reverseproxy in Hertz server.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/hertz-contrib/reverseproxy"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Create a new reverse proxy instance
// proxy := reverseproxy.New("http://localhost:8081") // Target URL
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Render HTML Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of rendering an HTML response in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.HTML(200, "
Hello World
")
})
h.Spin()
}
```
--------------------------------
### Hertz Graceful Shutdown Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating graceful shutdown for a Hertz server.
```go
package main
import (
"context"
"os"
"os/signal"
"syscall"
"time"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHostPorts("127.0.0.1:8888"))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
time.Sleep(5 * time.Second) // Simulate a long-running request
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
go func() {
h.Spin()
}()
quit := make(chan os.Signal, 1)
ssignal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.Shutdown(ctx); err != nil {
panic("server shutdown failed: " + err.Error())
}
}
```
--------------------------------
### Install CWGO
Source: https://github.com/cloudwego/hertz-examples/blob/main/hex/README.md
Install the CWGO tool. Use the appropriate command based on your Go version.
```bash
# Go 1.15 and earlier version
GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get github.com/cloudwego/cwgo@latest
```
```bash
# Go 1.16 and later version
GOPROXY=https://goproxy.cn/,direct go install github.com/cloudwego/cwgo@latest
```
--------------------------------
### Hertz SSE Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating the use of Server-Sent Events (SSE) with Hertz.
```go
package main
import (
"context"
"time"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/sse"
)
func main() {
h := server.Default()
h.GET("/hertz", sse.New(func(c context.Context, ctx *app.RequestContext) {
go func() {
for {
sse.Publish.Do(ctx, "message", utils.H{
"time": time.Now().String(),
"data": "hello world",
})
time.Sleep(1 * time.Second)
}
}()
}))
h.Spin()
}
```
--------------------------------
### Launch Hertz Hello World Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of launching a basic Hertz 'hello world' application.
```go
package main
import (
"context"
"github.com"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHostPorts("127.0.0.1:8888"))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz File Upload Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating file upload functionality in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.POST("/hertz", func(c context.Context, ctx *app.RequestContext) {
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(400, utils.H{
"error": "failed to get file",
})
return
}
// Save the file to a specific path
// err = ctx.SaveUploadedFile(file, "./uploads/"+file.Filename)
// if err != nil {
// ctx.JSON(500, utils.H{
// "error": "failed to save file",
// })
// return
// }
ctx.JSON(200, utils.H{
"filename": file.Filename,
"size": file.Size,
"message": "file uploaded successfully",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Streaming Write Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating streaming write functionality in Hertz.
```go
package main
import (
"context"
"time"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.Stream(200, "text/plain", func(w io.Writer) {
for i := 0; i < 5; i++ {
w.Write([]byte("stream data " + string(i) + "\n"))
time.Sleep(500 * time.Millisecond)
}
})
})
h.Spin()
}
```
--------------------------------
### Hertz Render JSON Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of rendering a JSON response in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"message": "hello world",
"status": "success",
})
})
h.Spin()
}
```
--------------------------------
### Hertz BasicAuth Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the BasicAuth middleware in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/basicauth"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(basicauth.BasicAuth(basicauth.Config{
Users: map[string]string{
"user": "password",
},
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Start XML Render Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/render/xml/README.md
Run this command to start the XML rendering server. Access the rendered XML via your browser at http://127.0.0.1:8080/someXML.
```bash
go run render/xml/main.go
```
--------------------------------
### Hertz Prometheus Metrics Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of integrating Prometheus for metrics monitoring in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/hertz-contrib/prometheus"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Initialize Prometheus metrics collector
// p := prometheus.NewPrometheus(
// "hertz_example",
// prometheus.WithDefaultMetrics(true),
// )
// p.Use(h.Group("/"))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Streaming Read Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating streaming read functionality in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.POST("/hertz", func(c context.Context, ctx *app.RequestContext) {
body, err := ctx.Body() // Read the entire request body
if err != nil {
ctx.JSON(500, utils.H{
"error": "failed to read body",
})
return
}
ctx.JSON(200, utils.H{
"message": string(body),
})
})
h.Spin()
}
```
--------------------------------
### Configure Hertz Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of configuring a Hertz server with various options.
```go
package main
import (
"context"
"time"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/config"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
// Use server.WithHostPorts to set the listening address and port.
// Use server.WithReadTimeout to set the read timeout.
// Use server.WithMaxRequestBodySize to set the maximum request body size.
// Use server.WithIdleTimeout to set the idle timeout.
// Use server.WithDisablePrintRoute to disable printing routes.
h := server.Default(server.WithHostPorts("127.0.0.1:8888"),
server.WithReadTimeout(10*time.Second),
server.WithMaxRequestBodySize(1<<30), // 1GB
server.WithIdleTimeout(30*time.Second),
server.WithDisablePrintRoute(true),
)
// Use server.WithExitWaitTime to set the exit wait time.
h.Use(func(ctx context.Context, c *app.RequestContext) {
c.Next(ctx)
})
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin(server.WithExitWaitTime(5 * time.Second))
}
```
--------------------------------
### Start Redirect Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/redirect/README.md
Run this command to start the redirect server for testing internal and external redirects.
```bash
go run redirect/main.go
```
--------------------------------
### Hertz Sentinel Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of integrating sentinel-golang for rate limiting and flow control in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/hertz-contrib/sentinel"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Initialize Sentinel with default configuration
// sentinel.New() // Use default config
// sentinel.New(sentinel.WithFlowRules(...))
h.Use(sentinel.SentinelMiddleware())
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz HTTP3 Protocol Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating the use of the HTTP3 protocol with Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/http3"
)
func main() {
h := server.Default(server.WithHTTP3(http3.New)) // Use server.WithHTTP3 to enable HTTP3.
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Run Hertz Examples Project
Source: https://github.com/cloudwego/hertz-examples/blob/main/hz/template/readme.md
Execute these shell commands to build and run the Hertz examples project. Ensure you have the necessary build scripts.
```shell
sh build.sh
```
```shell
sh output/bootstrap.sh
```
--------------------------------
### Hertz Jaeger Tracing Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of integrating Jaeger for distributed tracing in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/hertz-contrib/tracer/jaeger"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Initialize Jaeger tracer
// tracer, closer, err := jaeger.NewTracer("hertz-service", "", "", 1)
// if err != nil {
// panic(err)
// }
// defer closer.Close()
// h.Use(jaeger.New(jaeger.WithTracer(tracer)))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Start CWGO Hex Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/hex/README.md
Run the generated Go server to start the Hertz and Kitex application.
```bash
go run .
```
--------------------------------
### Hertz Custom Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of creating and using custom middleware in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Define a custom middleware function
customMiddleware := func(ctx context.Context, c *app.RequestContext) {
// Do something before the request handler
c.Next(ctx)
// Do something after the request handler
}
h.Use(customMiddleware)
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz TLS Protocol Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating the use of TLS protocol with Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
)
func main() {
h := server.Default(server.WithTLS( // Use server.WithTLS to enable TLS.
"./cert.pem", // Path to the certificate file.
"./key.pem", // Path to the key file.
))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz HTTP2 Protocol Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating the use of the HTTP2 protocol with Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/http2"
)
func main() {
h := server.Default(server.WithHTTP2(http2.New)) // Use server.WithHTTP2 to enable HTTP2.
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Run Streaming Write Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/streaming/README.md
Starts the streaming write server. This is a command-line instruction.
```bash
go run streaming/streaming_write/main.go
```
--------------------------------
### Run TLS Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/reverseproxy/tls/README.md
Execute the Go program to start the TLS server. Ensure you have the necessary Go environment set up.
```bash
go run tls/main.go
```
--------------------------------
### Hertz HTTP1 Protocol Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example demonstrating the use of the HTTP1 protocol with Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
)
func main() {
h := server.Default()
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Paseto Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Paseto middleware in Hertz for token-based authentication.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/paseto"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(paseto.New(paseto.Config{
// You can configure the key, expiration time, etc.
// Example: Key: []byte("your-secret-key"),
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Run Hertz JWT Demo
Source: https://github.com/cloudwego/hertz-examples/blob/main/bizdemo/hertz_jwt/readme.md
Execute this command to run the Hertz JWT example application after setting up the database.
```go
cd bizdemo/hertz_jwt && go run main.go
```
--------------------------------
### Hertz pprof Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the pprof middleware in Hertz for performance profiling.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/pprof"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(pprof.New())
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Casbin Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Casbin middleware in Hertz for access control.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/casbin"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Initialize Casbin enforcer with a model and policy file.
// Example: casbin.New("path/to/model.conf", "path/to/policy.csv")
h.Use(casbin.New())
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Gzip Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Gzip middleware in Hertz for response compression.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/gzip"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(gzip.Gzip(gzip.Config{
Level: 5, // Set the compression level (1-9).
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Cache Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Cache middleware in Hertz for response caching.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/cache"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(cache.New())
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Secure Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Secure middleware in Hertz for security enhancements.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/secure"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(secure.New(secure.Config{
// Example configuration options:
// SSLRedirect: true,
// STSSeconds: 31536000,
// BrowserXssFilter: true,
// ContentSecurityPolicy: "default-src 'self'",
// FrameDeny: true,
// HostsProxyHeaders: []string{"X-Forwarded-Host"},
// EnableReferrerPolicy: true,
// ReferrerPolicy: "origin",
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Recovery Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the Recovery middleware in Hertz to recover from panics.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/recovery"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(recovery.Recovery(recovery.WithLog(nil)))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Adaptor with Jade Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using Hertz adaptor to integrate with packages built for `http.Handler`, including Jade as a template engine.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/hertz-contrib/adaptor"
"github.com/Joker/jade"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
// Initialize Jade template engine
jade.Use(jade.New(jade.WithTemplateDir("./templates")))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.HTML(200, "index.jade", utils.H{
"title": "Hertz Jade Example",
})
})
h.Spin()
}
```
--------------------------------
### Hertz KeyAuth Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the KeyAuth middleware in Hertz for API key authentication.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/keyauth"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(keyauth.New(keyauth.Config{
KeyLookup: "query:key", // Look for the API key in the query parameter named 'key'.
KeyName: "key",
// You can also specify other lookup methods like "header:key", "cookie:key", etc.
Verify: func(ctx context.Context, req *app.Request, key string) bool {
// Implement your API key verification logic here.
return key == "secret-key"
},
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz Access Log Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the access log middleware in Hertz for logging requests.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/logger/accesslog"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(accesslog.New())
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Run MySQL Docker Container
Source: https://github.com/cloudwego/hertz-examples/blob/main/bizdemo/hertz_jwt/readme.md
Use this command to start the MySQL database in a Docker container for the demo.
```bash
cd bizdemo/hertz_jwt && docker-compose up
```
--------------------------------
### Test Hello World Endpoint
Source: https://github.com/cloudwego/hertz-examples/blob/main/hello/README.md
Send a GET request to the hello world endpoint using curl.
```bash
curl --location --request GET '127.0.0.1:8888/hello'
```
--------------------------------
### Hertz CSRF Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the CSRF middleware in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/hertz-contrib/csrf"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(csrf.New(csrf.Config{
// You can customize the cookie name, expiration time, etc.
// Example: CookieMaxAge: time.Hour * 1,
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Hertz CORS Middleware Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of using the CORS middleware in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
"github.com/hertz-contrib/cors"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
ExposeHeaders: []string{"*"},
AllowCredentials: true,
MaxAge: 3600 * 24 * 7,
// AllowOriginFunc: func(origin string) bool { return true },
// AllowWebP: true,
}))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"msg": "hello world",
})
})
h.Spin()
}
```
--------------------------------
### Run Hertz Session Demo
Source: https://github.com/cloudwego/hertz-examples/blob/main/bizdemo/hertz_session/README.md
Navigate to the demo directory and run the main application file to start the Hertz session server.
```bash
cd bizdemo/hertz_session
go run .
```
--------------------------------
### Run Hertz SSE Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/sse/README.md
Execute the Hertz SSE server example by navigating to the server directory and running the main Go file.
```bash
cd server
go run main.go
```
--------------------------------
### Implement Handler Logic for Method1
Source: https://github.com/cloudwego/hertz-examples/blob/main/hz/protobuf/README.MD
Modify the generated handler file (`biz/handler/hello/hello_service.go`) to implement the business logic for the `Method1` RPC. This example shows how to bind and validate the request, process it, and return a JSON response.
```go
// handler path: biz/handler/hello/hello_service.go
// 其中 "/hello" 是 protobuf idl 中 go_package 的最后一级
// "hello_service.go" 是 protobuf idl 中 service 的名字,所有 service 定义的方法都会生成在这个文件中
// Method1 .
// @router /hello [GET]
func Method1(ctx context.Context, c *app.RequestContext) {
var err error
var req hello.HelloReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(400, err.Error())
return
}
resp := new(hello.HelloResp)
// 你可以修改整个函数的逻辑,而不仅仅局限于当前模板
resp.RespBody = "hello," + req.Name // 添加的逻辑
c.JSON(200, resp)
}
```
--------------------------------
### Build and Run TikTok Demo Locally
Source: https://github.com/cloudwego/hertz-examples/blob/main/bizdemo/tiktok_demo/README.md
Instructions for compiling and running the TikTok demo application in a local environment. Requires FFmpeg to be installed and added to the system path.
```shell
# Install other services
docker compose --profile dev up -d
go build -o tiktok_demo && ./tiktok_demo
```
--------------------------------
### Run BasicAuth Middleware Server
Source: https://github.com/cloudwego/hertz-examples/blob/main/middleware/basicauth/README.md
Execute this command to start the basic authentication middleware server. Ensure you are in the correct directory.
```bash
go run middleware/basicauth/main.go
```
--------------------------------
### Hertz Redirect External URI Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of performing an external redirect in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.Redirect(302, "https://www.google.com")
})
h.Spin()
}
```
--------------------------------
### Hertz Redirect Internal URI Example
Source: https://github.com/cloudwego/hertz-examples/blob/main/README.md
Example of performing an internal redirect in Hertz.
```go
package main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/route"
)
func main() {
h := server.Default(server.WithHandleMethodNotAllowed(true))
h.GET("/hertz", func(c context.Context, ctx *app.RequestContext) {
ctx.Redirect(302, "/target")
})
h.GET("/target", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, utils.H{
"message": "redirected successfully",
})
})
h.Spin()
}
```