scud

package module
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 32 Imported by: 12 modules, 12 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

scud

serverless Golang made simple, secure, and fast


scud (Serverless Configuration & Utilities for Deployment) is a developer-friendly toolkit for building and deploying secure serverless Golang APIs on AWS.

It simplifies the process of compiling Golang serverless functions as an integral part of the AWS CDK workflow. The resulting Lambda functions are directly consumable by both standard and third-party AWS CDK constructs.

SCUD also provides an AWS CDK L3 construct for API Gateway that takes care of the infrastructure boilerplate required for secure serverless RESTful API development.

With SCUD, you can deliver fast, secure, and maintainable serverless APIs without the boilerplate.

Getting started

The latest version of the library is available at its main branch. All development, including new features and bug fixes, take place on the main branch using forking and pull requests as described in contribution guidelines. The stable version is available via Golang modules.

Use go get to retrieve the library and add it as dependency to your application.

go get -u github.com/fogfish/scud

Quick Start

Below is a minimal example of deploying a Golang application to AWS Lambda. The key feature here is that the compilation, packaging, and deployment of the function are fully integrated into the cdk deploy workflow.

package main

import (
  "github.com/aws/aws-cdk-go/awscdk/v2"
  "github.com/aws/jsii-runtime-go"
  "github.com/fogfish/scud"
)

func main() {
  app := awscdk.NewApp(nil)
  stack := awscdk.NewStack(app, jsii.String("example"), nil)

  scud.NewFunctionGo(stack, jsii.String("MyFun"),
    &scud.FunctionGoProps{
      SourceCodeModule: "github.com/fogfish/scud",
      SourceCodeLambda: "examples/01_simple_function/lambda",
    },
  )

  app.Synth(nil)
}

Golang Serverless

AWS CDK has a bundling feature that simplify the process of creating assets for Lambda functions from source code. This feature is useful for compiling and packaging Golang executable binaries into AWS Lambda assets. scud implements L3 construct to bundle Golang source code into ARM64 lambdas for Amazon Linux 2 requiring no effort that running cdk deploy.

scud.NewFunctionGo(stack, jsii.String("Handler"),
  &scud.FunctionGoProps{
    // Golang module that containing the function
    SourceCodeModule: "github.com/fogfish/scud",
    // Path to lambda function within the module 
    SourceCodeLambda:  "test/lambda/go",
    // Lambda properties
    FunctionProps: &awslambda.FunctionProps{},
  },
)

The benefit of using this L3 construct is its optimized deployment strategy, designed for monorepos that contain many Lambda functions. It automatically detects changes in the source code and deploys only the Lambda functions that have been modified, instead of redeploying everything. This makes deployments faster and more efficient, especially in large projects.

Linker Flags and Version Injection

You can inject custom variables and version information into your Go Lambda binary using the GoVar and SourceCodeVersion properties. These are passed as -ldflags to the Go compiler.

scud.NewFunctionGo(stack, jsii.String("Handler"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
    SourceCodeVersion: "v1.2.3", // Injects -X main.version=v1.2.3
    Toolchain: &scud.Toolchain{
      LDVars:: map[string]string{
        "main.buildTime": "2024-01-01",  // Injects -X main.buildTime=2024-01-01
        "main.commit":    "abc123",      // Injects -X main.commit=abc123
      },
    },
  },
)

This allows you to access version and build information in your Lambda function:

package main

var (
    version   = "dev"
    buildTime = "unknown" 
    commit    = "unknown"
)

func main() {
    log.Printf("Version: %s, Build: %s, Commit: %s", version, buildTime, commit)
    // ... rest of your Lambda code
}

Lambda Environment Variables

Use awslambda.Function and its AddEnvironment method to set runtime environment variables for your Lambda function:

f := scud.NewFunctionGo(stack, jsii.String("Handler"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
  }
)

// Set environment variables for the Lambda function
f.AddEnvironment(jsii.String("DATABASE_URL"), jsii.String("postgresql://..."), nil)
f.AddEnvironment(jsii.String("LOG_LEVEL"), jsii.String("debug"), nil)

Architecture: Graviton vs x86_64

Graviton (ARM64) is default architecture for lambda function supported by the library. Use standard Golang environment variable "GOARCH" to change the default architecture. Pass environment variable using GoEnv property:

scud.NewFunctionGo(scope, jsii.String("test"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda:  "test/lambda/go",
    Toolchain: &scud.Toolchain{
      GoEnv: map[string]string{"GOARCH": "amd64"},
    },
  },
)

CGO / C Libraries

CGO is disabled by default. Use standard Golang environment variable "CGO_ENABLED" to enable.

scud.NewFunctionGo(scope, jsii.String("test"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda:  "test/lambda/go",
    Toolchain: &scud.Toolchain{
      GoEnv: map[string]string{"CGO_ENABLED": "1"},
    },
  },
)

When developing on macOS, building Go binaries that depend on CGO or C libraries may fail or produce incompatible artifacts. Use a Linux cross-compiler (e.g. musl toolchain).

brew install FiloSottile/musl-cross/musl-cross
scud.NewFunctionGo(scope, jsii.String("test"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda:  "test/lambda/go",
    Toolchain: &scud.Toolchain{
      GoEnv: map[string]string{
        "CGO_ENABLED": "1",
        "CC":          "aarch64-linux-musl-gcc",
      },
      LDVars: []string{"-linkmode external", `-extldflags "-static"`},
    },
  },
)

