[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
在gin中,可以通过反射来执行对应的方法。下面是一个示例:
package main import ( "fmt" "github.com/gin-gonic/gin" "reflect" ) type
UserControllerstruct{} func (uc *UserController) GetUser(c *gin.Context) {
userId:= c.Param("id") // 假设这里是一个查询用户的方法 user := uc.queryUser(userId) c.JSON(200
, user) } func (uc *UserController) queryUser(userId string) interface{} { //
查询用户的逻辑,这里只是一个示例 user := map[string]interface{}{ "id": userId, "name": "John
Doe", "age": 30, } return user } func main() { r := gin.Default() // 创建
UserController 实例 userController := &UserController{} // 使用反射执行对应的方法 r.GET(
"/users/:id", func(c *gin.Context) { // 获取方法名称 methodName := "GetUser" //
使用反射获取方法 method := reflect.ValueOf(userController).MethodByName(methodName) //
判断方法是否存在 if method.IsValid() { // 构造参数 args := []reflect.Value{reflect.ValueOf(c
)} // 执行方法 result := method.Call(args) // 获取返回值 if len(result) > 0 { //
假设返回值是一个 interface{} data := result[0] c.JSON(200, data.Interface()) } } else {
c.JSON(404, gin.H{"error": fmt.Sprintf("Method %s not found", methodName)}) } })
r.Run(":8080") }
在这个示例中,我们定义了一个UserController结构体,并在结构体中定义了GetUser方法和queryUser方法。GetUser
方法用于处理请求并返回用户数据,queryUser方法用于查询用户信息。
在主函数中,我们创建了UserController的实例userController,然后通过反射获取对应的方法GetUser,并通过Call
方法执行该方法,最后获取返回值并返回给客户端。
需要注意的是,反射的使用需要谨慎,因为它会带来一些性能开销。尽量避免在高频请求的场景下大量使用反射。