the*_*lja 1 file-upload go aws-lambda
我需要使用 Go 对通过 AWS Lambda 上传的上传文件的内容进行一些简单的操作,但不确定如何解析接收内容,因为我是 Go 新手。到目前为止我找到的解决方案与http包和MultiPart表单函数有关。
type Request events.APIGatewayProxyRequest
func Handler(ctx context.Context, req Request) (Response, error) {
fmt.Println(req.Body)
....
}
Run Code Online (Sandbox Code Playgroud)
这就是我的请求正文的样子
------WebKitFormBoundaryx0SVDelfa90Fi5Uo
Content-Disposition: form-data; name="file"; filename="upload.txt"
Content-Type: text/plain
this is content
------WebKitFormBoundaryx0SVDelfa90Fi5Uo--
Run Code Online (Sandbox Code Playgroud)
我的请求是 的实例APIGatewayProxyRequest。
我想知道是否可以获得一个自定义结构,我可以从中访问 fe 等数据
customStruct.content => "this is content"
customStruct.fileName => upload.txt
customStruct.fileExtension => txt
Run Code Online (Sandbox Code Playgroud)
这有 3 个部分:
multipart.Reader来自events.APIGatewayProxyRequestmultipart.Reader它multipart.NewReader采用一个io.Readerandboundary字符串,如签名所示:
func NewReader(r io.Reader, boundary string) *Reader
Run Code Online (Sandbox Code Playgroud)
为此,您需要从Content-TypeHTTP 请求标头中提取边界字符串,这可以使用mime.ParseMediaType.
NewReaderMultipart执行此操作的一个简单方法是从go-awslambda具有以下签名的包中调用:
func NewReaderMultipart(req events.APIGatewayProxyRequest) (*multipart.Reader, error)
Run Code Online (Sandbox Code Playgroud)
获得 后mime.Reader,导航 MIME 消息,直到找到所需的 MIME 部分。
在此示例中,只有一部分,因此您只需调用:
part, err := reader.NextPart()
Run Code Online (Sandbox Code Playgroud)
一旦获得 MIME 部分,就可以提取所需的值。
content, err := io.ReadAll(part)
Run Code Online (Sandbox Code Playgroud)
从MIME部分获取文件名如下:
filename := part.FileName()
Run Code Online (Sandbox Code Playgroud)
称呼path/filepath.Ext。.这将在扩展中添加前导句点,但这可以轻松删除。
ext := filepath.Ext(part.FileName())
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式组合:
import (
"context"
"encoding/json"
"io"
"github.com/aws/aws-lambda-go/events"
"github.com/grokify/go-awslambda"
)
type customStruct struct {
Content string
FileName string
FileExtension string
}
func handleRequest(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
res := events.APIGatewayProxyResponse{}
r, err := awslambda.NewReaderMultipart(req)
if err != nil {
return res, err
}
part, err := r.NextPart()
if err != nil {
return res, err
}
content, err := io.ReadAll(part)
if err != nil {
return res, err
}
custom := customStruct{
Content: string(content),
FileName: part.FileName(),
FileExtension: filepath.Ext(part.FileName())}
customBytes, err := json.Marshal(custom)
if err != nil {
return res, err
}
res = events.APIGatewayProxyResponse{
StatusCode: 200,
Headers: map[string]string{
"Content-Type": "application/json"},
Body: string(customBytes)}
return res, nil
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2133 次 |
| 最近记录: |