package main
import (
"context"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/go-mizu/mizu"
)
var app *mizu.App
func init() {
// Initialize once, reuse across invocations
app = mizu.New()
app.Get("/", func(c *mizu.Ctx) error {
return c.JSON(200, map[string]string{"message": "Hello from Lambda!"})
})
app.Get("/users/{id}", func(c *mizu.Ctx) error {
id := c.Param("id")
return c.JSON(200, map[string]string{"id": id})
})
}
func handler(ctx context.Context, req events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error) {
// Convert Lambda request to http.Request
httpReq, err := convertRequest(ctx, req)
if err != nil {
return events.LambdaFunctionURLResponse{StatusCode: 500}, err
}
// Create response recorder
recorder := &responseRecorder{
headers: make(http.Header),
body: &bytes.Buffer{},
}
// Handle request
app.ServeHTTP(recorder, httpReq)
// Convert to Lambda response
return events.LambdaFunctionURLResponse{
StatusCode: recorder.statusCode,
Headers: flattenHeaders(recorder.headers),
Body: recorder.body.String(),
IsBase64Encoded: false,
}, nil
}
func main() {
lambda.Start(handler)
}
// Helper types and functions...
type responseRecorder struct {
statusCode int
headers http.Header
body *bytes.Buffer
}
func (r *responseRecorder) Header() http.Header { return r.headers }
func (r *responseRecorder) Write(b []byte) (int, error) { return r.body.Write(b) }
func (r *responseRecorder) WriteHeader(code int) { r.statusCode = code }
func convertRequest(ctx context.Context, req events.LambdaFunctionURLRequest) (*http.Request, error) {
httpReq, err := http.NewRequestWithContext(ctx, req.RequestContext.HTTP.Method, req.RawPath, strings.NewReader(req.Body))
if err != nil {
return nil, err
}
httpReq.URL.RawQuery = req.RawQueryString
for k, v := range req.Headers {
httpReq.Header.Set(k, v)
}
return httpReq, nil
}
func flattenHeaders(h http.Header) map[string]string {
flat := make(map[string]string)
for k, v := range h {
flat[k] = strings.Join(v, ",")
}
return flat
}