You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于AWS Lambda实现静态站点客户端页面自动化创建问询

Alright, let's walk through exactly how to build this AWS Lambda-driven automation for generating your client HTML pages. I’ve tailored this approach to your existing Bootstrap 4/Angular 1 setup, so it’ll fit right in:

整体 Workflow Overview

The core flow will be:

  1. Client uploads their product portfolio JSON to an S3 bucket
  2. S3 triggers an AWS Lambda function
  3. Lambda fetches your Bootstrap/Angular template, replaces placeholder fields, and injects the JSON path
  4. The final HTML file (named after the client’s company) is saved to a static hosting S3 bucket
  5. Clients access their page via your custom domain (e.g., mysite.com/acme-corp)

1. Prep Your AWS Resources First

S3 Buckets Setup

  • Template Bucket: Create an S3 bucket to store your master client-template.html file. In the template, add clear placeholders for dynamic data, like:
    • {{COMPANY_NAME}} for the client’s business name
    • {{CLIENT_WEBSITE}} for their official site URL
    • {{PRODUCT_JSON_URL}} for the path to their uploaded portfolio JSON
  • Client JSON Bucket: Make a bucket (e.g., client-product-assets) where clients will upload their JSON files. Enable S3 Event Notifications for this bucket: trigger Lambda whenever a new object is created (uploaded).
  • Static Hosting Bucket: Create a bucket (e.g., client-pages-hosting) to host the generated HTML files. Enable Static Website Hosting here, and configure CORS if needed for Angular to fetch the JSON files.

IAM Permissions for Lambda

Create an IAM role for your Lambda function with these permissions:

  • s3:GetObject for the template bucket and client JSON bucket
  • s3:PutObject for the static hosting bucket
  • Optional: sns:Publish if you want to send error alerts when something fails

2. Lambda Function Core Logic (Python Example)

I’ll use Python here because it’s straightforward for string manipulation and S3 interactions. You can adapt this to Node.js if that’s your preference.

import boto3
import json

s3 = boto3.client('s3')

# Configure your bucket names here
TEMPLATE_BUCKET = 'your-template-bucket-name'
TEMPLATE_KEY = 'client-template.html'
HOSTING_BUCKET = 'client-pages-hosting'

def lambda_handler(event, context):
    try:
        # Get details of the uploaded JSON file from the S3 event
        record = event['Records'][0]
        json_bucket = record['s3']['bucket']['name']
        json_key = record['s3']['object']['key']
        
        # Fetch and parse the client's JSON data
        json_response = s3.get_object(Bucket=json_bucket, Key=json_key)
        client_data = json.loads(json_response['Body'].read().decode('utf-8'))
        
        # Validate required fields exist in the JSON
        required_fields = ['companyName', 'officialWebsite']
        if not all(field in client_data for field in required_fields):
            raise ValueError("JSON missing required fields: companyName or officialWebsite")
        
        # Fetch the master template
        template_response = s3.get_object(Bucket=TEMPLATE_BUCKET, Key=TEMPLATE_KEY)
        template_content = template_response['Body'].read().decode('utf-8')
        
        # Replace placeholders with client data
        updated_html = template_content.replace('{{COMPANY_NAME}}', client_data['companyName'])
        updated_html = updated_html.replace('{{CLIENT_WEBSITE}}', client_data['officialWebsite'])
        
        # Generate public URL for the client's JSON (adjust if using private buckets)
        product_json_url = f"https://{json_bucket}.s3.amazonaws.com/{json_key}"
        updated_html = updated_html.replace('{{PRODUCT_JSON_URL}}', product_json_url)
        
        # Create a clean filename for the client's page (e.g., "acme-corp.html")
        page_filename = f"{client_data['companyName'].lower().replace(' ', '-')}.html"
        
        # Upload the final HTML to the hosting bucket
        s3.put_object(
            Bucket=HOSTING_BUCKET,
            Key=page_filename,
            Body=updated_html,
            ContentType='text/html'
        )
        
        return {
            'statusCode': 200,
            'body': f"Successfully generated client page: {page_filename}"
        }
    
    except Exception as e:
        # Optional: Send error alert via SNS here
        print(f"Error generating client page: {str(e)}")
        return {
            'statusCode': 500,
            'body': f"Failed to generate page: {str(e)}"
        }

3. Custom Domain Setup (For mysite.com/clientpage)

To map generated pages to your custom domain:

  1. Use Amazon CloudFront to create a distribution pointing to your static hosting bucket. This adds caching and HTTPS support.
  2. In Route 53 (or your DNS provider), create a CNAME record pointing your custom domain (e.g., mysite.com) to the CloudFront distribution domain.
  3. For clean paths like mysite.com/acme-corp, modify the Lambda to save the HTML file as index.html inside a folder named after the client (e.g., acme-corp/index.html). CloudFront/S3 will automatically serve this when users visit the folder path.

4. Quick Optimization Tips

  • Error Handling: Add SNS notifications to alert your team if a client’s JSON is invalid or Lambda fails.
  • Template Versioning: Enable versioning on your template bucket so you can roll back to older template versions if needed.
  • Private JSON Access: If clients’ product data is sensitive, use S3 pre-signed URLs for the JSON (note: these expire, so you’ll need to refresh them periodically or use CloudFront signed URLs).

内容的提问来源于stack exchange,提问作者sigur7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:29:00