Known limitations

  • Some C libraries cannot be statically linked
  • Libraries that require glibc may not build correctly on macOS
  • In such cases, builds must be performed on a Linux system

Container images

By default, Lambda functions are distributed as ZIP files. The library also supports building and deploying Lambda functions from containers. The provided L3 construct reduces the boilerplate required to define and build such containers, offering a simpler interface compared to the standard AWS CDK DockerImageCode.fromImageAsset. It allows you to easily package your executable, include static assets, and install any required packages.

The resulting container is based on either scratch if your code is pure Golang, or Linux Alpine if additional system packages are specified.

scud.NewContainerGo(stack, jsii.String("test"),
  &scud.ContainerGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
    StaticAssets: []string{
      // list of files to be include into container
      // path is relative to SourceCodeModule
      // For example 
      "test/lambda/go/main.go"
    },
    Packages: []string{
      // Additional Linux packages to install
      "zip", "curl",
    },
  },
)

Universal Function

For dynamic function creation, you can use the universal NewFunction constructor that accepts either FunctionGoProps or ContainerGoProps:

// Works with FunctionGoProps
func1 := scud.NewFunction(stack, jsii.String("func1"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
  },
)

// Works with ContainerGoProps  
func2 := scud.NewFunction(stack, jsii.String("func2"),
  &scud.ContainerGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
  },
)

Custom Go Environment

You can set additional Go environment variables for the build process using the GoEnv property. The library sets sensible defaults, but you can override them:

scud.NewFunctionGo(stack, jsii.String("Handler"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
    GoEnv: map[string]string{
      "GOARCH":      "amd64",           // Override architecture
      "CGO_ENABLED": "1",               // Enable CGO if needed
      "GOCACHE":     "/tmp/go-build",   // Custom build cache
    },
  },
)

Default environment variables set by the library:

  • GOOS=linux
  • GOARCH=arm64
  • CGO_ENABLED=0

The compiler inherits the environment of the process (HOME, GOCACHE, GOPROXY, GOPRIVATE, GOFLAGS, etc), the variables above and GoEnv override it. The build cache is the user's default one (go env GOCACHE) unless GOCACHE is defined.

Packages are built by import path in module mode (go build github.com/fogfish/scud/test/lambda/go), the module may be checked out anywhere, $GOPATH/src is not required. The module must be the main module of the CDK application or its dependency.

Change Detection

The asset hash of a function is computed by go list -deps using the same build environment as the compiler. It covers:

  • the content of every source file (Go, Cgo, assembly, embedded files) of every package the function depends on that belongs to the main module or a module replaced by a local directory (replace directive);
  • the path and version of every other module the function depends on (upgrading a library redeploys the function);
  • the Go toolchain version (go env GOVERSION);
  • the build configuration: GoEnv (except machine-local variables such as GOCACHE or GOPROXY), linker flags and variables, SCUD_COMPRESS_UPX.

File names are hashed relative to the package import path, so the hash is the same on a laptop and in CI. Files not used by the build (tests, docs, other packages) do not change the hash.

Function Defaults

The library's defaults are 1 minute timeout and a per-function log group named after the function, with 5 days retention, destroyed with the stack. Define defaults once per scope (application, stack or any construct); the defaults of the nearest ancestor apply, properties given to a function explicitly take precedence.

scud.SetDefaults(stack, &scud.Defaults{
  // Functions behind API Gateway HTTP API need timeout under
  // the integration's limit (30 seconds).
  Timeout:        awscdk.Duration_Seconds(jsii.Number(25)),
  MemorySize:     jsii.Number(256),
  // per-function log groups named <prefix>/<function name>
  LogGroupPrefix: "/myapp/mystack",
  LogRetention:   awslogs.RetentionDays_ONE_MONTH,
  // alternatively, single log group shared by all functions
  // LogGroup: awslogs.NewLogGroup(/* ... */),
})

The default function name is <stack name>-<shortened path of the function>. AWS Lambda limits function names to 64 characters, the synthesis fails if the name is longer; set FunctionName explicitly or shorten the stack name.

Tenant Isolation

AWS Lambda tenant isolation mode is configured through standard function properties:

scud.NewFunctionGo(stack, jsii.String("Handler"),
  &scud.FunctionGoProps{
    SourceCodeModule: "github.com/fogfish/scud",
    SourceCodeLambda: "test/lambda/go",
    FunctionProps: &awslambda.FunctionProps{
      TenancyConfig: awslambda.TenancyConfig_PER_TENANT(),
    },
  },
)

Logging

The L3 construct automatically creates a log group if one is not specified. It is recommended to define a single log group per application and reuse it across all Lambda functions.

For example, you could use a single log group to store logs for all of the Lambda functions that make up a particular application.

Compressing binaries

The L3 constuct uses the -s and -w linker flags by default to strip the debugging information from binaries. If you have UPX installed, you can enable binary compression by setting the SCUD_COMPRESS_UPX=1 environment variable before deploying the application. This can significantly reduce the size (almost 7x smaller) of your Lambda deployment package:

export SCUD_COMPRESS_UPX=1
cdk synth

The compression uses UPX with the --best --lzma flags for maximum compression. See more about compressions:

API Gateway

AWS API Gateway and AWS Lambda are a perfect approach for quick prototyping or production development of microservices on Amazon Web Services. Unfortunately, it requires a significant amount of boilerplate AWS CDK code to bootstrap the development. The scud library implements high-order components on top of AWS CDK that harden the API pattern including built-in validation of OAuth2 Bearer tokens for each API endpoint, supporting various identity providers such as IAM, JWT tokens, and AWS Cognito.

