aws/aws-sdk-go
GitHub: aws/aws-sdk-go
亚马逊官方的 AWS SDK for Go v1,为 Go 语言应用提供全面的 AWS 云服务 API 调用能力,现已进入维护终止状态。
Stars: 8682 | Forks: 2044
# AWS SDK for Go
[](https://docs.aws.amazon.com/sdk-for-go/api) [](https://github.com/aws/aws-sdk-go/blob/main/LICENSE.txt)
## 快速示例
### 完整 SDK 示例
此示例展示了一个完整可运行的 Go 文件,它将文件上传到 S3
并使用 Context 模式实现超时逻辑,如果耗时过长,将取消该
请求。此示例重点说明了如何使用 session、
创建 service client、发出请求、处理错误以及处理
响应。
```
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Uploads a file to S3 given a bucket and object key. Also takes a duration
// value to terminate the update if it doesn't complete within that time.
//
// The AWS Region needs to be provided in the AWS shared config or on the
// environment variable as `AWS_REGION`. Credentials also must be provided
// Will default to shared config file, but can load from environment if provided.
//
// Usage:
// # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail
// go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt
func main() {
var bucket, key string
var timeout time.Duration
flag.StringVar(&bucket, "b", "", "Bucket name.")
flag.StringVar(&key, "k", "", "Object key name.")
flag.DurationVar(&timeout, "d", 0, "Upload timeout.")
flag.Parse()
// All clients require a Session. The Session provides the client with
// shared configuration such as region, endpoint, and credentials. A
// Session should be shared where possible to take advantage of
// configuration and credential caching. See the session package for
// more information.
sess := session.Must(session.NewSession())
// Create a new instance of the service's client with a Session.
// Optional aws.Config values can also be provided as variadic arguments
// to the New function. This option allows you to provide service
// specific configuration.
svc := s3.New(sess)
// Create a context with a timeout that will abort the upload if it takes
// more than the passed in timeout.
ctx := context.Background()
var cancelFn func()
if timeout > 0 {
ctx, cancelFn = context.WithTimeout(ctx, timeout)
}
// Ensure the context is canceled to prevent leaking.
// See context package for more information, https://golang.org/pkg/context/
if cancelFn != nil {
defer cancelFn()
}
// Uploads the object to S3. The Context will interrupt the request if the
// timeout expires.
_, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: os.Stdin,
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode {
// If the SDK can determine the request or retry delay was canceled
// by a context the CanceledErrorCode error code will be returned.
fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err)
} else {
fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err)
}
os.Exit(1)
}
fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key)
}
```
### SDK 包概述
SDK 由两个主要组件组成:SDK 核心和 service client。
SDK 核心包均位于 SDK 根目录下的 aws 包中。
支持的每个 AWS service 的 client 都位于
SDK 根目录下 service 文件夹中各自的包内。
- aws - SDK 核心,提供通用的共享类型,如 Config、Logger,
以及使处理 API 参数更轻松的实用工具。
- awserr - 提供 SDK 在其处理过程中发生的所有
错误所使用的 error 接口。这也包括 service API
响应错误。Error 类型由 code 和 message 组成。
将 SDK 返回的 error 类型转换为 awserr.Error,并调用 Code
方法,将返回的错误与特定的错误代码进行比较。有关可以提取的其他值(如 RequestID),请参阅该包的
文档。
- credentials - 提供 SDK 用于检索 AWS 凭证以发出 API 请求的
类型和内置 credentials provider。
此文件夹下还包含其他 credentials provider,例如
用于代入 IAM 角色的 stscreds,以及用于 EC2 Instance 角色的 ec2rolecreds。
- endpoints - 为 SDK 提供 AWS Regions 和 Endpoints 元数据。
使用它来查找 AWS service endpoint 信息,例如哪些服务位于
某个区域中,以及某个服务位于哪些区域中。还提供了
所有区域标识符的常量,例如用于 "us-west-2" 的 UsWest2RegionID。
- session - 提供初始默认配置,并从
外部源(如环境和共享
凭证文件)加载配置。
- request - 为 SDK 提供 API 请求发送和重试逻辑。
此包还包括用于定义您自己的
请求重试器,以及配置 SDK 如何处理请求的实用工具。
- service - AWS 服务的 client。SDK 支持的所有服务均位于
此文件夹下。
### 如何使用 SDK 的 AWS Service Client
SDK 包含可用于向
AWS service API 发出请求的 Go 类型和实用工具。在 SDK 根目录的 service 文件夹中,您会找到
SDK 支持的每个 AWS service 对应的一个包。所有 service client 都遵循通用的创建和使用模式。
在为 AWS service 创建 client 时,您首先需要构造一个 Session
值。Session 提供可在您的 service client 之间共享的
共享配置。创建 service client 时,您可以通过 aws.Config 类型传入
附加配置,以覆盖 Session 中提供的配置,从而创建具有自定义
配置的 service client 实例。
一旦创建了服务的 client,您就可以使用它向
AWS 服务发出 API 请求。这些 client 可以安全地并发使用。
### 配置 SDK
在 AWS SDK for Go 中,您可以配置 service client 的设置,例如
日志级别和最大重试次数。大多数设置是可选的;
然而,对于每个 service client,您必须指定区域和凭证。
SDK 使用这些值将请求发送到正确的 AWS 区域,并使用
正确的凭证对请求进行签名。您可以将这些值指定为
session 的一部分或环境变量。
有关更多信息,请参阅 SDK 的 [配置指南][config_guide]。
有关如何结合 SDK 使用 Session 的更多信息,请参阅
[session][session_pkg] 包文档。
有关配置选项的更多信息,请参阅 [aws][aws_pkg] 包中的 [Config][config_typ] 类型。
### 配置凭证
使用 SDK 时,您通常需要 AWS 凭证来进行 AWS 服务
身份验证。SDK 支持多种提供这些
凭证的方法。默认情况下,SDK 会自动从
其默认凭证链中获取凭证。有关此链以及如何配置它的更多信息,请参阅 session 包。凭证
链中的常见项如下:
- 环境凭证 - 一组环境变量,当
为特定角色创建子进程时非常有用。
- 共享凭证文件 (~/.aws/credentials) - 此文件根据
配置文件名称存储您的凭证,对于本地开发非常有用。
- EC2 Instance Role 凭证 - 使用 EC2 Instance Role 分配凭证
给运行在 EC2 实例上的应用程序。这消除了在生产环境中管理
凭证文件的需要。
也可以在代码中通过将 Config 的 Credentials
值设置为自定义 provider 或使用 SDK 包含的某个 provider 来配置凭证,以绕过默认凭证链并使用自定义链。当
您希望指示 SDK 仅使用一组特定的
凭证或 provider 时,这非常有用。
此示例创建了一个用于代入 IAM 角色 "myRoleARN"
的 credential provider,并配置 S3 service client 以将该角色用于 API 请求。
```
// Initial credentials loaded from SDK's default credential chain. Such as
// the environment, shared credentials (~/.aws/credentials), or EC2 Instance
// Role. These credentials will be used to to make the STS Assume Role API.
sess := session.Must(session.NewSession())
// Create the credentials from AssumeRoleProvider to assume the role
// referenced by the "myRoleARN" ARN.
creds := stscreds.NewCredentials(sess, "myRoleArn")
// Create service client value configured for credentials
// from assumed role.
svc := s3.New(sess, &aws.Config{Credentials: creds})
```
有关 SDK 附带的 credential provider 以及如何自定义 SDK 使用凭证的更多信息,
请参阅 [credentials][credentials_pkg] 包文档。
```
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
```
### 配置 AWS Region
除凭证外,您还需要指定 SDK 将用于向
发出 AWS API 请求的区域。在 SDK 中,您可以通过环境变量指定区域,或者在创建 Session 或
service client 时直接在代码中指定。如果以多种方式指定了区域,则以代码中指定的最后一个值为准。
要通过环境变量设置区域,请将 "AWS_REGION" 设置为您希望
SDK 使用的区域。使用此方法设置区域
将允许您的应用程序在多个区域中运行,而无需在应用程序中
使用额外的代码来选择区域。
```
AWS_REGION=us-west-2
```
endpoints 包包含 SDK 已知的所有区域的常量。这些
值均以 RegionID 为后缀。这些值非常有用,因为它们
减少了手动输入区域字符串的需要。
要在 Session 上设置区域,请将 aws 包的 Config 结构体参数
Region 设置为您希望从该 session 创建的 service client 使用的 AWS 区域。
当您想要创建多个 service client,并且所有 client 都向同一区域发出 API 请求时,这非常有用。
```
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(endpoints.UsWest2RegionID),
}))
```
有关 AWS Regions 和 Endpoints 元数据,请参阅 [endpoints][endpoints_pkg] 包。
除了在创建 Session 时设置区域外,您还可以按
各个 service client 设置区域。这将覆盖 Session 的区域。当您希望在不同于 Session 区域的特定
区域中创建 service client 时,这非常有用。
```
svc := s3.New(sess, &aws.Config{
Region: aws.String(endpoints.UsWest2RegionID),
})
```
有关更多信息和其他选项(例如设置 Endpoint 和其他 service client 配置选项),请参阅 [aws][aws_pkg] 包中的 [Config][config_typ] 类型。
### 发出 API 请求
创建 client 后,您可以向该服务发出 API 请求。
每个 API 方法接受一个输入参数,并返回服务响应
和错误。SDK 提供了多种方法来进行 API 调用。
在此列表中,我们将使用 S3 ListObjects API 作为不同请求方式的示例。
- ListObjects - 将向服务发出 API 请求的基础 API 操作。
- ListObjectsRequest - 以 Request 为后缀的 API 方法将构造
API 请求,但不发送它。当您希望获取
请求的预签名 URL,并共享该预签名 URL 而不是让您的
应用程序直接发出请求时,这非常有用。
- ListObjectsPages - 与基础 API 操作相同,但使用回调自动
处理 API 响应的分页。
- ListObjectsWithContext - 与基础 API 操作相同,但增加了对
Context 模式的支持。这对于控制取消进行中的
请求非常有用。有关更多信息,请参阅 Go 标准库 context 包。此方法还将 request 包的 Option
函数式选项作为可变参数,用于修改请求的发出方式,或从原始 HTTP 响应中提取信息。
- ListObjectsPagesWithContext - 与 ListObjectsPages 相同,但增加了对
Context 模式的支持。与 ListObjectsWithContext 类似,此方法还将 request 包的 Option 函数选项类型作为可变参数。
除了 API 操作外,SDK 还包含几种高级方法,
这些方法抽象了检查并等待 AWS 资源达到
所需状态的过程。在此列表中,我们将使用 WaitUntilBucketExists 来演示
不同形式的 waiter。
- WaitUntilBucketExists. - 向 AWS 服务发出 API 请求以查询资源
状态的方法。当达到该状态时,将成功返回。
- WaitUntilBucketExistsWithContext - 与 WaitUntilBucketExists 相同,但增加了对
Context 模式的支持。此外,这些方法采用 request
包的 WaiterOptions 来配置 waiter,以及 SDK 将如何发出底层请求。
API 方法将记录该服务可能为该操作返回的错误代码。
这些错误也将作为以 service client 包中 "ErrCode" 为前缀的 const 字符串提供。如果 API 的 SDK 文档中没有列出
任何错误,您需要查阅 AWS 服务的 API
文档,以了解可能返回的错误。
```
ctx := context.Background()
result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{
Bucket: aws.String("my-bucket"),
Key: aws.String("my-key"),
})
if err != nil {
// Cast err to awserr.Error to handle specific error codes.
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == s3.ErrCodeNoSuchKey {
// Specific error code handling
}
return err
}
// Make sure to close the body when done with it for S3 GetObject APIs or
// will leak connections.
defer result.Body.Close()
fmt.Println("Object Size:", aws.Int64Value(result.ContentLength))
```
### API 请求分页和 Resource Waiter
分页辅助方法以 "Pages" 为后缀,并提供
完成 API 页面请求往返所需的功能。分页方法
采用一个回调函数,该函数将为 API 响应的每一页调用。
```
objects := []string{}
err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
Bucket: aws.String(myBucket),
}, func(p *s3.ListObjectsOutput, lastPage bool) bool {
for _, o := range p.Contents {
objects = append(objects, aws.StringValue(o.Key))
}
return true // continue paging
})
if err != nil {
panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err))
}
fmt.Println("Objects in bucket:", objects)
```
Waiter 辅助方法提供了等待 AWS 资源
状态的功能。这些方法抽象了检查 AWS
资源状态所需的逻辑,并等待直到该资源处于所需状态。waiter
将阻塞,直到资源处于所需状态、发生错误或
waiter 超时。如果资源超时,返回的错误代码将是
request.WaiterResourceNotReadyErrorCode。
```
err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{
Bucket: aws.String(myBucket),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode {
fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist")
}
panic(fmt.Errorf("failed to wait for bucket to exist, %v", err))
}
fmt.Println("Bucket", myBucket, "exists")
```
## 资源
[开发者指南](https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html) - 本文档
是对如何配置和使用 SDK 发出请求的总体介绍。
如果您是第一次使用 SDK,此文档和 API
文档将帮助您入门。本文档重点介绍 SDK 的语法
和行为。[服务开发者指南](https://aws.amazon.com/documentation/)
将帮助您开始使用特定的 AWS 服务。
[SDK API 参考文档](https://docs.aws.amazon.com/sdk-for-go/api/) - 使用此
文档查找 SDK 支持的 AWS 服务的所有 API 操作输入和输出参数。API 参考还包括
SDK 的文档,以及如何使用 SDK、service client API 操作和
API 操作所需参数的示例。
[服务文档](https://aws.amazon.com/documentation/) - 使用此
文档了解如何与 AWS 服务进行交互。这些指南非常适合
开始使用某项服务,或者需要了解更多
有关某项服务的信息时使用。虽然本文档不是编码所必需的,
但服务可能会提供值得关注的实用示例。
[SDK 示例](https://github.com/aws/aws-sdk-go/tree/main/example) -
SDK 的代码库中包含几个精心制作的示例,展示了如何使用 SDK
功能和 AWS 服务。
标签:EVTX分析, 日志审计, 漏洞利用检测