cwsaws

package module
v0.0.0-...-344536c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2025 License: MIT Imports: 31 Imported by: 0

README

cwsaws - AWS Services Utility Library

The cwsaws library provides a simplified interface to work with various AWS services in Go applications. It offers a consistent pattern for initializing service clients, connection pooling, and higher-level abstractions over the AWS SDK for Go v2.

Supported AWS Services

  • DynamoDB: CRUD operations, table management, and batch processing
  • S3: Object storage with local caching support
  • SQS: Message queue operations and Lambda event processing
  • SNS: Notification and SMS delivery
  • SES: Email delivery with template support
  • CloudWatch: Logging and monitoring
  • STS: Identity and access management

Environment Variables

Variable Module Type Description
S3CacheTTL cwsaws int S3 Object local cache time to live in minutes (default: 10)
S3VersionCheck cwsaws int Time in seconds between S3 version checks (default: 30)
CLOUDWATCHLOG_LOG_GROUP cwsaws string AWS CloudWatch log group name
Local_DynamoDB_AWS_ID cwsaws string AWS ID for local DynamoDB connections
Local_DynamoDB_AWS_Secret cwsaws string AWS Secret for local DynamoDB connections
Local_DynamoDB_URL cwsaws string URL for local DynamoDB endpoint
Local_DynamoDB_REGION cwsaws string Region for local DynamoDB connections

Installation

go get github.com/codeworks-tw/cwsutil/cwsaws

Usage Examples

DynamoDB
import "github.com/codeworks-tw/cwsutil/cwsaws"

// Create a DynamoDB table proxy
ctx := context.Background()
tableProxy := cwsaws.GetDynamoDBTableProxy[map[string]any]("my-table", ctx)

// Get item from table
key := map[string]types.AttributeValue{
    "id": &types.AttributeValueMemberS{Value: "123"},
}
input := &dynamodb.GetItemInput{
    Key: key,
}
item, err := tableProxy.ProxyGetItem(input)
S3
import "github.com/codeworks-tw/cwsutil/cwsaws"

// Create an S3 proxy for a specific bucket
ctx := context.Background()
s3Proxy := cwsaws.GetS3Proxy(ctx, "my-bucket")

// Check if object exists
exists := s3Proxy.ProxyObjectExists("path/to/object.json")

// Get object with caching
jsonObject, err := s3Proxy.ProxyGetObject("path/to/object.json", func(content []byte) (any, error) {
    var data map[string]any
    err := json.Unmarshal(content, &data)
    return data, err
})
SQS
import "github.com/codeworks-tw/cwsutil/cwsaws"

// Create an SQS proxy and process messages
ctx := context.Background()
sqsProxy := cwsaws.GetSqsProxy(ctx, func(ctx context.Context, msg types.Message) error {
    // Process message
    fmt.Println("Message body:", *msg.Body)
    return nil
})

// Initialize by queue name
err := sqsProxy.ProxyInitializeByName("my-queue")

// Process next batch of messages
err = sqsProxy.ProxyProcessNextMessages(10)
CloudWatch Logging
import "github.com/codeworks-tw/cwsutil/cwsaws"

// Create a CloudWatch logs proxy
ctx := context.Background()
cwProxy := cwsaws.GetCloudWatchLogProxy(ctx)

// Send a log message
err := cwProxy.SendMessage("My log message")
SES (Simple Email Service)
import (
    "github.com/codeworks-tw/cwsutil/cwsaws"
    "net/mail"
)

// Create an SES proxy
ctx := context.Background()
sesProxy := cwsaws.GetSesProxy(ctx)

// Send an email
email := &cwsaws.SESProxyEmailInput{
    From: mail.Address{Name: "Sender", Address: "sender@example.com"},
    To: []mail.Address{{Name: "Recipient", Address: "recipient@example.com"}},
    Subject: "Test Email",
    Body: "<h1>Hello World</h1>",
    // IsText: false, // Default is HTML
}
result, err := sesProxy.ProxySendEmail(email)
SNS (Simple Notification Service)
import "github.com/codeworks-tw/cwsutil/cwsaws"

// Create an SNS proxy
ctx := context.Background()
snsProxy := cwsaws.GetSnsProxy(ctx)

// Send SMS notification
result, err := snsProxy.ProxySendPhoneNotification("+1234567890", "Hello World from SNS")

