moesifawslambda

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 15, 2020 License: Apache-2.0 Imports: 15 Imported by: 1

README

Moesif AWS Lambda Middleware for Go

Built For Software License Source Code

Go Middleware for AWS Lambda that automatically logs API calls and sends to Moesif for API analytics and log analysis.

Designed for APIs that are hosted on AWS Lambda using Amazon API Gateway or Application Load Balancer as a trigger.

How to install

Run the following commands: moesif-aws-lambda-go can be installed like any other Go library through go get:

go get github.com/moesif/moesif-aws-lambda-go

Or, if you are already using Go Modules, specify a version number as well:

go get github.com/moesif/moesif-aws-lambda-go@v1.0.3

How to use

1. Add middleware to your Lambda application.
package main

import (
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-lambda-go/events"
    "context"
    "strings"
    "github.com/aws/aws-lambda-go/events"
	moesifawslambda "github.com/moesif/moesif-aws-lambda-go"
)

func MoesifOptions() map[string]interface{} {
	var moesifOptions = map[string]interface{} {
		"Log_Body": true,
	}
	return moesifOptions
}

func HandleLambdaEvent(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	return events.APIGatewayProxyResponse{
		Body:       request.Body,
		StatusCode: 200,
		Headers: map[string] string {
			"Content-Type":   "application/json",
		},
	   }, nil
}

func main() {
	lambda.Start(moesifawslambda.MoesifLogger(HandleLambdaEvent, MoesifOptions()))
}
2. Set MOESIF_APPLICATION_ID environment variable

Add a new environment variable with the name MOESIF_APPLICATION_ID and the value being your Moesif application id, which can be found in the Moesif Portal. After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the Moesif Portal, click on the top right menu, and then clicking Installation.

Optional: Capturing outgoing API calls

In addition to your own APIs, you can also start capturing calls out to third party services via the following method:

func MoesifOptions() map[string]interface{} {
	var moesifOptions = map[string]interface{} {
		"Application_Id": "Your Moesif Application Id",
		"Log_Body": true,
	}
	return moesifOptions
}

moesifawslambda.StartCaptureOutgoing(MoesifOptions())
moesifOption

(required), map[string]interface{}, are the configuration options for your application. Please find the details below on how to configure options.

Configuration options

Please note that the request and the response parameters in the configuration options are aws-lambda-go APIGatewayProxyRequest and APIGatewayProxyResponse respectively.

Should_Skip

(optional) (request, response) => boolean, a function that takes a request and a response, and returns true if you want to skip this particular event.

Identify_User

(optional, but highly recommended) (request, response) => string, a function that takes a request and response, and returns a string that is the user id used by your system. While Moesif tries to identify users automatically, but different frameworks and your implementation might be very different, it would be helpful and much more accurate to provide this function.

Identify_Company

(optional) (request, response) => string, a function that takes a request and response, and returns a string that is the company id for this event.

Get_Metadata

(optional) (request, response) => dictionary, a function that takes a request and response, and returns a dictionary (must be able to be encoded into JSON). This allows you to associate this event with custom metadata. For example, you may want to save a VM instance_id, a trace_id, or a tenant_id with the request.

Get_Session_Token

(optional) (request, response) => string, a function that takes a request and response, and returns a string that is the session token for this event. Moesif tries to get the session token automatically, but if this doesn't work for your service, you should use this to identify sessions.

Mask_Event_Model

(optional) (EventModel) => EventModel, a function that takes an EventModel and returns an EventModel with desired data removed. The return value must be a valid EventModel required by Moesif data ingestion API. For details regarding EventModel please see the Moesif Golang API Documentation.

Debug

(optional) boolean, a flag to see debugging messages.

Log_Body

(optional) boolean, Default true. Set to false to remove logging request and response body to Moesif.

Options for logging outgoing calls

The options below are applied to outgoing API calls. The request and response objects passed in are Request request and Response response objects.

Should_Skip_Outgoing

(optional) (request, response) => boolean, a function that takes a request and response, and returns true if you want to skip this particular event.

Identify_User_Outgoing

(optional, but highly recommended) (request, response) => string, a function that takes request and response, and returns a string that is the user id used by your system. While Moesif tries to identify users automatically, but different frameworks and your implementation might be very different, it would be helpful and much more accurate to provide this function.

Identify_Company_Outgoing

(optional) (request, response) => string, a function that takes request and response, and returns a string that is the company id for this event.

Get_Metadata_Outgoing

(optional) (request, response) => dictionary, a function that takes request and response, and returns a dictionary (must be able to be encoded into JSON). This allows to associate this event with custom metadata. For example, you may want to save a VM instance_id, a trace_id, or a tenant_id with the request.

Get_Session_Token_Outgoing

(optional) (request, response) => string, a function that takes request and response, and returns a string that is the session token for this event. Again, Moesif tries to get the session token automatically, but if you setup is very different from standard, this function will be very help for tying events together, and help you replay the events.

Mask_Event_Model_Outgoing

(optional) (EventModel) => EventModel, a function that takes an EventModel and returns an EventModel with desired data removed. The return value must be a valid EventModel required by Moesif data ingestion API. For details regarding EventModel please see the Moesif Golang API Documentation.

Log_Body_Outgoing

(optional) boolean, Default true. Set to false to remove logging request and response body to Moesif.

Update User

UpdateUser method

Create or update a user profile in Moesif. The metadata field can be any customer demographic or other info you want to store. Only the UserId field is required. This method is a convenient helper that calls the Moesif API lib. For details, visit the Go API Reference.

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

func literalFieldValue(value string) *string {
    return &value
}

var moesifOptions = map[string]interface{} {
	"Application_Id": "Your Moesif Application Id",
}

// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#users for campaign schema
campaign := models.CampaignModel {
  UtmSource: literalFieldValue("google"),
  UtmMedium: literalFieldValue("cpc"), 
  UtmCampaign: literalFieldValue("adwords"),
  UtmTerm: literalFieldValue("api+tooling"),
  UtmContent: literalFieldValue("landing"),
}
  
// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "email": "john@acmeinc.com",
  "first_name": "John",
  "last_name": "Doe",
  "title": "Software Engineer",
  "sales_info": map[string]interface{}{
      "stage": "Customer",
      "lifetime_value": 24000,
      "account_owner": "mary@contoso.com",
  },
}

// Only UserId is required
user := models.UserModel{
  UserId:  "12345",
  CompanyId:  literalFieldValue("67890"), // If set, associate user with a company object
  Campaign:  &campaign,
  Metadata:  &metadata,
}

// Update User
moesifawslambda.UpdateUser(&user, moesifOption)
UpdateUsersBatch method

Similar to UpdateUser, but used to update a list of users in one batch. Only the UserId field is required. This method is a convenient helper that calls the Moesif API lib. For details, visit the Go API Reference.


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

func literalFieldValue(value string) *string {
    return &value
}

var moesifOptions = map[string]interface{} {
	"Application_Id": "Your Moesif Application Id",
}

// List of Users
var users []*models.UserModel

// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#users for campaign schema
campaign := models.CampaignModel {
  UtmSource: literalFieldValue("google"),
  UtmMedium: literalFieldValue("cpc"), 
  UtmCampaign: literalFieldValue("adwords"),
  UtmTerm: literalFieldValue("api+tooling"),
  UtmContent: literalFieldValue("landing"),
}
  
// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "email": "john@acmeinc.com",
  "first_name": "John",
  "last_name": "Doe",
  "title": "Software Engineer",
  "sales_info": map[string]interface{}{
      "stage": "Customer",
      "lifetime_value": 24000,
      "account_owner": "mary@contoso.com",
  },
}

// Only UserId is required
userA := models.UserModel{
  UserId:  "12345",
  CompanyId:  literalFieldValue("67890"), // If set, associate user with a company object
  Campaign:  &campaign,
  Metadata:  &metadata,
}

users = append(users, &userA)

// Update User
moesifawslambda.UpdateUsersBatch(users, moesifOption)

Update Company

UpdateCompany method

Create or update a company profile in Moesif. The metadata field can be any company demographic or other info you want to store. Only the CompanyId field is required. This method is a convenient helper that calls the Moesif API lib. For details, visit the Go API Reference.

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

func literalFieldValue(value string) *string {
    return &value
}

var moesifOptions = map[string]interface{} {
	"Application_Id": "Your Moesif Application Id",
}

// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
campaign := models.CampaignModel {
  UtmSource: literalFieldValue("google"),
  UtmMedium: literalFieldValue("cpc"), 
  UtmCampaign: literalFieldValue("adwords"),
  UtmTerm: literalFieldValue("api+tooling"),
  UtmContent: literalFieldValue("landing"),
}
  
// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "org_name": "Acme, Inc",
  "plan_name": "Free",
  "deal_stage": "Lead",
  "mrr": 24000,
  "demographics": map[string]interface{}{
      "alexa_ranking": 500000,
      "employee_count": 47,
  },
}

// Prepare company model
company := models.CompanyModel{
	CompanyId:		  "67890",	// The only required field is your company id
	CompanyDomain:  literalFieldValue("acmeinc.com"), // If domain is set, Moesif will enrich your profiles with publicly available info 
	Campaign: 		  &campaign,
	Metadata:		    &metadata,
}

// Update Company
moesifawslambda.UpdateCompany(&company, moesifOption)
UpdateCompaniesBatch method

Similar to UpdateCompany, but used to update a list of companies in one batch. Only the CompanyId field is required. This method is a convenient helper that calls the Moesif API lib. For details, visit the Go API Reference.


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

func literalFieldValue(value string) *string {
    return &value
}

var moesifOptions = map[string]interface{} {
	"Application_Id": "Your Moesif Application Id",
}

// List of Companies
var companies []*models.CompanyModel

// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
campaign := models.CampaignModel {
  UtmSource: literalFieldValue("google"),
  UtmMedium: literalFieldValue("cpc"), 
  UtmCampaign: literalFieldValue("adwords"),
  UtmTerm: literalFieldValue("api+tooling"),
  UtmContent: literalFieldValue("landing"),
}
  
// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "org_name": "Acme, Inc",
  "plan_name": "Free",
  "deal_stage": "Lead",
  "mrr": 24000,
  "demographics": map[string]interface{}{
      "alexa_ranking": 500000,
      "employee_count": 47,
  },
}

// Prepare company model
companyA := models.CompanyModel{
	CompanyId:		  "67890",	// The only required field is your company id
	CompanyDomain:  literalFieldValue("acmeinc.com"), // If domain is set, Moesif will enrich your profiles with publicly available info 
	Campaign: 		  &campaign,
	Metadata:		    &metadata,
}

companies = append(companies, &companyA)

// Update Companies
moesifawslambda.UpdateCompaniesBatch(companies, moesifOption)

Examples

Other integrations

To view more documentation on integration options, please visit the Integration Options Documentation.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ContextKeyRequestStart = &contextKey{"RequestStart"}
View Source
var DefaultTransport = &Transport{
	Transport: http.DefaultTransport,
}

The default logging transport that wraps http.DefaultTransport.

Functions

func StartCaptureOutgoing

func StartCaptureOutgoing(configurationOption map[string]interface{})

Start Capture Outgoing Request

func UpdateCompaniesBatch added in v1.0.2

func UpdateCompaniesBatch(companies []*models.CompanyModel, configurationOption map[string]interface{})

Function to update Users in batch

func UpdateCompaniesBatchAsync added in v1.0.2

func UpdateCompaniesBatchAsync(companies []*models.CompanyModel, configurationOption map[string]interface{})

Update Companies Batch

func UpdateCompany added in v1.0.2

func UpdateCompany(company *models.CompanyModel, configurationOption map[string]interface{})

Function to update User

func UpdateCompanyAsync added in v1.0.2

func UpdateCompanyAsync(company *models.CompanyModel, configurationOption map[string]interface{})

Update Company

func UpdateUser added in v1.0.2

func UpdateUser(user *models.UserModel, configurationOption map[string]interface{})

Function to update User

func UpdateUserAsync added in v1.0.2

func UpdateUserAsync(user *models.UserModel, configurationOption map[string]interface{})

Update User

func UpdateUsersBatch added in v1.0.2

func UpdateUsersBatch(users []*models.UserModel, configurationOption map[string]interface{})

Function to update Users in batch

func UpdateUsersBatchAsync added in v1.0.2

func UpdateUsersBatchAsync(users []*models.UserModel, configurationOption map[string]interface{})

Update Users Batch

Types

type Transport

type Transport struct {
	Transport   http.RoundTripper
	LogRequest  func(req *http.Request)
	LogResponse func(resp *http.Response)
}

Transport implements http.RoundTripper.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(request *http.Request) (*http.Response, error)

RoundTrip is the core part of this module and implements http.RoundTripper.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL