AdSense

網頁

2024/3/6

Golang 建立AWS CloudWatch API client

Go以Google API Client Libraries來取得操作CloudWatch的API client。


事前要求

參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的credentials。


下載AWS SDK Go V2 modules

在專案根目錄執行以下命令下載需要的aws-sdk-go-v2 modules。



建立CloudWatch API client

呼叫config.LoadDefaultConfig傳入region參數(e.g. "ap-northeast-1")建立aws.Conifg物件,AWS SDK預設會讀取$HOME/.aws/credentials的access keys來通過權限驗證,然後呼叫cloudwatch.NewFromConfig建立cloudwatch.Client

main.go

package main

import (
    "context"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
)

func NewCloudWatchClient(ctx context.Context) *cloudwatch.Client {
    cfg, err := config.LoadDefaultConfig(
        ctx,
        config.WithRegion("ap-northeast-1"),
    )
    if err != nil {
        panic(err)
    }

    return cloudwatch.NewFromConfig(cfg) // Create a CloudWatch service client
}

func main() {
    ctx := context.TODO()
    client := NewCloudWatchClient(ctx)
    ...
}

沒有留言:

AdSense