RESTful API Pattern

Quick Start

package main

import (
  "github.com/aws/aws-cdk-go/awscdk/v2"
  "github.com/aws/aws-cdk-go/awscdk/v2/awsapigatewayv2"
  "github.com/aws/jsii-runtime-go"
  "github.com/fogfish/scud"
)

func main() {
  app := awscdk.NewApp(nil)
  stack := awscdk.NewStack(app, jsii.String("example-api"), nil)

  // API Gateway
  api := scud.NewGateway(stack, jsii.String("Gateway"), &scud.GatewayProps{})

  // Handler Function
  fun := scud.NewFunctionGo(stack, jsii.String("Handler"),
    &scud.FunctionGoProps{
      SourceCodeModule: "github.com/fogfish/scud",
      SourceCodeLambda:  "test/lambda/go",
    },
  )

  // Example endpoint
  api.NewAuthorizerPublic().
    AddResource("/example", fun)

  app.Synth(nil)
}

API Gateway

The library defined presets for AWS API Gateway V2 (HTTP API).

scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{}
)

The gateway has a single auto-deployed $default stage, the API is served at the root of the custom domain and of the execute-api endpoint.

Breaking change: versions up to v0.13.x created an additional stage api, which served the API at https://{uid}.execute-api.{region}.amazonaws.com/api/.... The stage is removed, use the $default stage endpoint.

Use gw.CfnStage() to configure stage settings not covered by the library.

API Gateway (Domain Name)

The library deploy gateway using default AWS host naming convention https://{uid}.execute-api.{region}.amazonaws.com. Supply custom domain name and Certificate ARN for custom naming.

scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{
    Host: jsii.String("test.example.com"),
    TlsArn: jsii.String("arn:aws:acm:eu-west-1:000000000000:certificate/00000000-0000-0000-0000-000000000000"),
  },
)

The hosted zone of the record is the host without its first label (e.g. api.example.com for v1.api.example.com). Use Zone to define it explicitly. Use ApiIdParameter to export the API id into SSM parameter (see stable alias).

scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{
    Host:           jsii.String("v1.api.example.com"),
    Zone:           jsii.String("api.example.com"),
    TlsArn:         jsii.String("arn:aws:acm:..."),
    ApiIdParameter: jsii.String("/example/v1/api"),
  },
)

Zone is resolved with Route 53 lookup at synthesis (HostedZone_FromLookup), it requires AWS credentials or cdk.context.json. Use HostedZone to pass the zone by attributes instead, no lookup is made. It takes precedence over Zone, the same option exists at AliasProps.

zone := awsroute53.HostedZone_FromHostedZoneAttributes(stack, jsii.String("Zone"),
  &awsroute53.HostedZoneAttributes{
    HostedZoneId: jsii.String("Z0000000000000"),
    ZoneName:     jsii.String("api.example.com"),
  },
)

scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{
    Host:       jsii.String("v1.api.example.com"),
    HostedZone: zone,
    TlsArn:     jsii.String("arn:aws:acm:..."),
  },
)

API Gateway (Resources)

Each authorizer implements the AddResource function to associate a Lambda function with a REST API path. It uses the specified path as a prefix, enabling the association of the Lambda function with all subpaths under that prefix (endpoint and endpoint/{any+}).

gateway.NewAuthorizerPublic().
  AddResource("/example", handler)

API Gateway (Routes)

Each authorizer implements the AddRoute function to associate a Lambda function with the exact route. The path may contain path parameters (/{instance}/facts), greedy path parameter (/files/{proxy+}) or be the root /. Use methods to split read and write operations of one path between functions.

gateway.NewAuthorizerPublic().
  AddRoute("/{instance}/facts", &scud.RouteProps{
    Handler: read,
    Methods: []apigw2.HttpMethod{apigw2.HttpMethod_GET},
  }).
  AddRoute("/{instance}/facts", &scud.RouteProps{
    Handler:  write,
    Methods:  []apigw2.HttpMethod{apigw2.HttpMethod_PUT, apigw2.HttpMethod_DELETE},
    Id:       "WriteFacts", // optional construct id
    Throttle: &scud.Throttle{RateLimit: 10, BurstLimit: 5},
  })

The default methods are all methods except OPTIONS when CORS is enabled (preflight is answered by API Gateway), otherwise ANY. The default construct id of the route is derived from method and the whole path. A single integration per function (and payload format) is shared by all its routes. RouteProps.AuthorizationScopes applies to JWT and Cognito authorizers, RouteProps.Grantee to IAM authorizer.

Payload Format

The payload format of Lambda integration is 1.0 by default, set RouteProps.PayloadFormatVersion to use 2.0.

Version Handler event (aws-lambda-go/events) Context of Lambda authorizer
1.0 APIGatewayProxyRequest RequestContext.Authorizer
2.0 APIGatewayV2HTTPRequest RequestContext.Authorizer.Lambda

AddResource always uses 1.0. The payload format of Lambda authorizer depends on its response type: SIMPLE uses 2.0 (APIGatewayV2CustomAuthorizerV2Request → APIGatewayV2CustomAuthorizerSimpleResponse), IAM uses 1.0 (APIGatewayV2CustomAuthorizerV1Request → APIGatewayCustomAuthorizerResponse).

Authorizer IAM

The library supports integration with AWS IAM to authorize incoming requests. This integration ensures that only authenticated and authorized principals can access the resources and functionalities provided by your Lambda functions. By leveraging AWS IAM policies and roles, the library enforces fine-grained access control, enhancing the security of your API endpoints.

api := scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{}
)

// Using the IAM authorizer requires specifying a principal or role. 
role := awsiam.NewRole(/* ... */)

api.NewAuthorizerIAM().
  AddResource("/example", handler, role)

You can still access API with curl even with IAM authorizer is used.

curl https://example.com/petshop/pets \
  -XGET \
  -H "Accept: application/json" \
  -H "x-amz-security-token: $AWS_SESSION_TOKEN" \
  --aws-sigv4 "aws:amz:eu-west-1:execute-api" \
  --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY"

Authorizer AWS Cognito

The library supports integration with AWS Cognito to authorize incoming requests. This integration allows you to manage user authentication and authorization seamlessly. By utilizing AWS Cognito, you can implement robust user sign-up, sign-in, and access control mechanisms. The library ensures that only authenticated users with valid tokens can access your API endpoints, providing an additional layer of security and user management capabilities. The integration of AWS API Gateway and AWS Cognito is well documented in the official documentation. This pattern facilitates the deployment of this configuration by simply providing the ARN of the user pool and specifying scopes to protect your endpoints.

api := scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{}
)

// Cognito pool has to be pre-defined.
// Supply list of allowed clients to control the access.
api.NewAuthorizerCognito("arn:aws:cognito-idp:...", /* ... */).
  AddResource("/example", handler, "my/scope")

Authorizer JWT

The library supports integration with Single Sign On provider (e.g. Auth0) to authorize incoming requests using JWT tokens. This integration allows you to leverage external identity providers for user authentication, ensuring secure and seamless access to your API endpoints. By validating JWT tokens issued by the SSO provider, the library ensures that only authenticated users can access your resources. Additionally, this setup can support various SSO standards and providers, enhancing flexibility and security in managing user identities and permissions.

api := scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{}
)

api.NewAuthorizerJwt("https://{tenant}.eu.auth0.com/", "https://example.com").
  AddResource("/example", handler, "my/scope")

Authorizer Lambda

Bring your own Lambda (REQUEST) authorizer. By default, the authorizer has no identity source, API Gateway invokes it for every request, including anonymous ones, caching is disabled (API Gateway requires zero TTL without identity source) and it uses simple responses.

auth := scud.NewFunctionGo(stack, jsii.String("Auth"), /* ... */)

gw.NewAuthorizerLambda(auth, &scud.AuthorizerLambdaProps{
  // optional, all defaults are shown
  IdentitySource:  nil,
  ResponseTypes:   []authorizers.HttpLambdaResponseType{authorizers.HttpLambdaResponseType_SIMPLE},
  ResultsCacheTtl: awscdk.Duration_Seconds(jsii.Number(0)),
}).
  AddRoute("/{instance}", &scud.RouteProps{Handler: handler})

Use package github.com/fogfish/scud/authorizer to implement the function:

import "github.com/fogfish/scud/authorizer"

func main() {
  lambda.Start(
    func(req authorizer.Request) (authorizer.Response, error) {
      key, ok := authorizer.Bearer(req)
      if !ok {
        return authorizer.Deny(), nil // 403
      }
      // ...
      return authorizer.Allow(map[string]any{"sub": "..."}), nil
    },
  )
}

Return Deny() with nil error to refuse the request, API Gateway answers an error with 500.

Any number of authorizers of any kind can be attached to one gateway. The construct ids are derived uniquely, the first instance of each kind keeps ids of previous versions. Set AuthorizerLambdaProps.Id to control the id of Lambda authorizer.

Stage: Throttling and Access Logs

scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{
    // throttling of all routes, use {0, 0} as a kill switch
    Throttle: &scud.Throttle{RateLimit: 100, BurstLimit: 50},
    // access logs in JSON format (scud.DefaultAccessLogFormat)
    // into new log group, or define LogGroup and Format
    AccessLog: &scud.AccessLog{},
  },
)

Route specific throttling is defined by RouteProps.Throttle.

CORS

AllowOrigins enables CORS for the origin with default headers (Authorization, Content-Type). Use Cors for full control (or HttpApiProps.CorsPreflight):

scud.NewGateway(stack, jsii.String("Gateway"),
  &scud.GatewayProps{
    Cors: &scud.Cors{
      AllowOrigins:  []string{"https://example.com"},
      AllowHeaders:  []string{"Authorization", "Content-Type", "Mcp-Session-Id", "Mcp-Protocol-Version"},
      ExposeHeaders: []string{"Mcp-Session-Id"},
    },
  },
)

Stable Alias of Versioned API

A version of API is an immutable deployment with its own host (v1.api.example.com), a stable host (api.example.com) follows the live version. API Gateway custom domain answers only to its own name, so the alias is a custom domain of its own with an API mapping to the version's API, owned by a stack that outlives versions. Switching the version updates the API mapping in place.

// versioned stack
scud.NewGateway(v1, jsii.String("Gateway"),
  &scud.GatewayProps{
    Host:           jsii.String("v1.api.example.com"),
    TlsArn:         jsii.String("arn:aws:acm:..."),
    ApiIdParameter: jsii.String("/example/v1/api"),
  },
)

// alias stack, the record is created at the zone apex by default
scud.NewAlias(alias, jsii.String("Alias"),
  &scud.AliasProps{
    Host:           jsii.String("api.example.com"),
    TlsArn:         jsii.String("arn:aws:acm:..."),
    ApiIdParameter: jsii.String("/example/v1/api"), // or ApiId, Api
  },
)

HowTo Contribute

The project is MIT licensed and accepts contributions via GitHub pull requests:

  1. Fork it and clone
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request
git clone https://github.com/fogfish/scud
cd scud

go build
go test

License

See LICENSE

References

  1. Migrating AWS Lambda functions from the Go1.x runtime to the custom runtime on Amazon Linux 2

Documentation

Index

Constants

View Source
const DefaultAccessLogFormat = `` /* 483-byte string literal not displayed */

DefaultAccessLogFormat is the JSON access log format used by default.

Variables

This section is empty.

Functions

func AssetCodeGo

func AssetCodeGo(compiler Compiler) awslambda.Code

AssetCodeGo bundles lambda function from source code

func NewContainerGo added in v0.8.4

func NewContainerGo(scope constructs.Construct, id *string, spec *ContainerGoProps) awslambda.Function

func NewFunction added in v0.10.1

func NewFunction(scope constructs.Construct, id *string, spec FunctionProps) awslambda.Function

func NewFunctionGo

func NewFunctionGo(scope constructs.Construct, id *string, spec *FunctionGoProps) awslambda.Function

NewFunctionGo creates Golang Lambda Function from "inline" code

func SetDefaults added in v0.14.0

func SetDefaults(scope constructs.Construct, defaults *Defaults)

SetDefaults defines defaults of functions created within the scope (stack or any construct) and its descendants. The defaults set on the nearest ancestor apply. The function can be called once per scope.

Types

type AccessLog added in v0.14.0

type AccessLog struct {
	// Log group to write access logs, created if not defined.
	// The retention of created log group follows scud.Defaults.
	LogGroup awslogs.ILogGroup

	// Log format, default is DefaultAccessLogFormat.
	Format *string
}

Access logging of the API

type Alias added in v0.14.0

type Alias struct {
	constructs.Construct
	Domain  apigw2.DomainName
	Mapping apigw2.ApiMapping
	Record  awsroute53.ARecord
}

Alias is a stable custom domain name mapped to HTTP API.

A version of API is an immutable deployment with its own host (e.g. v1.api.example.com). The alias (e.g. api.example.com) follows the live version. API Gateway custom domain answers only to its own name, so the alias is a custom domain of its own with an API mapping to the version's API. Deploy the alias by a stack that outlives versions, switching the version updates the API mapping in place.

func NewAlias added in v0.14.0

func NewAlias(scope constructs.Construct, id *string, props *AliasProps) *Alias

type AliasProps added in v0.14.0

type AliasProps struct {
	// Custom domain name of the alias (e.g. api.example.com)
	Host *string

	// Hosted zone (domain name) where the record is created.
	// Default is Host, the record is created at the zone apex.
	// The zone is resolved with Route 53 lookup at synthesis,
	// use HostedZone to avoid the lookup.
	Zone *string

	// Hosted zone where the record is created (e.g. HostedZone_FromHostedZoneAttributes).
	// It takes precedence over Zone, no lookup is made at synthesis.
	HostedZone awsroute53.IHostedZone

	// ARN of the certificate for the custom domain name.
	TlsArn *string

	// HTTP API the alias is mapped to. Use either Api, ApiId or ApiIdParameter.
	Api apigw2.IHttpApi

	// Id of HTTP API the alias is mapped to (e.g. stack output of the version).
	ApiId *string

	// Name of SSM parameter holding id of HTTP API the alias is mapped to
	// (see GatewayProps.ApiIdParameter).
	ApiIdParameter *string

	// Stage of the API, default is $default.
	Stage *string
}

AliasProps defines a stable custom domain mapped to a (versioned) HTTP API deployed by another stack.

type AuthorizerBasic added in v0.11.3

type AuthorizerBasic struct {
	RestAPI apigw2.HttpApi
	// contains filtered or unexported fields
}

func (*AuthorizerBasic) AddResource added in v0.11.3

func (api *AuthorizerBasic) AddResource(
	endpoint string,
	handler awslambda.Function,
) *AuthorizerBasic

Associate a Lambda function with a REST API path. It uses the specified path as a prefix, enabling the association of the Lambda function with all subpaths under that prefix.

func (*AuthorizerBasic) AddRoute added in v0.14.0

func (api *AuthorizerBasic) AddRoute(path string, props *RouteProps) *AuthorizerBasic

Associate a Lambda function with the exact route path (see RouteProps).

type AuthorizerIAM added in v0.8.0

type AuthorizerIAM struct {
	constructs.Construct
	RestAPI apigw2.HttpApi
	// contains filtered or unexported fields
}

func (*AuthorizerIAM) AddResource added in v0.8.0

func (api *AuthorizerIAM) AddResource(
	endpoint string,
	handler awslambda.Function,
	grantee awsiam.IGrantable,
) *AuthorizerIAM

Associate a Lambda function with a REST API path. It uses the specified path as a prefix, enabling the association of the Lambda function with all subpaths under that prefix.

Protect access to resource only for AWS IAM principals.

func (*AuthorizerIAM) AddRoute added in v0.14.0

func (api *AuthorizerIAM) AddRoute(path string, props *RouteProps) *AuthorizerIAM

Associate a Lambda function with the exact route path (see RouteProps). RouteProps.Grantee is granted to invoke the route.

type AuthorizerJwt added in v0.8.0

type AuthorizerJwt struct {
	constructs.Construct
	RestAPI apigw2.HttpApi
	// contains filtered or unexported fields
}

