将Node.js代码转换为Golang的实现方法
将Node.js代码转换为Golang的实现方法
'use strict'
const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.AWS_REGION })
const s3 = new AWS.S3()
// Change this value to adjust the signed URL's expiration
const URL_EXPIRATION_SECONDS = 300
// Main Lambda entry point
exports.handler = async (event) => {
return await getUploadURL(event)
}
const getUploadURL = async function(event) {
const randomID = parseInt(Math.random() * 10000000)
const Key = `${randomID}.jpg`
// Get signed URL from S3
const s3Params = {
Bucket: process.env.UploadBucket,
Key,
Expires: URL_EXPIRATION_SECONDS,
ContentType: 'image/jpeg',
// This ACL makes the uploaded object publicly readable. You must also uncomment
// the extra permission for the Lambda function in the SAM template.
// ACL: 'public-read'
}
console.log('Params: ', s3Params)
const uploadURL = await s3.getSignedUrlPromise('putObject', s3Params)
return JSON.stringify({
uploadURL: uploadURL,
Key
})
}
更多关于将Node.js代码转换为Golang的实现方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
很好的建议。还有一个有用的资源:看起来那段 Node.js 代码正在读取一个环境变量来获取区域信息。可以参考这个 Go by Example,它提供了一个简洁的示例,展示了如何在 Go 中实现:
https://gobyexample.com/environment-variables
不过说实话,我不太确定 AWS_REGION 是否需要这样处理——因为 AWS SDK 本身就会使用那个环境变量,所以可能不需要在配置中显式设置。但对于 UploadBucket 来说,这个方法可能会派上用场。
更多关于将Node.js代码转换为Golang的实现方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
你好,Abhishek Kumar Gupta,欢迎来到论坛!
这个网站上的任何人都不太可能将你的整个 Node.js 程序翻译成 Go 并直接交给你。有一些其他网站可以付费请人帮你做这件事,但本网站成员的目标是指导你,以便你能(主要)自己解决问题。
本着这个目标,我目前给你的建议是:
- 阅读 AWS SDK for Go 的文档。
- 查看 示例。
- 如果你有任何具体问题(例如:“如何在 Go 中设置 Lambda 入口点?”或“如何在 Go 中指定 S3 上传超时?”等等),可以随时在这里提问。
以下是使用Golang实现相同功能的代码示例:
package main
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
const URL_EXPIRATION_SECONDS = 300
type Response struct {
UploadURL string `json:"uploadURL"`
Key string `json:"Key"`
}
func main() {
// 模拟Lambda处理函数
event := map[string]interface{}{}
result, _ := handler(context.Background(), event)
fmt.Println(result)
}
func handler(ctx context.Context, event map[string]interface{}) (string, error) {
return getUploadURL(ctx)
}
func getUploadURL(ctx context.Context) (string, error) {
// 生成随机ID
rand.Seed(time.Now().UnixNano())
randomID := rand.Intn(10000000)
key := fmt.Sprintf("%d.jpg", randomID)
// 加载AWS配置
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(os.Getenv("AWS_REGION")))
if err != nil {
return "", fmt.Errorf("failed to load AWS config: %w", err)
}
// 创建S3客户端
s3Client := s3.NewFromConfig(cfg)
// 生成预签名URL
presignClient := s3.NewPresignClient(s3Client)
presignParams := &s3.PutObjectInput{
Bucket: aws.String(os.Getenv("UploadBucket")),
Key: aws.String(key),
ContentType: aws.String("image/jpeg"),
}
presignResult, err := presignClient.PresignPutObject(ctx, presignParams,
func(opts *s3.PresignOptions) {
opts.Expires = time.Duration(URL_EXPIRATION_SECONDS) * time.Second
},
)
if err != nil {
return "", fmt.Errorf("failed to generate presigned URL: %w", err)
}
// 构建响应
response := Response{
UploadURL: presignResult.URL,
Key: key,
}
// 转换为JSON字符串
jsonResponse, err := json.Marshal(response)
if err != nil {
return "", fmt.Errorf("failed to marshal response: %w", err)
}
return string(jsonResponse), nil
}
需要添加的go.mod依赖:
module s3-presigned-url
go 1.21
require (
github.com/aws/aws-sdk-go-v2 v1.24.0
github.com/aws/aws-sdk-go-v2/config v1.26.1
github.com/aws/aws-sdk-go-v2/service/s3 v1.47.5
)
主要区别说明:
- AWS SDK版本:Golang使用aws-sdk-go-v2,这是最新的AWS SDK for Go版本
- 配置加载:通过
config.LoadDefaultConfig加载AWS配置,支持环境变量和默认凭证链 - 预签名URL生成:使用
s3.NewPresignClient创建预签名客户端,通过PresignPutObject方法生成上传URL - 错误处理:Golang使用显式错误返回,需要处理每个可能返回错误的操作
- 随机数生成:使用
rand.Intn替代Math.random(),需要先设置随机种子 - JSON处理:使用标准库的
encoding/json进行JSON序列化
这个实现保持了与Node.js版本相同的功能逻辑,包括环境变量读取、S3预签名URL生成和JSON响应格式。

