github.com/aavshr/aws-sdk-go@v1.41.3/example/aws/request/httptrace/main.go (about) 1 // build example 2 3 package main 4 5 import ( 6 "bufio" 7 "context" 8 "errors" 9 "flag" 10 "fmt" 11 "log" 12 "os" 13 14 "github.com/aavshr/aws-sdk-go/aws" 15 "github.com/aavshr/aws-sdk-go/aws/session" 16 "github.com/aavshr/aws-sdk-go/service/sns" 17 ) 18 19 var clientCfg ClientConfig 20 var topicARN string 21 22 func init() { 23 clientCfg.SetupFlags("", flag.CommandLine) 24 25 flag.CommandLine.StringVar(&topicARN, "topic", "", 26 "The topic `ARN` to send messages to") 27 } 28 29 func main() { 30 if err := flag.CommandLine.Parse(os.Args[1:]); err != nil { 31 flag.CommandLine.PrintDefaults() 32 exitErrorf(err, "failed to parse CLI commands") 33 } 34 if len(topicARN) == 0 { 35 flag.CommandLine.PrintDefaults() 36 exitErrorf(errors.New("topic ARN required"), "") 37 } 38 39 httpClient := NewClient(clientCfg) 40 sess, err := session.NewSession(&aws.Config{ 41 HTTPClient: httpClient, 42 }) 43 if err != nil { 44 exitErrorf(err, "failed to load config") 45 } 46 47 // Start making the requests. 48 svc := sns.New(sess) 49 ctx := context.Background() 50 51 fmt.Printf("Message: ") 52 53 // Scan messages from the input with newline separators. 54 scanner := bufio.NewScanner(os.Stdin) 55 for scanner.Scan() { 56 trace, err := publishMessage(ctx, svc, topicARN, scanner.Text()) 57 if err != nil { 58 fmt.Fprintf(os.Stderr, "failed to publish message, %v\n", err) 59 } 60 log.Println(trace) 61 62 fmt.Println() 63 fmt.Printf("Message: ") 64 } 65 if err := scanner.Err(); err != nil { 66 fmt.Fprintf(os.Stderr, "failed to read input, %v", err) 67 } 68 } 69 70 // publishMessage will send the message to the SNS topic returning an request 71 // trace for metrics. 72 func publishMessage(ctx context.Context, svc *sns.SNS, topic, msg string) (*RequestTrace, error) { 73 trace := &RequestTrace{} 74 75 _, err := svc.PublishWithContext(ctx, &sns.PublishInput{ 76 TopicArn: &topic, 77 Message: &msg, 78 }, trace.TraceRequest) 79 if err != nil { 80 return trace, err 81 } 82 83 return trace, nil 84 } 85 86 func exitErrorf(err error, msg string, args ...interface{}) { 87 fmt.Fprintf(os.Stderr, "FAILED: %v\n"+msg+"\n", append([]interface{}{err}, args...)...) 88 os.Exit(1) 89 }