You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Go代码的if判断,实现Cilium双注解存在性检查?

Go代码修改方案:检查多个注解存在性

先给你解释下Go里if nodesubnet, ok := node.ObjectMeta.Annotations[xxx]; !ok这种语法:
这是Go的短变量声明+map存在性检查组合写法:

  • node.ObjectMeta.Annotations是map结构,用key取值时会返回两个值:对应key的value,以及一个布尔值ok——ok为true表示key存在,false表示不存在。
  • nodesubnet, ok := ...是在if条件里直接声明变量,这个变量仅在当前if/else代码块内有效。
  • 后面的!ok就是判断如果目标key不存在,就执行if块内的逻辑。

以下是满足你需求的修改代码,替换原316-318行的逻辑:

// 先尝试获取第一个Cilium注解
nodesubnet, ok := node.ObjectMeta.Annotations[CiliumK8sNodeSubnetAnnotation12]
// 如果第一个注解不存在,尝试获取第二个注解
if !ok {
    nodesubnet, ok = node.ObjectMeta.Annotations[CiliumK8sNodeSubnetAnnotation13]
}
// 两个注解都不存在时,打日志并跳过当前循环
if !ok {
    log.Warningf("Node subnet annotations %v or %v not found on node %v, static route not added", 
        CiliumK8sNodeSubnetAnnotation12, CiliumK8sNodeSubnetAnnotation13, node.Name)
    continue
}
// 走到这里说明至少有一个注解存在,直接使用nodesubnet的值
route.Network = nodesubnet
// 后续节点地址处理逻辑保持不变...

注意点

  • 第二次取值用nodesubnet, ok = ...而非:=,因为nodesubnet和ok已经在前面声明过,短变量声明:=不能重复定义已存在的变量。
  • 日志中同时列出两个注解,方便后续排查问题时明确检查范围。

内容的提问来源于stack exchange,提问作者99Linux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:27:05