52 lines
1012 B
Go
52 lines
1012 B
Go
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")
|
||
}
|