Files
learn-golang/go-gin-demo/handler_demo.go
2025-12-26 17:56:02 +08:00

52 lines
1012 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"github.com/gin-gonic/gin"
)
// 方式 2独立函数推荐便于单元测试
func getProduct(c *gin.Context) {
productID := c.Param("id")
c.JSON(200, gin.H{
"id": productID,
"name": "Product",
})
}
// 方式 3结构体方法便于依赖注入
type ProductService struct {
name string
}
type ProductHandler struct {
service *ProductService
}
func (h *ProductHandler) Get(c *gin.Context) {
id := c.Param("id")
// 使用 h.service 调用业务逻辑
c.JSON(200, gin.H{
"id": id,
"service_name": h.service.name,
})
}
func main() {
r := gin.Default()
// 方式 1直接定义
r.GET("/method1", func(c *gin.Context) {
c.JSON(200, gin.H{"method": "inline"})
})
// 方式 2使用独立函数
r.GET("/products/:id", getProduct)
// 方式 3使用结构体方法
service := &ProductService{name: "ProductService"}
handler := &ProductHandler{service: service}
r.GET("/products-struct/:id", handler.Get)
r.Run(":9999")
}