Go RestAPI and DynamoDB with Post/Get/Put/Delete example code

Go with DynamoDB for Post: saving data

Here’s an example of a Go REST API that can handle a POST request to insert data into a DynamoDB table:

package main

import (
    "context"
    "encoding/json"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-lambda-go/lambdacontext"
    "fmt"
)

type Item struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Create a new AWS session
    sess := session.Must(session.NewSession())

    // Create a new DynamoDB client
    db := dynamodb.New(sess)

    // Get the request body
    var item Item
    json.Unmarshal([]byte(request.Body), &item)
    if item.ID == "" || item.Name == "" || item.Email == "" {
        return events.APIGatewayProxyResponse{
            Body:       "Missing required fields",
            StatusCode: 400,
        }, nil
    }

    // Create a new DynamoDB PutItemInput
    input := &dynamodb.PutItemInput{
        TableName: aws.String("my-table"),
        Item: map[string]*dynamodb.AttributeValue{
            "id": {
                S: aws.String(item.ID),
            },
            "name": {
                S: aws.String(item.Name),
            },
            "email": {
                S: aws.String(item.Email),
            },
        },
    }

    // Put the item into the DynamoDB table
    _, err := db.PutItem(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       fmt.Sprintf("Failed to insert item into DynamoDB: %s", err),
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item inserted into DynamoDB"),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function unmarshals the request body into an Item struct, which includes id, name, email fields. The function also checks if any of the fields is missing, if any of the field is missing it returns a Bad Request error message.

Go RestAPI to PUT data to DynamoDB example code

Here’s an example of a Go REST API that can handle a PUT request to update data in a DynamoDB table:

package main

import (
    "context"
    "encoding/json"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-lambda-go/lambda"
    "fmt"
)

type Item struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Create a new AWS session
    sess := session.Must(session.NewSession())

    // Create a new DynamoDB client
    db := dynamodb.New(sess)

    // Get the request body
    var item Item
    json.Unmarshal([]byte(request.Body), &item)
    if item.ID == "" || item.Name == "" || item.Email == "" {
        return events.APIGatewayProxyResponse{
            Body:       "Missing required fields",
            StatusCode: 400,
        }, nil
    }

    // Create a new DynamoDB UpdateItemInput
    input := &dynamodb.UpdateItemInput{
        TableName: aws.String("my-table"),
        Key: map[string]*dynamodb.AttributeValue{
            "id": {
                S: aws.String(item.ID),
            },
        },
        ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
            ":name": {
                S: aws.String(item.Name),
            },
            ":email": {
                S: aws.String(item.Email),
            },
        },
        UpdateExpression: aws.String("SET name = :name, email = :email"),
        ReturnValues:     aws.String("UPDATED_NEW"),
    }

    // Update the item in the DynamoDB table
    _, err := db.UpdateItem(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       fmt.Sprintf("Failed to update item in DynamoDB: %s", err),
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item updated in DynamoDB"),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function unmarshals the request body into an Item struct, which includes id, name, email fields.

Go RestAPI to Get data from DynamoDB example code

Here is an example of a Go REST API that retrieves data from a DynamoDB table:

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/dynamodb"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and region from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create DynamoDB client
    svc := dynamodb.New(sess)

    // Create Router
    router := mux.NewRouter()

    // Define API endpoint
    router.HandleFunc("/items/{id}", func(w http.ResponseWriter, r *http.Request) {
        // Get item ID from request parameters
        vars := mux.Vars(r)
        id := vars["id"]

        // Prepare the input for the GetItem function call
        input := &dynamodb.GetItemInput{
            TableName: aws.String("myTable"),
            Key: map[string]*dynamodb.AttributeValue{
                "id": {
                    S: aws.String(id),
                },
            },
        }

        // Call GetItem
        result, err := svc.GetItem(input)
        if err != nil {
            log.Println(err.Error())
            return
        }

        // Write response
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(result.String()))
    }).Methods("GET")

    // Start Server
    log.Fatal(http.ListenAndServe(":8000", router))
}

This example uses the Gorilla mux router to handle HTTP requests and the AWS SDK for Go to interact with DynamoDB. The code defines an API endpoint that can be accessed at the path “/items/{id}” and listens on port 8000. When a GET request is received at this endpoint, the code retrieves the item ID from the request parameters, prepares an input for the DynamoDB GetItem function, and calls the function to retrieve the item with the specified ID. The item’s contents are returned in the response.

Note: you need to set up your AWS credentials in the same way as you would for any other AWS SDK that you use.

You can also use the Amazon DynamoDB Document Client, an abstraction over the low-level DynamoDB client that simplifies working with data in DynamoDB. You can find more information on the AWS documentation website.

Go RestAPI to Delete data from DynamoDB example code

Here is an example of a Go REST API that deletes data from a DynamoDB table:

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/dynamodb"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and region from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create DynamoDB client
    svc := dynamodb.New(sess)

    // Create Router
    router := mux.NewRouter()

    // Define API endpoint
    router.HandleFunc("/items/{id}", func(w http.ResponseWriter, r *http.Request) {
        // Get item ID from request parameters
        vars := mux.Vars(r)
        id := vars["id"]

        // Prepare the input for the DeleteItem function call
        input := &dynamodb.DeleteItemInput{
            TableName: aws.String("myTable"),
            Key: map[string]*dynamodb.AttributeValue{
                "id": {
                    S: aws.String(id),
                },
            },
        }

        // Call DeleteItem
        _, err := svc.DeleteItem(input)
        if err != nil {
            log.Println(err.Error())
            w.WriteHeader(http.StatusInternalServerError)
            return
        }

        // Return success status
        w.WriteHeader(http.StatusOK)
    }).Methods("DELETE")

    // Start Server
    log.Fatal(http.ListenAndServe(":8000", router))
}

This example uses the Gorilla mux router to handle HTTP requests and the AWS SDK for Go to interact with DynamoDB. The code defines an API endpoint that can be accessed at the path “/items/{id}” and listens on port 8000. When a DELETE request is received at this endpoint, the code retrieves the item ID from the request parameters, prepares an input for the DynamoDB DeleteItem function, and calls the function to delete the item with the specified ID. If the delete is successful, the code returns a 200 OK status, otherwise it returns a 500 Internal Server Error status.

Just like the previous example, you need to set up your AWS credentials in the same way as you would for any other AWS SDK that you use.

Upload/Download file CSV/Excel using Amazon Lambda with Go example code

Write example code: AWS Lambda with Go upload file

Here’s an example of an AWS Lambda function written in Go that can handle a file upload:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "io"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

    // Get the file from the request body
    file, header, err := request.GetFile("file")
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to get file from request body",
            StatusCode: 400,
        }, nil
    }
    defer file.Close()

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(header.Filename),
        Body:   file,
    }

    // Upload the file to S3
    _, err = svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s uploaded to S3", header.Filename),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file from the request body by calling request.GetFile(“file”), which returns the file, its header, and any error that may have occurred. If there is an error, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to S3.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message about the uploaded file.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Write example code: AWS Lambda with Go download file

Here’s an example of an AWS Lambda function written in Go that can handle a file download from an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "io"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the request query parameters
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query parameters",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }
    defer result.Body.Close()

    // Create a new file with the same name as the file in S3
    out, err := os.Create(fileName)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to create a new file",
            StatusCode: 500,
        }, nil
    }
    defer out.Close()

    // Copy the downloaded file to the new file
    _, err = io.Copy(out, result.Body)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to copy the downloaded file to the new file",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s downloaded from S3", fileName),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name from the request’s query parameters by calling request.QueryStringParameters[“fileName”], which returns the file name. If the file name is not provided, the function returns a Bad Request error message.

Write example code: AWS Lambda with Go upload CSV file

Here’s an example of an AWS Lambda function written in Go that can handle a CSV file upload to an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "mime/multipart"
    "io"
    "os"
    "strings"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file from the request body
    file, header, err := request.MultiValueHeaders["Content-File"][0], request.MultiValueHeaders["Content-Type"][0], request.MultiValueHeaders["Content-Disposition"][0]
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "File not found in request body",
            StatusCode: 400,
        }, nil
    }
    defer file.Close()

    // Get the file name from the request headers
    fileName := strings.Split(header, ";")[1]
    fileName = strings.TrimPrefix(fileName, " filename=")

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
        Body:   file,
    }

    // Upload the file to S3
    _, err = svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s uploaded to S3", fileName),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file from the request’s body by calling request.MultiValueHeaders[“Content-File”][0] which returns the file. If the file is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to the specified S3 bucket. The function also extracts the file name from the request headers, and the bucket name is hardcoded in the code.

Write example code: AWS Lambda with Go download CSV file

Here’s an example of an AWS Lambda function written in Go that can handle a CSV file download from an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the request query parameters
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query parameters",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }

    // Set the response headers
    headers := make(map[string]string)
    headers["Content-Type"] = "text/csv"
    headers["Content-Disposition"] = "attachment; filename=" + fileName

    return events.APIGatewayProxyResponse{
        Body:       result.Body.(io.ReadCloser),
        StatusCode: http.StatusOK,
        Headers: headers,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name from the request’s query parameters by calling request.QueryStringParameters[“fileName”]. If the file name is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the GetObject method to download the file from the specified S3 bucket. The function also sets the response headers to indicate that the response is a csv file and it is an attachment. The bucket name is hardcoded in the code.

Example code: AWS Lambda with Go upload Excel file

Here’s an example of an AWS Lambda function written in Go that can handle an Excel file upload to an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name and file content from the request body
    fileName := request.Headers["fileName"]
    fileContent := request.Body
    if fileName == "" || fileContent == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name or content not provided in request body",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
        Body:   strings.NewReader(fileContent),
    }

    // Upload the file to S3
    _, err := svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       "File uploaded successfully",
        StatusCode: http.StatusOK,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name and file content from the request body by calling request.Headers[“fileName”] and request.Body respectively. If the file name or content is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to the specified S3 bucket with the provided file name. The function also sets the response headers to indicate that the response is a excel file and it is an attachment. The bucket name is hardcoded in the code.

Example code: AWS Lambda with Go download Excel file

Here’s an example of an AWS Lambda function written in Go that can handle an Excel file download from an S3 bucket:

package main

import (
    "context"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the query string
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query string",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }

    // Get the file content
    fileContent, err := ioutil.ReadAll(result.Body)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to read file content",
            StatusCode: 500,
        }, nil
    }

    // Set the response headers to indicate that the response is a excel file and it is an attachment
    headers := make(map[string]string)
    headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    headers["Content-Disposition"] = "attachment; filename="+fileName

    return events.APIGatewayProxyResponse{
        Body:       string(fileContent),
        StatusCode: http.StatusOK,
        Headers: headers,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name from the query string by calling request.QueryStringParameters[“fileName”]. If the file name is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the GetObject method to download the file from the specified S3 bucket with the provided file name. The function also sets the response headers to indicate that the response is a excel

How to build AWS Lambda with Go example code: Post/Get/Put/Delete

How to build AWS Lambda with Go example code

To build an AWS Lambda function with Go, you will need to do the following:

1. Install the AWS SDK for Go by running go get -u github.com/aws/aws-sdk-go
2. Create a new Go file for your Lambda function, and import the necessary packages from the AWS SDK.
3. Define a function that will serve as the entry point for your Lambda function, and ensure it has the correct signature.
4. Build your Go code and create a deployment package (e.g. a ZIP file).
5. Use the AWS CLI or the AWS Lambda console to create or update your Lambda function, and provide the deployment package as the function code.

Here’s an example of a simple Lambda function written in Go:

package main

import (
"context"
"github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context) (string, error) {
return "Hello, World!", nil
}

func main() {
lambda.Start(HandleRequest)
}

Note: you will also need to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Post Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a POST request:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

type Request struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    var req Request
    json.Unmarshal([]byte(request.Body), &req)
    fmt.Printf("Received request: %+v\n", req)

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s! Your age is %d", req.Name, req.Age),
        StatusCode: 200,
    }
    return response, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function parses the incoming JSON payload in the request body and Unmarshals the json data into struct Request.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message including the Name and Age field from the request body.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Get Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a GET request:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    queryParams := request.QueryStringParameters

    name, ok := queryParams["name"]
    if !ok {
        name = "World"
    }

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s!", name),
        StatusCode: 200,
    }
    return response, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the value of the “name” query parameter from the request object and if it’s not present, it defaults to “World”. It then creates a response in the form of events.APIGatewayProxyResponse which contains a message using the name parameter.

