Skip to content
鼓励作者:欢迎打赏犒劳

hertz初体验

一个简单的web项目

go
package main

import (
	"context"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
	// 创建一个默认的 Hertz 服务器实例(默认使用 8888 端口)
	// 使用 server.Default() 会默认添加一些中间件,例如恢复中间件
	// 使用 server.New() 则可以创建一个没有任何默认中间件的纯净实例
	h := server.Default()

	// 注册一个 GET 路由处理函数
	// 第一个参数是路由路径,第二个参数是处理函数
	h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
		// 返回 JSON 响应
		ctx.JSON(consts.StatusOK, map[string]interface{}{
			"message": "pong",
			"status":  "success",
		})
	})

	// 启动服务器
	// Spin 方法会阻塞当前 goroutine,直到服务器被关闭
	h.Spin()
}

获取参数

get查询参数

go
package main

import (
    "context"
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    "github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
    h := server.Default()

    // 获取查询参数
    // 示例URL: /welcome?name=Alice&age=25
    h.GET("/welcome", func(c context.Context, ctx *app.RequestContext) {
        // 获取必需的查询参数,如果不存在则为空字符串
        name := ctx.Query("name")
        
        // 获取带有默认值的查询参数
        // 第二个参数是默认值,当参数不存在时使用
        age := ctx.DefaultQuery("age", "18")
        
        ctx.JSON(consts.StatusOK, map[string]interface{}{
            "name": name,
            "age":  age,
        })
    })

    h.Spin()
}

路径查询参数

go
package main

import (
    "context"
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    "github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
    h := server.Default()

    // 路径参数
    // 示例URL: /user/123/profile
    h.GET("/user/:id/profile", func(c context.Context, ctx *app.RequestContext) {
        // 使用 Param 方法获取路径参数
        userID := ctx.Param("id")
        
        ctx.JSON(consts.StatusOK, map[string]interface{}{
            "user_id": userID,
        })
    })

    h.Spin()
}

json请求参数

go
package main

import (
	"context"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

// 定义结构体来表示 JSON 请求体
// 使用 json tag 映射 JSON 字段
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func main() {
	h := server.Default()

	// 处理 JSON 请求体
	// 示例请求: POST /login with JSON body
	h.POST("/login", func(c context.Context, ctx *app.RequestContext) {
		var req LoginRequest

		// 绑定并验证 JSON 请求体
		// BindAndValidate 会自动将 JSON 体解析到结构体中
		if err := ctx.BindAndValidate(&req); err != nil {
			ctx.JSON(consts.StatusBadRequest, map[string]interface{}{
				"error": "Invalid request body",
			})
			return
		}

		// 简单的验证逻辑
		if req.Username == "" || req.Password == "" {
			ctx.JSON(consts.StatusBadRequest, map[string]interface{}{
				"error": "Username and password are required",
			})
			return
		}

		// 模拟用户验证
		if req.Username == "admin" && req.Password == "password" {
			ctx.JSON(consts.StatusOK, map[string]interface{}{
				"message": "Login successful",
				"user":    req.Username,
			})
		} else {
			ctx.JSON(consts.StatusUnauthorized, map[string]interface{}{
				"error": "Invalid credentials",
			})
		}
	})

	h.Spin()
}

post表单提交

go
package main

import (
	"context"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
	h := server.Default()

	// 处理表单提交
	// 示例请求: POST /submit-form with form data
	h.POST("/submit-form", func(c context.Context, ctx *app.RequestContext) {
		// 获取单个表单字段
		name, exists := ctx.GetPostForm("name")
		if !exists {
			name = "Unknown"
		}

		// 获取带有默认值的表单字段
		email := ctx.DefaultPostForm("email", "default@example.com")

		ctx.JSON(consts.StatusOK, map[string]interface{}{
			"name":  name,
			"email": email,
		})
	})

	h.Spin()
}

分组路由

go
package main

import (
	"context"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
	h := server.Default()

	// 创建 API 路由组
	api := h.Group("/api")
	{
		// 用户相关路由
		users := api.Group("/users")
		{
			users.GET("", getUsers)
			users.GET("/:id", getUserByID)
			users.POST("", createUser)
			users.PUT("/:id", updateUser)
			users.DELETE("/:id", deleteUser)
		}

		// 产品相关路由
		products := api.Group("/products")
		{
			products.GET("", getProducts)
			products.GET("/:id", getProductByID)
		}
	}

	h.Spin()
}

// 用户处理函数
func getUsers(c context.Context, ctx *app.RequestContext) {
	// 获取用户列表的逻辑
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"users": []map[string]interface{}{
			{"id": 1, "name": "John"},
			{"id": 2, "name": "Jane"},
		},
	})
}

func getUserByID(c context.Context, ctx *app.RequestContext) {
	userID := ctx.Param("id")
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"user": map[string]interface{}{
			"id":   userID,
			"name": "User " + userID,
		},
	})
}

func createUser(c context.Context, ctx *app.RequestContext) {
	// 创建用户的逻辑
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"message": "User created successfully",
	})
}

func updateUser(c context.Context, ctx *app.RequestContext) {
	userID := ctx.Param("id")
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"message": "User " + userID + " updated successfully",
	})
}

func deleteUser(c context.Context, ctx *app.RequestContext) {
	userID := ctx.Param("id")
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"message": "User " + userID + " deleted successfully",
	})
}

// 产品处理函数
func getProducts(c context.Context, ctx *app.RequestContext) {
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"products": []map[string]interface{}{
			{"id": 1, "name": "Product A"},
			{"id": 2, "name": "Product B"},
		},
	})
}

func getProductByID(c context.Context, ctx *app.RequestContext) {
	productID := ctx.Param("id")
	ctx.JSON(consts.StatusOK, map[string]interface{}{
		"product": map[string]interface{}{
			"id":   productID,
			"name": "Product " + productID,
		},
	})
}

如有转载或 CV 的请标注本站原文地址