1// Package jsonrpc provides JSON RPC utilities for serialization of AWS
2// requests and responses.
3package jsonrpc
4
5//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/input/json.json build_test.go
6//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/output/json.json unmarshal_test.go
7
8import (
9	"github.com/aws/aws-sdk-go/aws/awserr"
10	"github.com/aws/aws-sdk-go/aws/request"
11	"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
12	"github.com/aws/aws-sdk-go/private/protocol/rest"
13)
14
15var emptyJSON = []byte("{}")
16
17// BuildHandler is a named request handler for building jsonrpc protocol
18// requests
19var BuildHandler = request.NamedHandler{
20	Name: "awssdk.jsonrpc.Build",
21	Fn:   Build,
22}
23
24// UnmarshalHandler is a named request handler for unmarshaling jsonrpc
25// protocol requests
26var UnmarshalHandler = request.NamedHandler{
27	Name: "awssdk.jsonrpc.Unmarshal",
28	Fn:   Unmarshal,
29}
30
31// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc
32// protocol request metadata
33var UnmarshalMetaHandler = request.NamedHandler{
34	Name: "awssdk.jsonrpc.UnmarshalMeta",
35	Fn:   UnmarshalMeta,
36}
37
38// Build builds a JSON payload for a JSON RPC request.
39func Build(req *request.Request) {
40	var buf []byte
41	var err error
42	if req.ParamsFilled() {
43		buf, err = jsonutil.BuildJSON(req.Params)
44		if err != nil {
45			req.Error = awserr.New(request.ErrCodeSerialization, "failed encoding JSON RPC request", err)
46			return
47		}
48	} else {
49		buf = emptyJSON
50	}
51
52	if req.ClientInfo.TargetPrefix != "" || string(buf) != "{}" {
53		req.SetBufferBody(buf)
54	}
55
56	if req.ClientInfo.TargetPrefix != "" {
57		target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name
58		req.HTTPRequest.Header.Add("X-Amz-Target", target)
59	}
60
61	// Only set the content type if one is not already specified and an
62	// JSONVersion is specified.
63	if ct, v := req.HTTPRequest.Header.Get("Content-Type"), req.ClientInfo.JSONVersion; len(ct) == 0 && len(v) != 0 {
64		jsonVersion := req.ClientInfo.JSONVersion
65		req.HTTPRequest.Header.Set("Content-Type", "application/x-amz-json-"+jsonVersion)
66	}
67}
68
69// Unmarshal unmarshals a response for a JSON RPC service.
70func Unmarshal(req *request.Request) {
71	defer req.HTTPResponse.Body.Close()
72	if req.DataFilled() {
73		err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body)
74		if err != nil {
75			req.Error = awserr.NewRequestFailure(
76				awserr.New(request.ErrCodeSerialization, "failed decoding JSON RPC response", err),
77				req.HTTPResponse.StatusCode,
78				req.RequestID,
79			)
80		}
81	}
82	return
83}
84
85// UnmarshalMeta unmarshals headers from a response for a JSON RPC service.
86func UnmarshalMeta(req *request.Request) {
87	rest.UnmarshalMeta(req)
88}
89