You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Put Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a PUT request:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

type Request struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    var req Request
    json.Unmarshal([]byte(request.Body), &req)
    fmt.Printf("Received request: %+v\n", req)

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s! Your age is %d", req.Name, req.Age),
        StatusCode: 200,
    }
    return response, nil
}

func main() {
    lambda.Start(HandleRequest)
}

This example is similar to the previous POST request example. In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function parses the incoming JSON payload in the request body and Unmarshals the json data into struct Request.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message including the Name and Age field from the request body.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.
Please note that in a PUT request, it is a common practice to update the existing data instead of creating a new one. You can use DynamoDB or other data storage service to store and update the data.

Build Aws Lambda with Delete Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a DELETE request:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    pathParams := request.PathParameters

    id, ok := pathParams["id"]
    if !ok {
        return events.APIGatewayProxyResponse{
            Body:       "Missing id in path",
            StatusCode: 400,
        }, nil
    }

    // Delete the item with the given id from your data store
    err := deleteItem(id)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to delete item",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item with id %s deleted", id),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the value of the “id” path parameter from the request object and if it’s not present, returns a Bad Request error message . It then calls deleteItem function which deletes the item with the given id from your data store.
In the deleteItem function you can use DynamoDB or other data storage service to delete the data.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message about the deleted item.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Create RestAPI with Go & Postgres: Post, Get, PUT, Delete example code

Create Post Api with Go example code

To create a “POST” API in Go, you can use the net/http package that is included in the Go standard library. Here’s an example of how you can create a simple “POST” API that listens on a specific port and responds with “Hello, World!” when a client makes a “POST” request to the endpoint:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodPost {
			fmt.Fprint(w, "Hello, World!")
			return
		}
		http.Error(w, "Invalid request method", http.StatusBadRequest)
	})

	http.ListenAndServe(":8080", nil)
}

In this example, the http.HandleFunc function is used to register a function that will be called whenever a client makes a request to the root endpoint (“/”). The function checks the request method to see if it is a “POST” request, and if it is, it responds with “Hello, World!”. If the request method is not “POST”, it sends an error response with status code “400 Bad Request”. Finally, the http.ListenAndServe function is used to start the server and listen for incoming requests on port 8080.

Create GET api with go example code

Here is an example of a basic GET API written in Go using the popular Gin web framework:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello, World!",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the root URL (“/”) that responds to GET requests. The route handler is a function that takes a Gin context as its argument. This function sends a JSON response with a message of “Hello, World!” and a status code of 200 OK. Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a GET request to http://localhost:8080/ using any HTTP client.

Create PUT API with Go example code