func (*AuthorizerJwt) AddResource added in v0.8.0

func (api *AuthorizerJwt) AddResource(
	endpoint string,
	handler awslambda.Function,
	accessScope ...string,
) *AuthorizerJwt

Associate a Lambda function with a REST API path. It uses the specified path as a prefix, enabling the association of the Lambda function with all subpaths under that prefix.

Protect access to resource only for principals with valid JWT token.

func (*AuthorizerJwt) AddRoute added in v0.14.0

func (api *AuthorizerJwt) AddRoute(path string, props *RouteProps) *AuthorizerJwt

Associate a Lambda function with the exact route path (see RouteProps). RouteProps.AuthorizationScopes are required from the token.

type AuthorizerLambda added in v0.14.0

type AuthorizerLambda struct {
	RestAPI apigw2.HttpApi
	// contains filtered or unexported fields
}

func (*AuthorizerLambda) AddResource added in v0.14.0

func (api *AuthorizerLambda) AddResource(
	endpoint string,
	handler awslambda.Function,
) *AuthorizerLambda

Associate a Lambda function with a REST API path. It uses the specified path as a prefix, enabling the association of the Lambda function with all subpaths under that prefix.

func (*AuthorizerLambda) AddRoute added in v0.14.0

func (api *AuthorizerLambda) AddRoute(path string, props *RouteProps) *AuthorizerLambda

Associate a Lambda function with the exact route path (see RouteProps).

type AuthorizerLambdaProps added in v0.14.0

type AuthorizerLambdaProps struct {
	// Construct id of the authorizer, it is also the default name of
	// the authorizer. Default is derived from the function's construct id.
	Id string

	// Name of the authorizer, default is Id.
	AuthorizerName *string

	// Identity sources (e.g. "$request.header.Authorization").
	// Empty (default) means no identity source: API Gateway invokes
	// the authorizer for every request, including anonymous ones.
	// API Gateway requires disabled caching (zero ResultsCacheTtl)
	// for authorizers without identity source.
	IdentitySource []string

	// Response types of the authorizer, default is SIMPLE.
	// SIMPLE responses use authorizer payload format 2.0, IAM uses 1.0.
	ResponseTypes []authorizers.HttpLambdaResponseType

	// How long API Gateway caches authorizer results, default 0 (disabled).
	ResultsCacheTtl awscdk.Duration
}

Properties of Lambda authorizer

type AuthorizerPublic added in v0.11.3

type AuthorizerPublic struct {
	RestAPI apigw2.HttpApi
	// contains filtered or unexported fields
}

func (*AuthorizerPublic) AddResource added in v0.11.3

func (api *AuthorizerPublic) AddResource(
	endpoint string,
	handler awslambda.Function,
) *AuthorizerPublic

Associate a Lambda function with a REST API path. It uses the specified path as a prefix, enabling the association of the Lambda function with all subpaths under that prefix.

func (*AuthorizerPublic) AddRoute added in v0.14.0

func (api *AuthorizerPublic) AddRoute(path string, props *RouteProps) *AuthorizerPublic

Associate a Lambda function with the exact route path (see RouteProps). The route is public even if the HTTP API has default authorizer.

type Compiler added in v0.6.0

type Compiler interface {
	awscdk.ILocalBundling
	SourceCodeModule() string
	SourceCodeLambda() string
	SourceCodeVersion() string
}

type ContainerGoProps added in v0.8.4

type ContainerGoProps struct {
	*awslambda.DockerImageFunctionProps

	// Canonical name of Golang module that containing the function
	//	SourceCodeModule: "github.com/fogfish/scud",
	SourceCodeModule string

	// Path to lambda function relative to the module
	//	SourceCodeLambda:  "test/lambda/go"
	SourceCodeLambda string

	// The version of software asset passed as linker flag
	//	-ldflags '-X main.version=...'
	SourceCodeVersion string

	// Toolchain configuration for building Go Lambda function
	Toolchain *Toolchain

	// Path to Dockerfile relative to the module,
	// if not specified, the default Dockerfile will be generated.
	//
	// The file must contain:
	// ADD bootstrap /bin/bootstrap
	// CMD ["/bin/bootstrap"]
	Dockerfile string

	// Static files included into container, the path is relative to module
	// Only added to container if Dockerfile is not specified, otherwise it's caller responsibility to add them into container within Dockerfile
	StaticAssets []string

	// Linux Alpine Packages (apk) to be installed within the container
	// Only added to container if Dockerfile is not specified, otherwise it's caller responsibility to add them into container within Dockerfile
	Packages []string
}

func (*ContainerGoProps) HKT1 added in v0.10.7

func (*ContainerGoProps) UniqueID added in v0.10.4

func (props *ContainerGoProps) UniqueID() string

type Cors added in v0.14.0

type Cors struct {
	// Origins allowed to access the API
	AllowOrigins []string

	// Headers allowed in the request, default is Authorization, Content-Type
	AllowHeaders []string

	// Headers exposed to browser in the response
	ExposeHeaders []string

	// Allow credentials (cookies, authorization headers) in cross-origin requests
	AllowCredentials bool

	// For how long browser caches the preflight response, default is 10 minutes
	MaxAge awscdk.Duration
}

CORS configuration of the HTTP API

type Defaults added in v0.14.0

