笔记-go反射操作私有变量

// Index 获取首页信息
func (receiver *Home) Index(req *controllers.HomeRequest, ctx *gin.Context) (*controllers.HomeResponse, error) {
    value := reflect.ValueOf(ctx).Elem()

    engine := value.FieldByName("engine")
    // rf can't be read or set.
    engine = reflect.NewAt(engine.Type(), unsafe.Pointer(engine.UnsafeAddr())).Elem()
    v := engine.Interface()
    context := v.(*gin.Engine)
    help.Dump(context)

    return &controllers.HomeResponse{}, nil
}

不需要依赖注释生成文档,可以反射操作所有路由信息

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!