amazon-web-services - Go 中返回 JSON

标签 amazon-web-services go lambda

如何从 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 获得的结果:

enter image description here

最佳答案

自从 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/

相关文章:

java - 从 amazon s3 存储桶删除文件时出错

amazon-web-services - AWS Cloudformation dynamodb 表名末尾有字符

node.js - Lambda 函数失败,未生成日志

go - 如何在 go 框架中为不同的测试执行测试顺序?

google-app-engine - 使用 go 和应用引擎的数据存储导入和解析大型 CSV 文件

go - 匿名结构无法使用复合文字进行编译

amazon-web-services - 使 Quicksight 资源依赖于 AWS CDK 中的 s3 存储桶创建

python - 比较卡住集时如何使用 Lambda 函数找到精确的字符串匹配?

c# - Lambda 参数在稍后范围内访问字段时与类字段冲突

java - Java 8 流中的非干扰确切含义