Featured

Angular 8 – Upload/Display/Delete files to/from Firebase Storage using @angular/fire

In this tutorial, ozenero.com shows you way to upload, get, delete Files to/from Firebase Storage in a simple Angular 8 App using @angular/fire. Files’ info will be stored in Firebase Realtime Database.

Related Posts:
Angular 8 Firebase tutorial: Integrate Firebase into Angular 8 App with @angular/fire
Angular 8 Firebase CRUD operations with @angular/fire
Angular 8 Firestore tutorial with CRUD application example – @angular/fire

Want to know to to deploy Angular App on Hostings?
>> Please visit this Series (with Instructional Videos)

Continue reading “Angular 8 – Upload/Display/Delete files to/from Firebase Storage using @angular/fire”

Featured

Vue.js + Spring Boot example | Spring Data JPA + REST + MariaDB CRUD

Tutorial: Vue.js SpringBoot CRUD MariaDB Example | Spring Data JPA + REST + MariaDB CRUD

In this Vue.js SpringBoot tutorial, we show you Vue.js Http Client & Spring Boot Server example that uses Spring JPA to do CRUD with MariaDB and Vue.js as a front-end technology to make request and receive response.

Related Posts:
MariaDB – How to use Spring JPA MariaDB | Spring Boot
Vue Router example – with Nav Bar, Dynamic Route & Nested Routes
Reactjs JWT Authentication Example

Continue reading “Vue.js + Spring Boot example | Spring Data JPA + REST + MariaDB CRUD”

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.

Accessibility in Angular example

Accessibility in Angular example

Here’s an example of how to implement accessibility in an Angular application:

1. Use appropriate ARIA roles and attributes: Use ARIA roles and attributes to provide additional information to assistive technologies. For example, use the role=”button” attribute on a button element, and the aria-label attribute to provide a text description of the button’s purpose


2. Provide alternative text for images: Use the alt attribute to provide alternative text for images. This text is read by assistive technologies to describe the image to users who are visually impaired.

Company Logo

3. Use semantic elements: Use semantic elements such as

,

Angular Property binding best practices example code

Angular Property binding best practices example code

Here are some best practices for using property binding in Angular:

1. Use the [property] syntax for property binding: Instead of using the bind-property syntax, use the [property] syntax for property binding. This makes the binding more readable and consistent with other Angular syntax.







2. Use ngIf and ngFor directives to conditionally render elements: Instead of using property binding to conditionally show or hide elements, use the ngIf and ngFor directives. These directives are specifically designed for this purpose and can improve the performance of the application.


Error: {{errorMessage}}
Error: {{errorMessage}}

3. Use one-way binding for read-only properties: Use one-way binding ([property]) for read-only properties and two-way binding ([(ngModel)]) for properties that need to be updated from the template.








4. Use the async pipe for observables: Instead of manually subscribing to observables in the component and updating the view, use the async pipe. The async pipe subscribes to an observable and updates the view automatically.


{{user.name}}
{{user.name}}

5. Use property binding with care: Property binding can be useful, but it can also make the code less readable, harder to debug and cause performance issues.

It’s worth noting that using property binding excessively can lead to tight coupling between the component and the template, which can make it harder to test and maintain the component.

It’s recommended to use property binding judiciously and use other Angular features such as directives, services, and the component lifecycle hooks to manage the component’s state and behavior.

Angular Avoid side effects example code

Here’s an example of how to avoid side effects in an Angular component:

1. Isolate component logic: Instead of directly manipulating the DOM or other components, use the component’s input and output properties to communicate with other parts of the application. This makes the component more isolated and easier to test.

// Good
@Input() user: User;

// Bad
@ViewChild('usernameInput') input: ElementRef;

2. Avoid changing input properties: Input properties should be treated as immutable. Avoid changing the values of input properties within the component. This can cause unexpected behavior and make the component harder to reason about.

// Good
sortUsers(users: User[]) {
  return users.sort((a, b) => a.name.localeCompare(b.name));
}

// Bad
@Input() users: User[];

sortUsers() {
  this.users.sort((a, b) => a.name.localeCompare(b.name));
}

3. Avoid subscriptions in the constructor: It’s a best practice to avoid subscribing to observables in the constructor. Instead, use the ngOnInit lifecycle hook and make sure to unsubscribe in the ngOnDestroy lifecycle hook.

// Good
export class ExampleComponent implements OnInit, OnDestroy {

Angular Return the proper type example code

Here’s an example of how to return the proper type in an Angular service:

1. Use a strongly-typed return type: Use a strongly-typed return type for the service’s methods to ensure that the correct type is returned.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) {}

  getUser(): Observable {
    return this.http.get('/api/user');
  }
}

In this example, the getUser method has a return type of Observable, which ensures that the method returns an observable of the User type.

2. Use Typescript’s type inference: If the return type can be inferred from the implementation, Typescript will automatically infer the return type and you don’t have to explicitly specify it.

@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) {}

  getUser() {
    return this.http.get('/api/user');
  }
}

In this case, the return type of getUser method is Observable inferred by the type of the http.get request

3. Use the as keyword: If you want to cast the return value to a specific type, use the as keyword.

@Injectable({
  provided

Angular Property binding best practices – Passing in a string example

Here’s an example of how to use property binding best practices when passing in a string:

1. Use one-way binding for read-only properties: When passing in a string as a property value, use one-way binding ([property]) if the value is read-only.




2. Use string literals instead of variables: When passing in a string as a property value, it’s best to use string literals instead of variables. This makes the binding more readable and eliminates the need for unnecessary component state.







3. Avoid complex expressions or function calls: When passing in a string as a property value, avoid using complex expressions or function calls. This can make the binding less readable and harder to debug.







4. Use property binding with care: Property binding can be useful, but it can also make the code less readable, harder to debug and cause performance issues. Therefore, it’s recommended to use property binding judiciously, and use other Angular features such as directives, services, and the component lifecycle hooks to manage the component’s state and behavior.

Angular Property binding best practices – Passing in an object example code

Here’s an example of how to use property binding best practices when passing in an object:

1. Use one-way binding for read-only properties: When passing in an object as a property value, use one-way binding ([property]) if the value is read-only.




2. Use object literals instead of variables: When passing in an object as a property value, it’s best to use object literals instead of variables. This makes the binding more readable and eliminates the need for unnecessary component state.







3. Avoid complex expressions or function calls: When passing in an object as a property value, avoid using complex expressions or function calls. This can make the binding less readable and harder to debug.







4. Use property binding with care: Property binding can be useful, but it can also make the code less readable, harder to debug and cause performance issues. Therefore, it’s recommended to use property binding judiciously, and use other Angular features such as directives, services, and the component lifecycle hooks to manage the component’s state and behavior.
By following these best practices, you can ensure that your component’s property bindings are clear, predictable, and easy to maintain.

It’s also worth noting that, when passing complex objects as properties, it’s important to ensure that the objects are immutable, to avoid unexpected behavior and make the component easier to reason about.