There are 3 parts to this:
- create a
multipart.Reader from events.APIGatewayProxyRequest
- get the MIME Part
- extract MIME Part values
Step 1: Create a multipart.Reader
The multipart.NewReader takes an io.Reader and boundary string as shown by the signature:
func NewReader(r io.Reader, boundary string) *Reader
To do this, you will need to extract the boundary string from the Content-Type HTTP request header which can be done using mime.ParseMediaType.
An easy way to do this is to call NewReaderMultipart from the go-awslambda package which has the following signature:
func NewReaderMultipart(req events.APIGatewayProxyRequest) (*multipart.Reader, error)
Step 2: get the MIME Part
Once you have the mime.Reader, navigate the MIME message till you find the MIME part desired.
In the example here, there's only one part, so you can simply call:
part, err := reader.NextPart()
Once you have the MIME Part, the desired values can be extracted.
Step 3.1: Content
content, err := io.ReadAll(part)
Step 3.2: File name
Get the file name from the MIME part as follows:
filename := part.FileName()
Step 3.3: File extension
Call path/filepath.Ext. This will add the leading period . in the extension but this can be easily removed.
ext := filepath.Ext(part.FileName())
Summary
You can combine this as follows:
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
}
strings.Split()or forstrings.Index())? pkg.go.dev/strings