使用Golang从Lambda调用AppSync Mutation

9rygscc1  于 8个月前  发布在  Go
关注(0)|答案(3)|浏览(77)

我尝试从lambda调用一个变体(特别是使用golang)。我使用AWS_IAM作为AppSync API的身份验证方法。我还给予appsync:GraphQL权限给我的lambda。
然而,在看了这里的文档后:https://docs.aws.amazon.com/sdk-for-go/api/service/appsync/
我找不到任何关于如何从库中调用appsync的文档。有人能在这里为我指出正确的方向吗?
P.S.我不想从lambda查询或订阅或其他任何东西。它只是一个突变
谢谢你,谢谢
------更新------
感谢@thomasmichaelwallace通知我使用https://godoc.org/github.com/machinebox/graphql
现在的问题是,我如何使用awsv 4对来自该软件包的请求进行签名?

qnyhuwrf

qnyhuwrf1#

我找到了一种使用普通http.Request和AWS v4签名的方法。(感谢@thomasmichaelwallace指出这种方法)

client := new(http.Client)
// construct the query
query := AppSyncPublish{
    Query: `
        mutation ($userid: ID!) {
            publishMessage(
                userid: $userid
            ){
                userid
            }
        }
    `,
    Variables: PublishInput{
        UserID:     "wow",
    },
}
b, err := json.Marshal(&query)
if err != nil {
    fmt.Println(err)
}

// construct the request object
req, err := http.NewRequest("POST", os.Getenv("APPSYNC_URL"), bytes.NewReader(b))
if err != nil {
    fmt.Println(err)
}
req.Header.Set("Content-Type", "application/json")

// get aws credential
config := aws.Config{
    Region: aws.String(os.Getenv("AWS_REGION")),
}
sess := session.Must(session.NewSession(&config))

//sign the request
signer := v4.NewSigner(sess.Config.Credentials)
signer.Sign(req, bytes.NewReader(b), "appsync", "ap-southeast-1", time.Now())

//FIRE!!
response, _ := client.Do(req)

//print the response
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
newStr := buf.String()

fmt.Printf(newStr)

字符串

yyhrrdl8

yyhrrdl82#

问题是,该API/库旨在帮助您创建/更新应用程序同步示例。
如果你想真正调用它们,那么你需要POST到GraphQL端点。
最简单的测试方法是登录到AWS AppSync控制台,按下侧边栏中的“查看”按钮,然后输入并运行您的mutation。
我对go不太在行,但据我所知,golang中有GraphQL的客户端库(例如https://godoc.org/github.com/machinebox/graphql)。
如果您使用的是IAM,那么您需要使用v4签名来签署您的请求(详情请参阅本文:https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html

sigwle7e

sigwle7e3#

更新SDK v2:

func SignRequest(ctx context.Context, cfg aws.Config, req *http.Request, body []byte) error {
    signer := v4.NewSigner()

    hash := sha256.Sum256(body)

    cred, err := cfg.Credentials.Retrieve(ctx)
    if err != nil {
        return err
    }
    return signer.SignHTTP(ctx, cred, req, hex.EncodeToString(hash[:]), "appsync", cfg.Region, time.Now())
}

字符串
现在还有一个非官方客户端:https://github.com/sony/appsync-client-go

相关问题