// Send notification using template
templateInput := &cwsaws.SNSProxyTemplateNotificationInput{
    TemplateName: "my-template",
    Phone:        "+1234567890",
    Params:       []any{"John", "Doe"},
}
result, err = snsProxy.ProxySendTemplateNotification(templateInput)

Generic Repository Pattern

The cwsaws library provides a generic Repository pattern for DynamoDB operations:

import "github.com/codeworks-tw/cwsutil/cwsaws"

// Define primary key structure
type UserPKey struct {
    ID string `json:"id"`
}

// Create repository
repo := &cwsaws.Repository[UserPKey]{
    TableName: "users",
}

// Get item
ctx := context.Background()
pKey := UserPKey{ID: "123"}
user, err := repo.Get(ctx, pKey)

// Update item with expression
updateExpr := expression.Set(expression.Name("status"), expression.Value("active"))
expr, _ := expression.NewBuilder().WithUpdate(updateExpr).Build()
updatedUser, err := repo.Merge(ctx, pKey, expr)

// Query items
queryExpr := expression.Key("id").Equal(expression.Value("123"))
keyExpr, _ := expression.NewBuilder().WithKeyCondition(queryExpr).Build()
items, err := repo.Query(ctx, "my-index", keyExpr)

// Delete item
deletedUser, err := repo.Delete(ctx, pKey)

Release History

  • 0.3.7 - Sep. 20, 2025 - Added CloudWatch logging support
  • 0.3.6 - Jun. 15, 2025
  • 0.3.5 - May. 25, 2025
  • 0.1.0 - Apr. 11, 2024 - Initial release

License

Copyright (c) 2024 - Present Codeworks TW Ltd.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSingletonClient

func GetSingletonClient[T any](name ClientName, ctx context.Context, clientGenFn func(cfg aws.Config) T, optFns ...func(*config.LoadOptions) error) T

func ProxyProcessLambdaEvent

func ProxyProcessLambdaEvent(ctx context.Context, event events.SQSEvent, processFn func(ctx context.Context, msg types.Message) error) error

func StructToAttributeValueMap

func StructToAttributeValueMap(s any, modify ...func(key string, val any) any) (map[string]types.AttributeValue, error)

Types

type ClientName

type ClientName string
const (
	ClientName_STS        ClientName = "STS"
	ClientName_DynamoDB   ClientName = "DynamoDB"
	ClientName_SQS        ClientName = "SQS"
	ClientName_SNS        ClientName = "SNS"
	ClientName_S3         ClientName = "S3"
	ClientName_SES        ClientName = "SES"
	ClientName_CloudWatch ClientName = "CloudWatch"
)

type CloudWatchLogsProxy

type CloudWatchLogsProxy struct {
	*cloudwatchlogs.Client
	Context  *context.Context
	LogGroup string
}

func GetCloudWatchLogProxy

func GetCloudWatchLogProxy(ctx context.Context, optFns ...func(*config.LoadOptions) error) CloudWatchLogsProxy

func (*CloudWatchLogsProxy) CreateLogGroup

func (p *CloudWatchLogsProxy) CreateLogGroup() error

func (*CloudWatchLogsProxy) CreateLogStream

func (p *CloudWatchLogsProxy) CreateLogStream() error

func (*CloudWatchLogsProxy) GetTimedLogStreamName

func (p *CloudWatchLogsProxy) GetTimedLogStreamName(interval int) *string

func (*CloudWatchLogsProxy) SendMessage

func (p *CloudWatchLogsProxy) SendMessage(message string) error

type DynamoDBTableProxy

type DynamoDBTableProxy[O any] struct {
	*dynamodb.Client
	Context   *context.Context
	TableName string
}

func GetDynamoDBTableProxy

func GetDynamoDBTableProxy[O any](name string, ctx context.Context, optFns ...func(*config.LoadOptions) error) DynamoDBTableProxy[O]

func (*DynamoDBTableProxy[O]) ProxyCreateTableAndWaitActive

func (table *DynamoDBTableProxy[O]) ProxyCreateTableAndWaitActive(input *dynamodb.CreateTableInput) (*dynamodb.CreateTableOutput, error)

func (*DynamoDBTableProxy[O]) ProxyDeleteItem

func (table *DynamoDBTableProxy[O]) ProxyDeleteItem(input *dynamodb.DeleteItemInput) (*O, error)

