AdSense

網頁

2023/9/5

Golang 建立AWS Pricing API client

Go以AWS提供的SDK aws-sdk-go-v2來取得操作AWS Price List Service資源的API client。



事前要求

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


下載AWS SDK Go V2 modules

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


建立Pricing API client

在Go程式中呼叫config.LoadDefaultConfig傳入region參數("ap-south-1""us-east-1""eu-central-1")建立aws.Conifg物件,AWS SDK預設會讀取$HOME/.aws/credentials的access keys來通過權限驗證,然後依此參數呼叫pricing.NewFromConfig建立pricing.Client

main.go

package main

import (
    "context"

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

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

func NewPricingClient(ctx context.Context) *pricing.Client {
    cfg, err := config.LoadDefaultConfig(
        ctx,
        config.WithRegion("ap-south-1"), // only support "us-east-1", "eu-central-1", "ap-south-1" 
    )
    if err != nil {
        panic(err)
    }

    return pricing.NewFromConfig(cfg) // Create an Pricing service client
}

沒有留言:

AdSense