简体   繁体   中英

How to use AWS GO SDK with RESTful API?

I am new to using AWS SDKs and building APIs. However, I am trying to find a way to build an application where if I click a button on the web browser, I want it to trigger an amazon sdk Go function to build an AMI. How can I go about this?

I went through this tutorial on RESTful API with Go . However, I am getting confused on how the the Amazon SDK GO functions will be working with the APIs. So I have something like the code below. I just don't know if I am doing this correctly in terms of the high level.

package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ec2"
    "github.com/gorilla/mux"
    "net/http"
)

func (c *EC2) CreateLaunchTemplate(input *CreateLaunchTemplateInput) (*CreateLaunchTemplateOutput, error) {
    // w.Header().Set("Content-Type", "application/json")
    svc := ec2.New(session.New())
    input := &ec2.CreateLaunchTemplateInput{
        LaunchTemplateData: &ec2.RequestLaunchTemplateData{
            ImageId:      aws.String("ami-0cc142296677e2132"),
            InstanceType: aws.String("t2.micro"),
            NetworkInterfaces: []*ec2.LaunchTemplateInstanceNetworkInterfaceSpecificationRequest{
                {
                    AssociatePublicIpAddress: aws.Bool(true),
                    DeviceIndex:              aws.Int64(0),
                    Ipv6AddressCount:         aws.Int64(1),
                    SubnetId:                 aws.String("subnet-03a04de08c5c6cb8e"),
                },
            },
            TagSpecifications: []*ec2.LaunchTemplateTagSpecificationRequest{
                {
                    ResourceType: aws.String("instance"),
                    Tags: []*ec2.Tag{
                        {
                            Key:   aws.String("Name"),
                            Value: aws.String("webserver"),
                        },
                    },
                },
            },
        },
        LaunchTemplateName: aws.String("my-template"),
        VersionDescription: aws.String("WebVersion1"),
    }

    result, err := svc.CreateLaunchTemplate(input)
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            fmt.Println(err.Error())
        }
        return
    }
}

func main() {
    // Init Router
    r := mux.NewRouter()

    // Route Handlers / Endpoints
    r.HandleFunc("/api/create_ami", CreateLaunchTemplate).Methods("GET")
    log.Fatal(http.ListenAndServe(":8000", r))
}

I ended up solving the problem...I just didn't understand the syntaxes of golang and aws sdk. But I was able to spin an ami using a button.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ec2"
    "github.com/gorilla/mux"
)

func createInstance(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-1")},
    )

    // Create EC2 service client
    svc := ec2.New(sess)

    // Specify the details of the instance that you want to create.
    runResult, err := svc.RunInstances(&ec2.RunInstancesInput{
        // An Amazon Linux AMI ID for t2.micro instances in the us-west-2 region
        ImageId:      aws.String("ami-xxxxxx"),
        InstanceType: aws.String("t2.micro"),
        MinCount:     aws.Int64(1),
        MaxCount:     aws.Int64(1),
    })

    if err != nil {
        fmt.Println("Could not create instance", err)
        return
    }

    fmt.Println("Created instance", *runResult.Instances[0].InstanceId)

    // Add tags to the created instance
    _, errtag := svc.CreateTags(&ec2.CreateTagsInput{
        Resources: []*string{runResult.Instances[0].InstanceId},
        Tags: []*ec2.Tag{
            {
                Key:   aws.String("Name"),
                Value: aws.String("test"),
            },
        },
    })
    if errtag != nil {
        log.Println("Could not create tags for instance", runResult.Instances[0].InstanceId, errtag)
        return
    }
}

func main() {

    r := mux.NewRouter() //init the router

    fmt.Println("Successfully tagged instance")


    r.HandleFunc("/api/instance", createInstance).Methods("GET")
    log.Fatal(http.ListenAndServe(":8500", r))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM