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

使用apex/gateway与Localstack部署Go Lambda返回301异常求助

问题:Localstack部署Go Lambda函数返回301重定向而非预期内容

我正在使用Localstack部署Go语言编写的Lambda函数,采用apex/gateway包实现,该包可替代net/http的ListenAndServe以适配AWS Lambda。但调用函数后得到301重定向结果,没有输出预期的“Hello World from Go”。

Go源码

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/apex/gateway"
)

func main() {
    http.HandleFunc("/", hello)
    log.Fatal(gateway.ListenAndServe(":3000", nil))
}

func hello(w http.ResponseWriter, r *http.Request) {
    // example retrieving values from the api gateway proxy request context.
    requestContext, ok := gateway.RequestContext(r.Context())
    if !ok || requestContext.Authorizer["sub"] == nil {
        fmt.Fprint(w, "Hello World from Go")
        return
    }

    userID := requestContext.Authorizer["sub"].(string)
    fmt.Fprintf(w, "Hello %s from Go", userID)
}

部署命令

GOOS=linux GOARCH=amd64 go build -o main main.go
zip -D main.zip main
awslocal lambda create-function --function-name main --zip-file fileb://main.zip --runtime go1.x --role arn:aws:iam::000000000000:role/lambda-role
awslocal lambda invoke --function-name main output.txt

执行结果

终端输出:

{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}

output.txt文件内容:

{"statusCode":301,"headers":{"Content-Type":"text/html; charset=utf-8","Location":"/"},"multiValueHeaders":{},"body":"\u003ca href=\"/\"\u003eMoved Permanently\u003c/a\u003e.\n\n"}

我预期应输出“Hello World from Go”,但实际得到301重定向结果,已查阅相关帖子但未解决问题,特此求助。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:49:59