type Defaults struct {
	// Function timeout, the library's default is 1 minute.
	Timeout awscdk.Duration

	// Function memory size (MB), the AWS Lambda's default is 128 MB.
	MemorySize *float64

	// Log group shared by all functions in the scope.
	// When defined, per-function log groups are not created.
	LogGroup awslogs.ILogGroup

	// Prefix of per-function log group names, e.g. "/myapp/mystack".
	// The log group is named <prefix>/<function name>.
	// The library's default is the function name.
	LogGroupPrefix string

	// Retention of per-function log groups, the library's default is 5 days.
	LogRetention awslogs.RetentionDays

	// Removal policy of per-function log groups, the library's default is DESTROY.
	LogRemovalPolicy awscdk.RemovalPolicy
}

Defaults of functions (and log groups) created by the library within a scope. Properties given explicitly to the function take precedence.

Functions behind API Gateway HTTP API must have the timeout shorter than the integration timeout (30 seconds by default, maximum).

type FunctionGoProps

type FunctionGoProps struct {
	*awslambda.FunctionProps

	// Canonical name of Golang module that containing the function
	//	SourceCodeModule: "github.com/fogfish/scud",
	SourceCodeModule string

	// Path to lambda function relative to the module
	//	SourceCodeLambda:  "test/lambda/go"
	SourceCodeLambda string

	// The version of software asset passed as linker flag
	//	-ldflags '-X main.version=...'
	SourceCodeVersion string

	// Toolchain configuration for building Go Lambda function
	Toolchain *Toolchain
}

FunctionGoProps is properties of the function

func (*FunctionGoProps) HKT1 added in v0.10.7

func (*FunctionGoProps) UniqueID added in v0.10.4

func (props *FunctionGoProps) UniqueID() string

type FunctionProps added in v0.10.1

type FunctionProps interface {
	HKT1(awslambda.Function)
	UniqueID() string
}

type Gateway

type Gateway struct {
	constructs.Construct
	RestAPI apigw2.HttpApi

	// Custom domain name, nil if not configured
	Domain apigw2.DomainName

	// DNS record of the custom domain name, nil if not configured
	Record awsroute53.ARecord
	// contains filtered or unexported fields
}

func NewGateway

func NewGateway(scope constructs.Construct, id *string, props *GatewayProps) *Gateway

NewGateway creates new instance of Gateway

func (*Gateway) ApiId added in v0.14.0

func (gw *Gateway) ApiId() *string

ApiId of the HTTP API

func (*Gateway) CfnStage added in v0.14.0

func (gw *Gateway) CfnStage() apigw2.CfnStage

L1 construct of the default stage, use it to configure stage settings not covered by the library.

func (*Gateway) NewAuthorizerBasic added in v0.11.3

func (gw *Gateway) NewAuthorizerBasic(access, secret string, source ...string) *AuthorizerBasic

Creates integration with Basic Authorizer to authorize incoming requests. This integration implements a simple access/secret key validation mechanism, allowing you to protect your API endpoints using basic authentication. By validating the provided credentials against the configured access and secret keys, the library ensures that only authorized clients can access your resources, enhancing the security of your API.

func (*Gateway) NewAuthorizerCognito added in v0.8.0

func (gw *Gateway) NewAuthorizerCognito(cognitoArn string, clients ...string) *AuthorizerJwt

Creates integration with AWS Cognito to authorize incoming requests. This integration allows you to manage user authentication and authorization seamlessly. By utilizing AWS Cognito, you can implement robust user sign-up, sign-in, and access control mechanisms. The library ensures that only authenticated users with valid tokens can access your API endpoints, providing an additional layer of security and user management capabilities.

func (*Gateway) NewAuthorizerIAM added in v0.8.0

func (gw *Gateway) NewAuthorizerIAM() *AuthorizerIAM

Creates integration with AWS IAM to authorize incoming requests. This integration ensures that only authenticated and authorized principals can access the resources and functionalities provided by your Lambda functions. By leveraging AWS IAM policies and roles, the library enforces fine-grained access control, enhancing the security of your API endpoints.

func (*Gateway) NewAuthorizerJwt added in v0.8.0

func (gw *Gateway) NewAuthorizerJwt(iss string, aud ...string) *AuthorizerJwt

Creates integration with Single Sign On provider (e.g. Auth0) to authorize incoming requests using JWT tokens. This integration allows you to leverage external identity providers for user authentication, ensuring secure and seamless access to your API endpoints. By validating JWT tokens issued by the SSO provider, the library ensures that only authenticated users can access your resources. Additionally, this setup can support various SSO standards and providers, enhancing flexibility and security in managing user identities and permissions.

func (*Gateway) NewAuthorizerLambda added in v0.14.0

func (gw *Gateway) NewAuthorizerLambda(handler awslambda.IFunction, props *AuthorizerLambdaProps) *AuthorizerLambda

Creates integration with own Lambda (REQUEST) authorizer. Use package github.com/fogfish/scud/authorizer to implement the function.

func (*Gateway) NewAuthorizerPublic added in v0.11.3

func (gw *Gateway) NewAuthorizerPublic() *AuthorizerPublic

Creates public (unprotected) integration to authorize incoming requests. This integration allows unrestricted access to the associated API endpoints, enabling any client to interact with the resources and functionalities provided by your Lambda functions without requiring authentication or authorization. It is suitable for scenarios where open access is desired, such as public APIs or endpoints that do not handle sensitive data.

type GatewayProps added in v0.7.0

