emahiro/b.log

Drastically Repeat Yourself !!!!

aws.EndpointResolverWithOptions はエラー時にデフォルトの Endpoint Endpoint Resolver を返す

タイトルの通りなんですが、AWS SDK Go V2 を利用して AWS の設定を初期化する実装をする際に Endpoint Resolver Option を設定したいケースがあると思います。

リージョンが異なるなどで AWS に各サービスごとに設定内容を変えたいケースなどが使いたいケースかと思いますが、特に設定しないケースにおいてはエラーを返す ( aws.EndpointNotFoundError を返す)とデフォルトの Endpoint Resolver が返されるとドキュメントに書いてありました。

EndpointResolverWithOptions is an endpoint resolver that can be used to provide or override an endpoint for the given service, region, and the service client's EndpointOptions. API clients will attempt to use the EndpointResolverWithOptions first to resolve an endpoint if available. If the EndpointResolverWithOptions returns an EndpointNotFoundError error, API clients will fallback to attempting to resolve the endpoint using its internal default endpoint resolver.

pkg.go.dev

実装としては以下のようになります。

import (
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
)

// 略

awscfg, err = config.LoadDefaultConfig(context.TODO(), config.WithEndpointResolverWithOptions(aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
    if service == $awsServcieID { // cf. ses.ServiceID
        // service ごとに aws.Endpoint の中身を変更する。
    } 
    return aws.Endpoint{}, &aws.EndpointNotFoundError{}
}))

エラーを返すとデフォルトの設定が割り当てられる、というのはちょっとトリッキーな設定ですが知ってると挙動を AWS SDK に任せられるので便利だなと思いました。