CodeSampleX

샘플

github.com/aws/aws-sdk-go-v2 v1.41.7: aws.NewConfig, aws.String, aws.ToString

검증된 샘플 — golang github.com/aws/aws-sdk-go-v2 v1.41.7: aws.NewConfig, aws.String, aws.ToString. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:c40db6c933680ce5e76027f5cac9746f3eb1f3fb4e5ad8b7de704f80476de1ad

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-10-09

케이스

HOW
목표
verify pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7
패키지
심벌
  • aws.NewConfig
  • aws.String
  • aws.ToString
  • aws.CredentialsProviderFunc
  • aws.NewCredentialsCache
  • aws.AnonymousCredentials
생성일
2026-10-09T03:51:53Z

컨트랙트

  1. aws.NewConfig returns an initialized Config and Copy produces an independent shallow copy
  2. aws.String and aws.ToString correctly convert between string values and pointers with safe nil handling
  3. aws.CredentialsProviderFunc wraps a function satisfying CredentialsProvider interface and retrieves credentials
  4. aws.NewCredentialsCache caches credentials and delegates retrieval to underlying provider
  5. aws.AnonymousCredentials returns sentinel credentials and reports expected retrieval error

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json
  • test/contract.go

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:d0868ce1103521a2a88bcbb03fb204734a65044fe3b5e2fe99f607f95ce5b7e1","contract":["aws.NewConfig returns an initialized Config and Copy produces an independent shallow copy","aws.String and aws.ToString correctly convert between string values and pointers with safe nil handling","aws.CredentialsProviderFunc wraps a function satisfying CredentialsProvider interface and retrieves credentials","aws.NewCredentialsCache caches credentials and delegates retrieval to underlying provider","aws.AnonymousCredentials returns sentinel credentials and reports expected retrieval error"],"goal":"verify pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7","kind":"HOW","packages":["pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7"],"schemaVersion":1,"symbols":["aws.NewConfig","aws.String","aws.ToString","aws.CredentialsProviderFunc","aws.NewCredentialsCache","aws.AnonymousCredentials"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7"],"schemaVersion":1,"subject":"pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7","symbols":["aws.NewConfig","aws.String","aws.ToString","aws.CredentialsProviderFunc","aws.NewCredentialsCache","aws.AnonymousCredentials"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/aws/aws-sdk-go-v2 v1.41.7

require github.com/aws/smithy-go v1.25.1 // indirect
go.sum
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
sample.go
package sample

import (
	"context"
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
)

// ClientConfigHolder wraps an aws.Config with helper methods.
type ClientConfigHolder struct {
	Config aws.Config
}

// NewClientConfigHolder creates a new ClientConfigHolder with specified region and credentials provider.
func NewClientConfigHolder(region string, creds aws.CredentialsProvider) (*ClientConfigHolder, error) {
	if region == "" {
		return nil, fmt.Errorf("region cannot be empty")
	}

	cfg := aws.NewConfig()
	cfg.Region = region
	cfg.Credentials = creds

	return &ClientConfigHolder{
		Config: cfg.Copy(),
	}, nil
}

// CreateStaticCredentialsProvider returns a CredentialsProvider that supplies static credentials.
func CreateStaticCredentialsProvider(accessKey, secretKey, sessionToken string) aws.CredentialsProvider {
	return aws.CredentialsProviderFunc(func(ctx context.Context) (aws.Credentials, error) {
		return aws.Credentials{
			AccessKeyID:     accessKey,
			SecretAccessKey: secretKey,
			SessionToken:    sessionToken,
			Source:          "StaticCredentialsProvider",
		}, nil
	})
}

// CreateCachedCredentialsProvider wraps an underlying provider with a CredentialsCache.
func CreateCachedCredentialsProvider(provider aws.CredentialsProvider, expiryWindow time.Duration) *aws.CredentialsCache {
	return aws.NewCredentialsCache(provider, func(options *aws.CredentialsCacheOptions) {
		options.ExpiryWindow = expiryWindow
	})
}

// SafeStringValue dereferences a string pointer using aws.ToString with a fallback.
func SafeStringValue(val *string, fallback string) string {
	res := aws.ToString(val)
	if res == "" {
		return fallback
	}
	return res
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/aws/aws-sdk-go-v2@v1.41.7"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"sample"
)

func main() {
	if err := runTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All AWS SDK Go v2 contract tests passed successfully.")
}

func runTests() error {
	ctx := context.Background()

	// 1. aws.NewConfig returns an initialized Config and Copy produces an independent shallow copy
	{
		cfg := aws.NewConfig()
		if cfg == nil {
			return fmt.Errorf("expected non-nil Config from aws.NewConfig")
		}
		cfg.Region = "us-east-1"

		holder, err := sample.NewClientConfigHolder("us-west-2", nil)
		if err != nil {
			return fmt.Errorf("unexpected error creating ClientConfigHolder: %w", err)
		}
		if holder.Config.Region != "us-west-2" {
			return fmt.Errorf("expected region us-west-2, got %q", holder.Config.Region)
		}

		copied := holder.Config.Copy()
		if copied.Region != "us-west-2" {
			return fmt.Errorf("expected copied region to be us-west-2, got %q", copied.Region)
		}
	}

	// 2. aws.String and aws.ToString correctly convert between string values and pointers with safe nil handling
	{
		ptr := aws.String("example-endpoint")
		if ptr == nil || *ptr != "example-endpoint" {
			return fmt.Errorf("expected valid pointer from aws.String")
		}

		val := aws.ToString(ptr)
		if val != "example-endpoint" {
			return fmt.Errorf("expected 'example-endpoint' from aws.ToString, got %q", val)
		}

		nilVal := aws.ToString(nil)
		if nilVal != "" {
			return fmt.Errorf("expected empty string from aws.ToString(nil), got %q", nilVal)
		}

		fallback := sample.SafeStringValue(nil, "default-val")
		if fallback != "default-val" {
			return fmt.Errorf("expected fallback value, got %q", fallback)
		}
	}

	// 3. aws.CredentialsProviderFunc wraps a function satisfying CredentialsProvider interface and retrieves credentials
	{
		staticProvider := sample.CreateStaticCredentialsProvider("test-access-key", "test-secret-key", "test-session-token")
		creds, err := staticProvider.Retrieve(ctx)
		if err != nil {
			return fmt.Errorf("unexpected error retrieving credentials: %w", err)
		}
		if creds.AccessKeyID != "test-access-key" || creds.SecretAccessKey != "test-secret-key" {
			return fmt.Errorf("credentials fields mismatch: %+v", creds)
		}
		if !creds.HasKeys() {
			return fmt.Errorf("expected creds.HasKeys() to be true")
		}
	}

	// 4. aws.NewCredentialsCache caches credentials and delegates retrieval to underlying provider
	{
		callCount := 0
		customProvider := aws.CredentialsProviderFunc(func(c context.Context) (aws.Credentials, error) {
			callCount++
			return aws.Credentials{
				AccessKeyID:     fmt.Sprintf("key-%d", callCount),
				SecretAccessKey: "secret-data",
				CanExpire:       true,
				Expires:         time.Now().Add(10 * time.Minute),
			}, nil
		})

		cache := sample.CreateCachedCredentialsProvider(customProvider, 10*time.Second)
		if cache == nil {
			return fmt.Errorf("expected non-nil CredentialsCache")
		}

		first, err := cache.Retrieve(ctx)
		if err != nil {
			return fmt.Errorf("error in first Retrieve: %w", err)
		}
		if callCount != 1 {
			return fmt.Errorf("expected callCount 1, got %d", callCount)
		}

		second, err := cache.Retrieve(ctx)
		if err != nil {
			return fmt.Errorf("error in second Retrieve: %w", err)
		}
		if callCount != 1 {
			return fmt.Errorf("expected cached callCount to remain 1, got %d", callCount)
		}
		if second.AccessKeyID != first.AccessKeyID {
			return fmt.Errorf("expected cached credentials to match")
		}
	}

	// 5. aws.AnonymousCredentials returns sentinel credentials and reports expected retrieval error
	{
		anon := aws.AnonymousCredentials{}
		creds, err := anon.Retrieve(ctx)
		if err == nil {
			return fmt.Errorf("expected error from AnonymousCredentials.Retrieve")
		}
		if creds.Source != "AnonymousCredentials" {
			return fmt.Errorf("expected Source AnonymousCredentials, got %q", creds.Source)
		}
	}

	return nil
}

오리진 시더

익명