type GatewayProps struct {
	*apigw2.HttpApiProps

	// Custom domain name of the API (e.g. v1.api.example.com), requires TlsArn.
	Host *string

	// ARN of the certificate for the custom domain name.
	TlsArn *string

	// Hosted zone (domain name) where the custom domain record is created.
	// Default is the Host without its first label
	// (e.g. api.example.com for v1.api.example.com).
	// The zone is resolved with Route 53 lookup at synthesis,
	// use HostedZone to avoid the lookup.
	Zone *string

	// Hosted zone where the custom domain record is created
	// (e.g. HostedZone_FromHostedZoneAttributes). It takes precedence over Zone,
	// no lookup is made at synthesis.
	HostedZone awsroute53.IHostedZone

	// Shortcut to enable CORS for the given origin with default headers.
	// Use Cors for full control.
	AllowOrigins *string

	// CORS configuration, ignored if HttpApiProps.CorsPreflight is defined.
	Cors *Cors

	// Access logging of the default stage
	AccessLog *AccessLog

	// Throttling of the default stage (all routes). Route specific throttling
	// is defined by RouteProps.Throttle.
	Throttle *Throttle

	// Name of SSM parameter, the API id is exported to (e.g. /myapp/v1/api).
	// Use it to refer the versioned API from another stack (see NewAlias).
	ApiIdParameter *string
}

type GoCompiler added in v0.6.0

type GoCompiler struct {
	// contains filtered or unexported fields
}

func NewGoCompiler added in v0.6.0

func NewGoCompiler(
	sourceCodePackage string,
	sourceCodeLambda string,
	sourceCodeVersion string,
	config *Toolchain,
) *GoCompiler

func (*GoCompiler) SourceCodeLambda added in v0.6.0

func (g *GoCompiler) SourceCodeLambda() string

func (*GoCompiler) SourceCodeModule added in v0.8.3

func (g *GoCompiler) SourceCodeModule() string

func (*GoCompiler) SourceCodeVersion added in v0.8.3

func (g *GoCompiler) SourceCodeVersion() string

func (*GoCompiler) TryBundle added in v0.6.0

func (g *GoCompiler) TryBundle(outputDir *string, options *awscdk.BundlingOptions) *bool

type Hasher added in v0.10.6

type Hasher struct {
	// contains filtered or unexported fields
}

Hasher is a utility to compute hash of lambda function and its dependencies.

The hash covers:

  • the content of every source file (Go, Cgo, assembly, embedded files) of every package the function depends on that belongs to the main module or to a module replaced by a local directory;
  • the path and version of every other module the function depends on;
  • the Go toolchain version;
  • the build configuration (GOOS, GOARCH, CGO_ENABLED, ldflags, etc).

Packages are resolved by `go list` in module mode, file names are hashed relative to the package import path, so the hash is the same on any machine regardless of the checkout location.

func NewHasher added in v0.10.6

func NewHasher(verbose bool) *Hasher

func (*Hasher) Hash added in v0.10.6

func (h *Hasher) Hash(sourceCodeModule, sourceCodeLambda, sourceCodeVersion string) (string, error)

type RouteProps added in v0.14.0

type RouteProps struct {
	// Function handling requests of the route (required)
	Handler awslambda.IFunction

	// HTTP methods of the route. The default is every method except OPTIONS
	// if CORS is enabled at the gateway (preflight is answered by
	// API Gateway), otherwise ANY.
	Methods []apigw2.HttpMethod

	// Construct id of the route. If the route has multiple methods, the id is
	// suffixed with the method. The default is derived from the method and
	// the whole path (e.g. GET/{instance}/facts), as HttpApi.AddRoutes does.
	Id string

	// Payload format of the Lambda integration, default is 1.0.
	//
	//   - 1.0: the function receives events.APIGatewayProxyRequest, the context
	//     of Lambda authorizer is at RequestContext.Authorizer
	//   - 2.0: the function receives events.APIGatewayV2HTTPRequest, the context
	//     of Lambda authorizer is at RequestContext.Authorizer.Lambda
	//
	// One integration per function and payload format is shared by all routes.
	PayloadFormatVersion apigw2.PayloadFormatVersion

	// Throttling of the route, overrides the gateway's throttling.
	Throttle *Throttle

	// OAuth scopes required by the route (JWT and Cognito authorizers only).
	AuthorizationScopes []string

	// Principal granted to invoke the route (IAM authorizer only).
	Grantee awsiam.IGrantable
}

RouteProps defines the exact route of HTTP API.

Unlike AddResource, the route matches the path exactly. The path may contain path parameters (e.g. /{instance}/facts), greedy path parameter (e.g. /files/{proxy+}) or be the root "/".

type Throttle added in v0.14.0

type Throttle struct {
	// The steady-state rate limit (requests per second).
	RateLimit float64
	// The maximum number of concurrent requests.
	BurstLimit float64
}

Throttling of the API

type Toolchain added in v0.12.1

type Toolchain struct {
	// Go environment, default includes
	//	GOOS=linux
	//	GOARCH=arm64
	//	CGO_ENABLED=0
	//
	// The compiler inherits the environment of the process (HOME, GOPATH,
	// GOCACHE, GOPROXY, GOPRIVATE, GOFLAGS, etc), variables defined here
	// override inherited ones.
	GoEnv map[string]string

	// Linker flags passed to the Go linker (-ldflags).
	LDFlags []string

	// Go variables injected at link time using -X key=value.
	// Example: -ldflags "-X main.version=1.0.0"
	LDVars map[string]string
}

Configure Go compiler and Linter

Directories

Path Synopsis
examples
internal
cmd/auth command
test
lambda/another command
lambda/go command

Jump to

Keyboard shortcuts

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