Here is an example of a basic PUT API written in Go using the popular Gin web framework:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.PUT("/user/:id", func(c *gin.Context) {
        // Get the ID from the URL parameters
        id := c.Param("id")

        // Bind the request body to a struct
        var user struct {
            Name string `json:"name" binding:"required"`
            Age  int    `json:"age" binding:"required"`
        }
        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        // Update the user in the database
        // ...

        c.JSON(http.StatusOK, gin.H{
            "message": "User updated successfully",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to PUT requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then binds the request body to a struct, in this case the struct is user which contains Name and Age field.
Then it checks if there is any error from the binding process, if there is, it will return a Bad Request with the error message.
If no error, it will update the user in the database (this part is left to you to implement) and then sends a JSON response with a message of “User updated successfully” and a status code of 200 OK. Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a PUT request to http://localhost:8080/user/ using any HTTP client with json payload of the user such as {“name”:”John”,”age”:25}

Create Delete RestAPI with Go example code

Here is an example of a basic DELETE REST API written in Go using the popular Gin web framework:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.DELETE("/user/:id", func(c *gin.Context) {
        // Get the ID from the URL parameters
        id := c.Param("id")

        // Delete the user from the database
        // ...

        c.JSON(http.StatusOK, gin.H{
            "message": "User deleted successfully",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to DELETE requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then deletes the user from the database (this part is left to you to implement) and then sends a JSON response with a message of “User deleted successfully” and a status code of 200 OK. Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a DELETE request to http://localhost:8080/user/ using any HTTP client.

Create Post RestAPI with Go and Postgresql example code

Here is an example of a basic POST REST API written in Go using the popular Gin web framework and Postgresql as a database:

package main

import (
    "database/sql"
    "net/http"

    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "postgres://user:password@host/dbname")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    r := gin.Default()

    r.POST("/user", func(c *gin.Context) {
        // Bind the request body to a struct
        var user struct {
            Name string `json:"name" binding:"required"`
            Age  int    `json:"age" binding:"required"`
        }
        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        // Insert the user into the database
        _, err := db.Exec("INSERT INTO users (name, age) VALUES ($1, $2)", user.Name, user.Age)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusCreated, gin.H{
            "message": "User created successfully",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the URL path /user that responds to POST requests.
The route handler is a function that takes a Gin context as its argument. This function first binds the request body to a struct, in this case the struct is user which contains Name and Age field.
Then it checks if there is any error from the binding process, if there is, it will return a Bad Request with the error message.
If no error, it will insert the user into the Postgresql database by executing the SQL statement INSERT INTO users (name, age) VALUES ($1, $2) using the user’s name and age as the parameters and then sends a JSON response with a message of “User created successfully” and a status code of 201 Created.
It also checks if there is any error while executing the query, if so it will return a status code of 500 Internal Server Error with the error message.
Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a POST request to http://localhost:8080/user using any HTTP client with json payload of the user such as {“name”:”John”,”age”:25}

Please note that the database connection string is an example and you need to change it to match your database credentials and settings.
Also, it is important to note that you need to have the “github.com/lib/pq” package installed and imported in order to use postgres as a database with Go.
Also, it is assumed that you have the necessary table created in the database and ready to use.

Create Get RestAPI with Go and Postgresql example code

Here is an example of a basic GET REST API written in Go using the popular Gin web framework and Postgresql as a database:

package main

import (
    "database/sql"
    "net/http"

    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "postgres://user:password@host/dbname")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    r := gin.Default()

    r.GET("/user/:id", func(c *gin.Context) {
        // Get the ID from the URL parameters
        id := c.Param("id")

        // Get the user from the database
        var user struct {
            Name string
            Age  int
        }
        err := db.QueryRow("SELECT name, age FROM users WHERE id = $1", id).Scan(&user.Name, &user.Age)
        if err != nil {
            c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
            return
        }

        c.JSON(http.StatusOK, gin.H{
            "user": user,
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to GET requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then it queries the Postgresql database for user with the corresponding id by executing the SQL statement SELECT name, age FROM users WHERE id = $1 and scan the result into user struct.
Then it checks if there is any error from the query, if there is and the error is not found, it will return a Not Found with the error message.
If no error, it will send a JSON response with the user data and a status code of 200 OK.
Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a GET request to http://localhost:8080/user/ using any HTTP client.
Please note that the database connection string is an example and you need to change it to match your database credentials and settings.
Also, it is important to note that you need to have the “github.com/lib/pq” package installed and imported in order to use postgres as a database with Go.
Also, it is assumed that you have the necessary table created in the database and ready to use.

Create Put RestAPI with Go and Postgresql example code

Here is an example of a basic PUT REST API written in Go using the popular Gin web framework and Postgresql as a database:

package main

import (
    "database/sql"
    "net/http"

    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "postgres://user:password@host/dbname")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    r := gin.Default()

    r.PUT("/user/:id", func(c *gin.Context) {
        // Get the ID from the URL parameters
        id := c.Param("id")

        // Bind the request body to a struct
        var user struct {
            Name string `json:"name" binding:"required"`
            Age  int    `json:"age" binding:"required"`
        }
        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        // Update the user in the database
        _, err := db.Exec("UPDATE users SET name = $1, age = $2 WHERE id = $3", user.Name, user.Age, id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{
            "message": "User updated successfully",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to PUT requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then binds the request body to a struct, in this case the struct is user which contains Name and Age field.
Then it checks if there is any error from the binding process, if there is, it will return a Bad Request with the error message.
If no error, it will update the user in the Postgresql database by executing the SQL statement UPDATE users SET name = $1, age = $2 WHERE id = $3 using the user’s name, age and id as the parameters and then sends a JSON response with a message of “User updated successfully” and a status code of 200 OK.
It also checks if there is any error while executing the query, if so it will return a status code of 500 Internal Server Error with the error message.
Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a PUT request to http://localhost:8080/user/ using any HTTP client with json payload of the user such as {“name”:”John”,”age”:25}
Please note that the database connection string is an example and you need to change it to match your database credentials and settings.

Create Delete RestAPI with Go and Postgresql example code

Here is an example of a basic DELETE REST API written in Go using the popular Gin web framework and Postgresql as a database:

package main

import (
    "database/sql"
    "net/http"

    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "postgres://user:password@host/dbname")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    r := gin.Default()

    r.DELETE("/user/:id", func(c *gin.Context) {
        // Get the ID from the URL parameters
        id := c.Param("id")

        // Delete the user from the database
        _, err := db.Exec("DELETE FROM users WHERE id = $1", id)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{
            "message": "User deleted successfully",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This code creates a new Gin router and sets up a route for the URL path /user/:id that responds to DELETE requests. The :id in the route path is a URL parameter.
The route handler is a function that takes a Gin context as its argument. This function first extracts the “id” from the URL parameters, then deletes the user from the Postgresql database by executing the SQL statement DELETE FROM users WHERE id = $1 using the user’s id as the parameter and then sends a JSON response with a message of “User deleted successfully” and a status code of 200 OK.
It also checks if there is any error while executing the query, if so it will return a status code of 500 Internal Server Error with the error message.
Finally, the router is started by calling the Run() method.

You would run this code by running go run main.go, and then making a DELETE request to http://localhost:8080/user/ using any HTTP client.

How to write unit-testcase for Go RestAPI

Unit testing in Go is typically done using the built-in testing package. You can use this package to create unit tests for your REST API by writing test functions that make HTTP requests to your API and assert that the responses are as expected.

Here’s an example of how you might write a unit test for a GET endpoint that retrieves a user by ID:

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
)

func TestGetUser(t *testing.T) {
    // Set up the router and a test server
    router := gin.Default()
    router.GET("/user/:id", getUser)
    w := httptest.NewRecorder()
    req, _ := http.NewRequest("GET", "/user/1", nil)
    router.ServeHTTP(w, req)

    // Assert that the response has the expected status code and body
    if w.Code != http.StatusOK {
        t.Errorf("Expected status code %d, got %d", http.StatusOK, w.Code)
    }
    expectedBody := `{"user":{"name":"John","age":25}}`
    if w.Body.String() != expectedBody {
        t.Errorf("Expected body %s, got %s", expectedBody, w.Body.String())
    }
}

This test function creates a new Gin router, sets up a route for the /user/:id path that calls the getUser function, and then creates a test server using httptest.NewRecorder().
It creates an HTTP GET request to the endpoint and serves the request to the test server.
The test function uses the testing package’s Errorf function to check that the response has the expected status code (200 OK) and body ({“user”:{“name”:”John”,”age”:25}}).

To run this test, you can use the command go test in your project’s directory. The test function name should be in the format Test* to be recognized as a unit test.

You can also use testing frameworks like testify which provides a lot of useful testing utility functions like assert and require which makes it more readable and easy to use for testing.

It’s also important to note that you may want to consider testing your database interactions in isolation, by using a library like sqlmock which allows you to mock and test your database interactions without hitting an actual database.