func (*DynamoDBTableProxy[O]) ProxyDeleteTableAndWait

func (table *DynamoDBTableProxy[O]) ProxyDeleteTableAndWait() (*dynamodb.DeleteTableOutput, error)

func (*DynamoDBTableProxy[O]) ProxyGetItem

func (table *DynamoDBTableProxy[O]) ProxyGetItem(input *dynamodb.GetItemInput) (*O, error)

func (*DynamoDBTableProxy[O]) ProxyPutItem

func (table *DynamoDBTableProxy[O]) ProxyPutItem(input *dynamodb.PutItemInput) (*O, error)

func (*DynamoDBTableProxy[O]) ProxyQuery

func (table *DynamoDBTableProxy[O]) ProxyQuery(input *dynamodb.QueryInput) ([]*O, error)

func (*DynamoDBTableProxy[O]) ProxyQueryBatchUpdate

func (table *DynamoDBTableProxy[O]) ProxyQueryBatchUpdate(input *dynamodb.QueryInput, callback func(item *O, batchRequests *[]types.WriteRequest) *[]types.WriteRequest) *sync.WaitGroup

func (*DynamoDBTableProxy[O]) ProxyScan

func (table *DynamoDBTableProxy[O]) ProxyScan(input *dynamodb.ScanInput) ([]*O, error)

func (*DynamoDBTableProxy[O]) ProxyScanWithCalback

func (table *DynamoDBTableProxy[O]) ProxyScanWithCalback(input *dynamodb.ScanInput, callback func(item *O, batchRequests []types.WriteRequest) []types.WriteRequest) *sync.WaitGroup

func (*DynamoDBTableProxy[O]) ProxyTableHasGSI

func (table *DynamoDBTableProxy[O]) ProxyTableHasGSI(gsiName string) bool

func (*DynamoDBTableProxy[O]) ProxyTableIsActive

func (table *DynamoDBTableProxy[O]) ProxyTableIsActive() bool

func (*DynamoDBTableProxy[O]) ProxyUpdateItem

func (table *DynamoDBTableProxy[O]) ProxyUpdateItem(input *dynamodb.UpdateItemInput) (*O, error)

type IRepository

type IRepository[PKey any] interface {
	Get(ctx context.Context, pKey PKey, columns ...string) (*map[string]any, error)
	Query(ctx context.Context, indexName string, expr expression.Expression) ([]*map[string]any, error)
	Merge(ctx context.Context, pKey PKey, expr expression.Expression) (*map[string]any, error)
	Delete(ctx context.Context, pKey PKey) (*map[string]any, error)
	GetDynamoDBTableProxy(ctx context.Context) *DynamoDBTableProxy[map[string]any]
	GetPKeyKeys() []string
}

type Repository

type Repository[PKey any] struct {
	IRepository[PKey]
	TableName string
}

func (*Repository[PKey]) Delete

func (r *Repository[PKey]) Delete(ctx context.Context, pKey PKey) (*map[string]any, error)

func (*Repository[PKey]) Get

func (r *Repository[PKey]) Get(ctx context.Context, pKey PKey, columns ...string) (*map[string]any, error)

func (*Repository[PKey]) GetDynamoDBTableProxy

func (r *Repository[PKey]) GetDynamoDBTableProxy(ctx context.Context) DynamoDBTableProxy[map[string]any]

func (*Repository[PKey]) GetPKeyKeys

func (r *Repository[PKey]) GetPKeyKeys() []string

func (*Repository[PKey]) Merge

func (r *Repository[PKey]) Merge(ctx context.Context, pKey PKey, expr expression.Expression) (*map[string]any, error)

func (*Repository[PKey]) Query

func (r *Repository[PKey]) Query(ctx context.Context, indexName string, expr expression.Expression) ([]*map[string]any, error)

func (*Repository[PKey]) QueryBatchUpdate

func (r *Repository[PKey]) QueryBatchUpdate(ctx context.Context, indexName string, expr expression.Expression, callback func(item *map[string]any, batchRequests *[]types.WriteRequest) *[]types.WriteRequest)

type S3Proxy

type S3Proxy struct {
	*s3.Client
	Context    context.Context
	BucketName string
	Versioning *bool
	Lock       sync.Mutex
}

func GetS3Proxy

func GetS3Proxy(ctx context.Context, bucketName string) S3Proxy

