Skip to content

Instantly share code, notes, and snippets.

@vdparikh
Created July 21, 2018 23:07
Show Gist options
  • Select an option

  • Save vdparikh/aac5e68acbd96da3db165d3687c7be2e to your computer and use it in GitHub Desktop.

Select an option

Save vdparikh/aac5e68acbd96da3db165d3687c7be2e to your computer and use it in GitHub Desktop.
Invoke Lambda Function from GO
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
)
type getItemsRequest struct {
SortBy string
SortOrder string
ItemsToGet int
}
type lambdaResponse struct {
StatusCode int64 `json:"StatusCode"`
Payload map[string]interface{} `json:"Payload"`
}
func main() {
// Create Lambda service client
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
client := lambda.New(sess, &aws.Config{Region: aws.String("us-east-1")})
// Get the 10 most recent items
request := getItemsRequest{"time", "descending", 10}
payload, err := json.Marshal(request)
if err != nil {
fmt.Println("Error marshalling InvokeFromGoFunction request")
os.Exit(0)
}
result, err := client.Invoke(&lambda.InvokeInput{FunctionName: aws.String("InvokeFromGoFunction"), Payload: payload})
if err != nil {
fmt.Println("Error calling InvokeFromGoFunction")
os.Exit(0)
}
var resp lambdaResponse
resp.StatusCode = *result.StatusCode
// fmt.Println("Status Code", *result.StatusCode)
// fmt.Println("Payload", string(result.Payload))
err = json.Unmarshal(result.Payload, &resp.Payload)
fmt.Println("Marshaled Response", resp)
if err != nil {
fmt.Println("Error unmarshalling InvokeFromGoFunction response")
os.Exit(0)
}
// If the status code is NOT 200, the call failed
if resp.StatusCode != 200 {
fmt.Println("Error getting items, StatusCode: ", resp.StatusCode)
os.Exit(0)
}
// // If the result is failure, we got an error
// if resp.Body.Result == "failure" {
// fmt.Println("Failed to get items")
// os.Exit(0)
// }
// // Print out items
// if len(resp.Body.Data) > 0 {
// for i := range resp.Body.Data {
// fmt.Println(resp.Body.Data[i].Item)
// }
// } else {
// fmt.Println("There were no items")
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment