First function

The first function call of a package

We take the code from Return values AS SDK and put the creation of the client into a function named “init.

  1 package main
  2
  3 import (
  4         "context"
  5         "fmt"
  6
  7         "github.com/aws/aws-sdk-go-v2/aws"
  8         "github.com/aws/aws-sdk-go-v2/config"
  9         "github.com/aws/aws-sdk-go-v2/service/sns"
 10 )
 11
 12 var client *sns.Client
 13
 14 func init(){
 15         cfg, err := config.LoadDefaultConfig(context.TODO())
 16         if err != nil {
 17                 panic("configuration error, " + err.Error())
 18         }
 19         client = sns.NewFromConfig(cfg)
 20 }
 21
 22 func main() {
 23         topic := aws.String("go-topic")
 24
 25         parms := &sns.CreateTopicInput{
 26                 Name: topic,
 27         }
 28         results, err := client.CreateTopic(context.TODO(), parms)
 29         if err != nil {
 30                 panic("sns error, " + err.Error())
 31         }
 32         fmt.Println(*results.TopicArn)
 33 }
package main

import (
        "context"
        "fmt"

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

var client *sns.Client

func init(){
        cfg, err := config.LoadDefaultConfig(context.TODO())
        if err != nil {
                panic("configuration error, " + err.Error())
        }
        client = sns.NewFromConfig(cfg)
}

func main() {
        topic := aws.String("go-topic")

        parms := &sns.CreateTopicInput{
                Name: topic,
        }
        results, err := client.CreateTopic(context.TODO(), parms)
        if err != nil {
                panic("sns error, " + err.Error())
        }
        fmt.Println(*results.TopicArn)
}

The init function is automatically called before the main program. you can also use it to init a package.

The program structure

In line 12 we define a variable with package scope:

 12 var client *sns.Client

After the definition client is not initialized yet. But when we execute the program init is called as the very first function.

In line 19 we initialize the SNS client:

 19         client = sns.NewFromConfig(cfg)

Do not use the := operator, because it will create a local scope variable.

This code, if used inside the function init, will create a second variable which is not visible outside the init function. So this code will not work;

client := sns.NewFromConfig(cfg)

Execute program

Copy the program code without line numbers into a file named main.go, then execute the program:

go run main.go

That gives the topic ARN

arn:aws:sns:eu-central-1:555553403305:go-topic

Where 555553403305 is the account number

Cleanup

You can use this arn to delete the topic:

aws sns delete-topic --topic-arn arn:aws:sns:eu-central-1:555553403305:go-topic

Source

See the full source on github.

Sources