Go钩子函数示例

钩子函数

  • 这里主要参考了ClusterAPI里的machine_collection选择器,使用了钩子函数,支持自定义过滤条件(Hook)
// Filter returns a Machines containing only the Machines that match all of the given MachineFilters.
func (s Machines) Filter(filters ...Func) Machines {
	return newFilteredMachineCollection(And(filters...), s.UnsortedList()...)
}

// AnyFilter returns a Machines containing only the Machines that match any of the given MachineFilters.
func (s Machines) AnyFilter(filters ...Func) Machines {
	return newFilteredMachineCollection(Or(filters...), s.UnsortedList()...)
}

先看下Func的定义:

// Func is the functon definition for a filter.
type Func func(machine *clusterv1.Machine) bool

以及两个自定义Hook

// ActiveMachines returns a filter to find all active machines.
// Usage: GetFilteredMachinesForCluster(ctx, client, cluster, ActiveMachines).
func ActiveMachines(machine *clusterv1.Machine) bool {
	if machine == nil {
		return false
	}
	return machine.DeletionTimestamp.IsZero()
}

// HasDeletionTimestamp returns a filter to find all machines that have a deletion timestamp.
func HasDeletionTimestamp(machine *clusterv1.Machine) bool {
	if machine == nil {
		return false
	}
	return !machine.DeletionTimestamp.IsZero()
}

同时想支持And或Or(Hook)对过滤条件进行再筛选

// And returns a filter that returns true if all of the given filters returns true.
func And(filters ...Func) Func {
	return func(machine *clusterv1.Machine) bool {
		for _, f := range filters {
			if !f(machine) {
				return false
			}
		}
		return true
	}
}

// Or returns a filter that returns true if any of the given filters returns true.
func Or(filters ...Func) Func {
	return func(machine *clusterv1.Machine) bool {
		for _, f := range filters {
			if f(machine) {
				return true
			}
		}
		return false
	}
}

// Not returns a filter that returns the opposite of the given filter.
func Not(mf Func) Func {
	return func(machine *clusterv1.Machine) bool {
		return !mf(machine)
	}
}

通过钩子函数,使用的方式可以多种多样,如下:

machines := c.Machines.Filter(collections.Not(collections.HasDeletionTimestamp))

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值