func (*S3Proxy) IsVersioning

func (p *S3Proxy) IsVersioning() (bool, error)

func (*S3Proxy) ProxyGetObject

func (p *S3Proxy) ProxyGetObject(subPath string, parsingFunc func(content []byte) (any, error)) (any, error)

func (*S3Proxy) ProxyGetObjectVersionId

func (p *S3Proxy) ProxyGetObjectVersionId(subPath string) (string, error)

func (*S3Proxy) ProxyObjectExists

func (p *S3Proxy) ProxyObjectExists(subPath string) bool

func (*S3Proxy) ProxyPutObject

func (p *S3Proxy) ProxyPutObject(subPath string, object []byte) error

type S3ProxyObject

type S3ProxyObject struct {
	Content          any
	VersionId        string
	ExpiredTimeStamp int
	NextVersionCheck int
}

type SESProxy

type SESProxy struct {
	*ses.Client
	Context context.Context
}

func GetSesProxy

func GetSesProxy(ctx context.Context) SESProxy

func (*SESProxy) ProxyGetTemplateMessage

func (p *SESProxy) ProxyGetTemplateMessage(input SESProxyTemplateInput) (string, string, error)

func (*SESProxy) ProxySendEmail

func (p *SESProxy) ProxySendEmail(input *SESProxyEmailInput) (*ses.SendEmailOutput, error)

func (*SESProxy) ProxySendTemplateEmail

func (p *SESProxy) ProxySendTemplateEmail(input *SESProxyTemplateEmailInput) (*ses.SendEmailOutput, error)

type SESProxyEmailInput

type SESProxyEmailInput struct {
	From           mail.Address
	To             []mail.Address
	CC             []mail.Address
	BCC            []mail.Address
	Subject        string
	SubjectCharset string // default: UTF-8
	Body           string
	BodyCharset    string // default: UTF-8
	IsText         bool   // default: html
}

type SESProxyTemplateEmailInput

type SESProxyTemplateEmailInput struct {
	TemplateInput SESProxyTemplateInput
	From          mail.Address
	To            []mail.Address
	CC            []mail.Address
	BCC           []mail.Address
}

type SESProxyTemplateInput

type SESProxyTemplateInput struct {
	TemplateName  string
	SubjectParams map[string]any
	MessageParams map[string]any
	IsText        bool // default: html
}

type SNSProxy

type SNSProxy struct {
	*sns.Client
	Context  context.Context
	Topic    string
	TopicArn string
}

func GetSnsProxy

func GetSnsProxy(ctx context.Context) SNSProxy

func GetSnsProxyWithTopic

func GetSnsProxyWithTopic(ctx context.Context, Topic string) SNSProxy

func (*SNSProxy) ProxySendPhoneNotification

func (s *SNSProxy) ProxySendPhoneNotification(phone string, content string, phases ...any) (*sns.PublishOutput, error)

func (*SNSProxy) ProxySendTemplateNotification

func (s *SNSProxy) ProxySendTemplateNotification(input *SNSProxyTemplateNotificationInput) (*sns.PublishOutput, error)

type SNSProxyTemplateNotificationInput

type SNSProxyTemplateNotificationInput struct {
	TemplateName string
	Phone        string
	Params       []any
}

type SQSProxy

type SQSProxy struct {
	*sqs.Client
	Context   context.Context
	QueueName string
	AccountId string
	QueueArn  string
	QueueUrl  string
	Region    string
	// contains filtered or unexported fields
}

func GetSqsProxy

func GetSqsProxy(ctx context.Context, processFn ...func(ctx context.Context, msg types.Message) error) SQSProxy

func (*SQSProxy) ProxyInitializeByArn

func (proxy *SQSProxy) ProxyInitializeByArn(arn string) error

func (*SQSProxy) ProxyInitializeByName

func (proxy *SQSProxy) ProxyInitializeByName(name string) error

func (*SQSProxy) ProxyProcessNextMessages

func (proxy *SQSProxy) ProxyProcessNextMessages(MaxNumberOfMessages int32) error

type STSProxy

type STSProxy struct {
	*sts.Client
	Context context.Context
	// contains filtered or unexported fields
}

func GetStsClient

func GetStsClient(ctx context.Context) STSProxy

func (*STSProxy) GetAccountId

func (proxy *STSProxy) GetAccountId() (string, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL