Skip to content

Instantly share code, notes, and snippets.

@ei-grad
Created April 5, 2024 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ei-grad/dfccea206a21c647997e0e74d555abb4 to your computer and use it in GitHub Desktop.
Save ei-grad/dfccea206a21c647997e0e74d555abb4 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
type loggingRoundTripper struct {
logger *log.Logger
next http.RoundTripper
}
func (lrt *loggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// Send the request
resp, err := lrt.next.RoundTrip(req)
if err != nil {
return nil, err
}
// Copy the response body for logging
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Log the response body
lrt.logger.Printf("Response Body: %s\n", string(body))
// IMPORTANT: We need to replace the response body because it's been read
resp.Body = io.NopCloser(bytes.NewReader(body))
return resp, nil
}
func main() {
// Initialize logger
logger := log.New(os.Stdout, "", log.LstdFlags)
// Load the Shared AWS Configuration (~/.aws/config)
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithHTTPClient(&http.Client{
Transport: &loggingRoundTripper{
logger: logger,
next: http.DefaultTransport,
},
}),
)
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
// Create an Amazon STS service client
svc := sts.NewFromConfig(cfg)
// Call the GetCallerIdentity operation
result, err := svc.GetCallerIdentity(context.TODO(), &sts.GetCallerIdentityInput{})
if err != nil {
log.Fatalf("unable to get caller identity, %v", err)
}
fmt.Printf("%+v\n", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment