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

使用AWS SDK Go V2添加CloudFront行为遇CachedMethods必填错误

解决CloudFront添加行为时的CachedRequired错误

问题原因

尽管AWS SDK for Go v2将CachedMethods标记为弃用,但如果你的CloudFront分发仍在使用传统缓存配置(未指定CachePolicyId),CloudFront底层API依然要求必须提供CachedMethods参数。弃用标记仅表示AWS推荐用缓存策略(Cache Policy)替代手动配置缓存行为,而非完全移除该参数的必要性。

解决方案1:补全CachedMethods参数(兼容旧模式)

创建CacheBehavior时,添加CachedMethods字段,其值需为AllowedMethods的子集(通常包含GET和HEAD):

newBehavior := cloudfrontTypes.CacheBehavior{
    TargetOriginId:       aws.String(originID),
    PathPattern:          aws.String(pathPattern),
    ViewerProtocolPolicy: cloudfrontTypes.ViewerProtocolPolicyAllowAll,
    AllowedMethods: &cloudfrontTypes.AllowedMethods{
        Quantity: aws.Int32(2),
        Items: []cloudfrontTypes.Method{
            cloudfrontTypes.MethodGet,
            cloudfrontTypes.MethodHead,
        },
    },
    // 新增CachedMethods参数
    CachedMethods: &cloudfrontTypes.CachedMethods{
        Quantity: aws.Int32(2),
        Items: []cloudfrontTypes.Method{
            cloudfrontTypes.MethodGet,
            cloudfrontTypes.MethodHead,
        },
    },
    Compress:        aws.Bool(true),
    SmoothStreaming: aws.Bool(false),
    MinTTL:          aws.Int64(0),
    ForwardedValues: &cloudfrontTypes.ForwardedValues{
        QueryString: aws.Bool(false),
        Cookies: &cloudfrontTypes.CookiePreference{
            Forward: cloudfrontTypes.ItemSelectionAll,
        },
        Headers: &cloudfrontTypes.Headers{
            Quantity: aws.Int32(0),
        },
        QueryStringCacheKeys: &cloudfrontTypes.QueryStringCacheKeys{
            Quantity: aws.Int32(0),
        },
    },
    DefaultTTL:             aws.Int64(0),
    MaxTTL:                 aws.Int64(3600),
    FieldLevelEncryptionId: aws.String(""),
}

解决方案2:改用CachePolicyId(推荐新模式)

AWS推荐用缓存策略替代手动配置CachedMethods、ForwardedValues等参数,步骤如下:

  1. 在AWS控制台或通过SDK创建自定义缓存策略,或使用AWS托管策略(比如658327ea-f89d-4fab-a63d-7e88639e58f6对应「CachingOptimized」策略)
  2. 在CacheBehavior中设置CachePolicyId,同时移除被缓存策略替代的字段:
newBehavior := cloudfrontTypes.CacheBehavior{
    TargetOriginId:       aws.String(originID),
    PathPattern:          aws.String(pathPattern),
    ViewerProtocolPolicy: cloudfrontTypes.ViewerProtocolPolicyAllowAll,
    AllowedMethods: &cloudfrontTypes.AllowedMethods{
        Quantity: aws.Int32(2),
        Items: []cloudfrontTypes.Method{
            cloudfrontTypes.MethodGet,
            cloudfrontTypes.MethodHead,
        },
    },
    Compress:        aws.Bool(true),
    SmoothStreaming: aws.Bool(false),
    // 使用托管缓存策略CachingOptimized
    CachePolicyId: aws.String("658327ea-f89d-4fab-a63d-7e88639e58f6"),
    FieldLevelEncryptionId: aws.String(""),
}

注意:使用缓存策略后,ForwardedValues、MinTTL等参数会被策略配置覆盖,无需手动设置。

内容的提问来源于stack exchange,提问作者Dingba Nice

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:23:09