如何从 golang 获取 JSON,而不将其编码为字符串?我正在使用this project将 go 代码包装在 python 中,以便我可以在 AWS lambda 函数中执行它。
我的问题是,无论我返回 json.Marshal(obj)
还是 string(json.Marshal(obj))
我都会得到 Base64 编码的 json 或字符串表示(例如 "{\"bar\":\"foo\"}"
)。如果您使用 AWS API 网关,这不是一个合适的响应,因为它需要纯 json,就像您在 Node.js 中返回 json 对象时得到的那样。
这是我的代码:
package main
import "C"
import (
"encoding/json"
"github.com/eawsy/aws-lambda-go-core/service/lambda/runtime"
)
type Response struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
func Handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
res := &Response{
StatusCode: 1,
Headers: map[string]string{"Content-Type": "application/json"},
Body: "Hello World",
}
content, _ := json.Marshal(res)
return string(content), nil
}
这是我从 AWS 获得的结果:
最佳答案
自从 AWS Lambda 起 officially supports Go ,这是一个修改后的示例。
package main
import (
"github.com/aws/aws-lambda-go/lambda"
)
// Response ...
type Response struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
// Handle ...
func Handle() (Response, error) {
return Response{
StatusCode: 1,
Headers: map[string]string{"Content-Type": "application/json"},
Body: "Hello World",
},
nil
}
func main() {
lambda.Start(Handle)
}
(用另一个例子更新下面)
您还可以直接使用 map[string]interface{}
数据类型,而无需创建 type
。
package main
import (
"github.com/aws/aws-lambda-go/lambda"
)
// Handle ...
func Handle() (map[string]interface{}, error) {
return map[string]interface{}{
"statusCode": 1,
"headers": map[string]string{"Content-Type": "application/json"},
"body": "Hello World",
},
nil
}
func main() {
lambda.Start(Handle)
}
关于amazon-web-services - Go 中返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41903075/