Select Git revision
string_utils.go
request.go 2.51 KiB
package handler_utils
import (
"bytes"
"context"
"github.com/aws/aws-sdk-go/aws/credentials"
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/go-resty/resty/v2"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/aws/aws-lambda-go/lambdacontext"
)
const HTTPXRequestIDHeaderKey = "X-Request-ID"
func RequestIDFromLambdaContext(ctx context.Context) *string {
// Get request ID from context
if ctx != nil {
lambdaContext, _ := lambdacontext.FromContext(ctx)
if lambdaContext != nil {
return &lambdaContext.AwsRequestID
}
}
return nil
}
func RequestIDFromHeaders(headers map[string]string, requestIDHeaderKey string) *string {
// Get request ID from parent micro service
if requestID, ok := headers[requestIDHeaderKey]; ok {
return &requestID
}
return nil
}
func AddRequestIDToHeaders(requestID *string, responseHeaders map[string]string, requestIDHeaderKey string, requestHeaders map[string]string) {
if requestID != nil && responseHeaders != nil {
responseHeaders[requestIDHeaderKey] = *requestID
responseHeaders[HTTPXRequestIDHeaderKey] = *requestID
}
// Add the HTTP X-Request-ID request header to the response headers: https://http.dev/x-request-id
for key, val := range requestHeaders {
// Don't be case-sensitive
if strings.ToLower(key) == strings.ToLower(HTTPXRequestIDHeaderKey) {
responseHeaders[HTTPXRequestIDHeaderKey] = val
break
}
}
}
func SignAWSRestyClient(client *resty.Client, accessKeyID, secretAccessKey string, bodyBytes []byte) error {
var bodySeeker io.ReadSeeker = bytes.NewReader(bodyBytes)
// Add a hook to sign the request before sending
client.SetPreRequestHook(func(_ *resty.Client, r *http.Request) error {
err := SignAWSHttpRequest(r, accessKeyID, secretAccessKey, bodySeeker)
if err != nil {
return err
}
return nil
})
return nil
}
// SignAWSRequest wraps and executes http.NewRequest and adds a sig version 4 signature for AWS API Gateway