repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"fmt"
"regexp"
"strings"
"unicode"
)
func (a *API) enableGeneratedTypedErrors() {
switch a.Metadata.Protocol {
case "json":
case "rest-json":
default:
return
}
a.WithGeneratedTypedErrors = true
}
// updateTopLevelShapeReferences moves resultWrapper, locationName, and
// xmlNamespace traits from toplevel shape references to the toplevel
// shapes for easier code generation
func (a *API) updateTopLevelShapeReferences() {
for _, o := range a.Operations {
// these are for REST-XML services
if o.InputRef.LocationName != "" {
o.InputRef.Shape.LocationName = o.InputRef.LocationName
}
if o.InputRef.Location != "" {
o.InputRef.Shape.Location = o.InputRef.Location
}
if o.InputRef.Payload != "" {
o.InputRef.Shape.Payload = o.InputRef.Payload
}
if o.InputRef.XMLNamespace.Prefix != "" {
o.InputRef.Shape.XMLNamespace.Prefix = o.InputRef.XMLNamespace.Prefix
}
if o.InputRef.XMLNamespace.URI != "" {
o.InputRef.Shape.XMLNamespace.URI = o.InputRef.XMLNamespace.URI
}
}
}
// writeShapeNames sets each shape's API and shape name values. Binding the
// shape to its parent API. This will set OrigShapeName on each Shape and ShapeRef
// to allow access to the original shape name for code generation.
func (a *API) writeShapeNames() {
writeOrigShapeName := func(s *ShapeRef) {
if len(s.ShapeName) > 0 {
s.OrigShapeName = s.ShapeName
}
}
for n, s := range a.Shapes {
s.API = a
s.ShapeName, s.OrigShapeName = n, n
for _, ref := range s.MemberRefs {
writeOrigShapeName(ref)
}
writeOrigShapeName(&s.MemberRef)
writeOrigShapeName(&s.KeyRef)
writeOrigShapeName(&s.ValueRef)
}
}
func (a *API) resolveReferences() {
resolver := referenceResolver{API: a, visited: map[*ShapeRef]bool{}}
for _, s := range a.Shapes {
resolver.resolveShape(s)
}
for _, o := range a.Operations {
o.API = a // resolve parent reference
resolver.resolveReference(&o.InputRef)
resolver.resolveReference(&o.OutputRef)
// Resolve references for errors also
for i := range o.ErrorRefs {
resolver.resolveReference(&o.ErrorRefs[i])
o.ErrorRefs[i].Shape.Exception = true
o.ErrorRefs[i].Shape.ErrorInfo.Type = o.ErrorRefs[i].Shape.ShapeName
}
}
}
func (a *API) backfillErrorMembers() {
stubShape := &Shape{
ShapeName: "string",
Type: "string",
}
var locName string
switch a.Metadata.Protocol {
case "ec2", "query", "rest-xml":
locName = "Message"
case "json", "rest-json":
locName = "message"
}
for _, s := range a.Shapes {
if !s.Exception {
continue
}
var haveMessage bool
for name := range s.MemberRefs {
if strings.EqualFold(name, "Message") {
haveMessage = true
break
}
}
if !haveMessage {
ref := &ShapeRef{
ShapeName: stubShape.ShapeName,
Shape: stubShape,
LocationName: locName,
}
s.MemberRefs["Message"] = ref
stubShape.refs = append(stubShape.refs, ref)
}
}
if len(stubShape.refs) != 0 {
a.Shapes["SDKStubErrorMessageShape"] = stubShape
}
}
// A referenceResolver provides a way to resolve shape references to
// shape definitions.
type referenceResolver struct {
*API
visited map[*ShapeRef]bool
}
// resolveReference updates a shape reference to reference the API and
// its shape definition. All other nested references are also resolved.
func (r *referenceResolver) resolveReference(ref *ShapeRef) {
if ref.ShapeName == "" {
return
}
shape, ok := r.API.Shapes[ref.ShapeName]
if !ok {
panic(fmt.Sprintf("unable resolve reference, %s", ref.ShapeName))
}
if ref.JSONValue {
ref.ShapeName = "JSONValue"
if _, ok := r.API.Shapes[ref.ShapeName]; !ok {
r.API.Shapes[ref.ShapeName] = &Shape{
API: r.API,
ShapeName: "JSONValue",
Type: "jsonvalue",
ValueRef: ShapeRef{
JSONValue: true,
},
}
}
}
ref.API = r.API // resolve reference back to API
ref.Shape = shape // resolve shape reference
if r.visited[ref] {
return
}
r.visited[ref] = true
shape.refs = append(shape.refs, ref) // register the ref
// resolve shape's references, if it has any
r.resolveShape(shape)
}
// resolveShape resolves a shape's Member Key Value, and nested member
// shape references.
func (r *referenceResolver) resolveShape(shape *Shape) {
r.resolveReference(&shape.MemberRef)
r.resolveReference(&shape.KeyRef)
r.resolveReference(&shape.ValueRef)
for _, m := range shape.MemberRefs {
r.resolveReference(m)
}
}
// fixStutterNames fixes all name stuttering based on Go naming conventions.
// "Stuttering" is when the prefix of a structure or function matches the
// package name (case insensitive).
func (a *API) fixStutterNames() {
names, ok := legacyStutterNames[ServiceID(a)]
if !ok {
return
}
shapeNames := names.ShapeOrder
if len(shapeNames) == 0 {
shapeNames = make([]string, 0, len(names.Shapes))
for k := range names.Shapes {
shapeNames = append(shapeNames, k)
}
}
for _, shapeName := range shapeNames {
s := a.Shapes[shapeName]
newName := names.Shapes[shapeName]
if other, ok := a.Shapes[newName]; ok && (other.Type == "structure" || other.Type == "enum") {
panic(fmt.Sprintf(
"shape name already exists, renaming %v to %v\n",
s.ShapeName, newName))
}
s.Rename(newName)
}
for opName, newName := range names.Operations {
if _, ok := a.Operations[newName]; ok {
panic(fmt.Sprintf(
"operation name already exists, renaming %v to %v\n",
opName, newName))
}
op := a.Operations[opName]
delete(a.Operations, opName)
a.Operations[newName] = op
op.ExportedName = newName
}
}
// regexpForValidatingShapeName is used by validateShapeName to filter acceptable shape names
// that may be renamed to a new valid shape name, if not already.
// The regex allows underscores(_) at the beginning of the shape name
// There may be 0 or more underscores(_). The next character would be the leading character
// in the renamed shape name and thus, must be an alphabetic character.
// The regex allows alphanumeric characters along with underscores(_) in rest of the string.
var regexForValidatingShapeName = regexp.MustCompile("^[_]*[a-zA-Z][a-zA-Z0-9_]*$")
// legacyShapeNames is a map of shape names that are supported and bypass the validateShapeNames util
var legacyShapeNames = map[string][]string{
"mediapackage": {
"__AdTriggersElement",
"__PeriodTriggersElement",
},
}
// validateShapeNames is valid only for shapes of type structure or enums
// We validate a shape name to check if its a valid shape name
// A valid shape name would only contain alphanumeric characters and have an alphabet as leading character.
//
// If we encounter a shape name with underscores(_), we remove the underscores, and
// follow a canonical upper camel case naming scheme to create a new shape name.
// If the shape name collides with an existing shape name we return an error.
// The resulting shape name must be a valid shape name or throw an error.
func (a *API) validateShapeNames() error {
loop:
for _, s := range a.Shapes {
if s.Type == "structure" || s.IsEnum() {
for _, legacyname := range legacyShapeNames[a.PackageName()] {
if s.ShapeName == legacyname {
continue loop
}
}
name := s.ShapeName
if b := regexForValidatingShapeName.MatchString(name); !b {
return fmt.Errorf("invalid shape name found: %v", s.ShapeName)
}
// Slice of strings returned after we split a string
// with a non alphanumeric character as delimiter.
slice := strings.FieldsFunc(name, func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})
// Build a string that follows canonical upper camel casing
var b strings.Builder
for _, word := range slice {
b.WriteString(strings.Title(word))
}
name = b.String()
if s.ShapeName != name {
if a.Shapes[name] != nil {
// throw an error if shape with a new shape name already exists
return fmt.Errorf("attempt to rename shape %v to %v for package %v failed, as this rename would result in shape name collision",
s.ShapeName, name, a.PackageName())
}
debugLogger.Logf("Renaming shape %v to %v for package %v \n", s.ShapeName, name, a.PackageName())
s.Rename(name)
}
}
}
return nil
}
// renameExportable renames all operation names to be exportable names.
// All nested Shape names are also updated to the exportable variant.
func (a *API) renameExportable() {
for name, op := range a.Operations {
newName := a.ExportableName(name)
if newName != name {
delete(a.Operations, name)
a.Operations[newName] = op
}
op.ExportedName = newName
}
for k, s := range a.Shapes {
// FIXME SNS has lower and uppercased shape names with the same name,
// except the lowercased variant is used exclusively for string and
// other primitive types. Renaming both would cause a collision.
// We work around this by only renaming the structure shapes.
if s.Type == "string" {
continue
}
for mName, member := range s.MemberRefs {
newName := a.ExportableName(mName)
if newName != mName {
delete(s.MemberRefs, mName)
s.MemberRefs[newName] = member
// also apply locationName trait so we keep the old one
// but only if there's no locationName trait on ref or shape
if member.LocationName == "" && member.Shape.LocationName == "" {
member.LocationName = mName
}
}
if newName == "_" {
panic("Shape " + s.ShapeName + " uses reserved member name '_'")
}
}
newName := a.ExportableName(k)
if s.Type == "structure" && newName == a.StructName() {
// If struct collides client's struct type name the shape needs to
// be renamed with a trailing `_` to prevent collision.
newName += "_"
}
if newName != s.ShapeName {
s.Rename(newName)
}
s.Payload = a.ExportableName(s.Payload)
// fix required trait names
for i, n := range s.Required {
s.Required[i] = a.ExportableName(n)
}
}
for _, s := range a.Shapes {
// fix enum names
if s.IsEnum() {
s.EnumConsts = make([]string, len(s.Enum))
for i := range s.Enum {
shape := s.ShapeName
shape = strings.ToUpper(shape[0:1]) + shape[1:]
s.EnumConsts[i] = shape + s.EnumName(i)
}
}
}
}
// renameCollidingFields will rename any fields that uses an SDK or Golang
// specific name.
func (a *API) renameCollidingFields() {
for _, v := range a.Shapes {
namesWithSet := map[string]struct{}{}
for k, field := range v.MemberRefs {
if _, ok := v.MemberRefs["Set"+k]; ok {
namesWithSet["Set"+k] = struct{}{}
}
if collides(k) || (v.Exception && exceptionCollides(k)) {
renameCollidingField(k, v, field)
}
}
// checks if any field names collide with setters.
for name := range namesWithSet {
field := v.MemberRefs[name]
renameCollidingField(name, v, field)
}
}
}
func renameCollidingField(name string, v *Shape, field *ShapeRef) {
newName := name + "_"
debugLogger.Logf("Shape %s's field %q renamed to %q", v.ShapeName, name, newName)
delete(v.MemberRefs, name)
v.MemberRefs[newName] = field
// Set LocationName to the original field name if it is not already set.
// This is to ensure we correctly serialize to the proper member name
if len(field.LocationName) == 0 {
field.LocationName = name
}
}
// collides will return true if it is a name used by the SDK or Golang.
func collides(name string) bool {
switch name {
case "String",
"GoString",
"Validate":
return true
}
return false
}
func exceptionCollides(name string) bool {
switch name {
case "Code",
"Message",
"OrigErr",
"Error",
"String",
"GoString",
"RequestID",
"StatusCode",
"RespMetadata":
return true
}
return false
}
func (a *API) applyShapeNameAliases() {
service, ok := shapeNameAliases[a.name]
if !ok {
return
}
// Generic Shape Aliases
for name, s := range a.Shapes {
if alias, ok := service[name]; ok {
s.Rename(alias)
s.AliasedShapeName = true
}
}
}
// renameIOSuffixedShapeNames renames shapes that have `Input` or `Output`
// as suffix in their shape names. We add `_` and the end to avoid possible
// conflicts with the generated operation input/output types. SDK has already
// released quite a few shapes with input, output name suffixed with Input or Output.
// This change uses a legacy IO suffixed list and does not rename those legacy shapes.
// We do not rename aliased shapes. We do not rename shapes that are an input or output
// shape of an operation.
func (a *API) renameIOSuffixedShapeNames() {
// map all input shapes in service enclosure
inputShapes := make(map[string]*Shape, len(a.Operations))
// map all output shapes in service enclosure
outputShapes := make(map[string]*Shape, len(a.Operations))
for _, op := range a.Operations {
if len(op.InputRef.ShapeName) != 0 {
inputShapes[op.InputRef.Shape.ShapeName] = op.InputRef.Shape
}
if len(op.OutputRef.ShapeName) != 0 {
outputShapes[op.OutputRef.Shape.ShapeName] = op.OutputRef.Shape
}
}
for name, shape := range a.Shapes {
// skip if this shape is already aliased
if shape.AliasedShapeName {
continue
}
// skip if shape name is not suffixed with `Input` or `Output`
if !strings.HasSuffix(name, "Input") && !strings.HasSuffix(name, "Output") {
continue
}
// skip if this shape is an input shape
if s, ok := inputShapes[name]; ok && s == shape {
continue
}
// skip if this shape is an output shape
if s, ok := outputShapes[name]; ok && s == shape {
continue
}
// skip if this shape is a legacy io suffixed shape
if legacyIOSuffixed.LegacyIOSuffix(a, name) {
continue
}
// rename the shape to suffix with `_`
shape.Rename(name + "_")
}
}
// createInputOutputShapes creates toplevel input/output shapes if they
// have not been defined in the API. This normalizes all APIs to always
// have an input and output structure in the signature.
func (a *API) createInputOutputShapes() {
for _, op := range a.Operations {
createAPIParamShape(a, op.Name, &op.InputRef, op.ExportedName+"Input",
shamelist.Input,
)
op.InputRef.Shape.UsedAsInput = true
createAPIParamShape(a, op.Name, &op.OutputRef, op.ExportedName+"Output",
shamelist.Output,
)
op.OutputRef.Shape.UsedAsOutput = true
}
}
func (a *API) renameAPIPayloadShapes() {
for _, op := range a.Operations {
op.InputRef.Payload = a.ExportableName(op.InputRef.Payload)
op.OutputRef.Payload = a.ExportableName(op.OutputRef.Payload)
}
}
func createAPIParamShape(a *API, opName string, ref *ShapeRef, shapeName string, shamelistLookup func(string, string) bool) {
if len(ref.ShapeName) == 0 {
setAsPlacholderShape(ref, shapeName, a)
return
}
// nothing to do if already the correct name.
if s := ref.Shape; s.AliasedShapeName || s.ShapeName == shapeName || shamelistLookup(a.name, opName) {
return
}
if s, ok := a.Shapes[shapeName]; ok {
panic(fmt.Sprintf(
"attempting to create duplicate API parameter shape, %v, %v, %v, %v\n",
shapeName, opName, ref.ShapeName, s.OrigShapeName,
))
}
ref.Shape.removeRef(ref)
ref.ShapeName = shapeName
ref.Shape = ref.Shape.Clone(shapeName)
ref.Shape.refs = append(ref.Shape.refs, ref)
}
func setAsPlacholderShape(tgtShapeRef *ShapeRef, name string, a *API) {
shape := a.makeIOShape(name)
shape.Placeholder = true
*tgtShapeRef = ShapeRef{API: a, ShapeName: shape.ShapeName, Shape: shape}
shape.refs = append(shape.refs, tgtShapeRef)
}
// makeIOShape returns a pointer to a new Shape initialized by the name provided.
func (a *API) makeIOShape(name string) *Shape {
shape := &Shape{
API: a, ShapeName: name, Type: "structure",
MemberRefs: map[string]*ShapeRef{},
}
a.Shapes[name] = shape
return shape
}
// removeUnusedShapes removes shapes from the API which are not referenced by
// any other shape in the API.
func (a *API) removeUnusedShapes() {
for _, s := range a.Shapes {
if len(s.refs) == 0 {
a.removeShape(s)
}
}
}
// Sets the EndpointsID field of Metadata with the value of the
// EndpointPrefix if EndpointsID is not set.
func (a *API) setMetadataEndpointsKey() {
if len(a.Metadata.EndpointsID) != 0 {
return
}
a.Metadata.EndpointsID = a.Metadata.EndpointPrefix
}
func (a *API) findEndpointDiscoveryOp() {
for _, op := range a.Operations {
if op.IsEndpointDiscoveryOp {
a.EndpointDiscoveryOp = op
return
}
}
}
func (a *API) injectUnboundedOutputStreaming() {
for _, op := range a.Operations {
if op.AuthType != V4UnsignedBodyAuthType {
continue
}
for _, ref := range op.InputRef.Shape.MemberRefs {
if ref.Streaming || ref.Shape.Streaming {
if len(ref.Documentation) != 0 {
ref.Documentation += `
//`
}
ref.Documentation += `
// To use an non-seekable io.Reader for this request wrap the io.Reader with
// "aws.ReadSeekCloser". The SDK will not retry request errors for non-seekable
// readers. This will allow the SDK to send the reader's payload as chunked
// transfer encoding.`
}
}
}
}
| 613 |
session-manager-plugin | aws | Go | // +build go1.8,codegen
package api
import (
"reflect"
"strconv"
"strings"
"testing"
)
func TestUniqueInputAndOutputs(t *testing.T) {
const serviceName = "FooService"
shamelist[serviceName] = map[string]persistAPIType{
"OpOutputNoRename": {
output: true,
},
"OpInputNoRename": {
input: true,
},
"OpBothNoRename": {
input: true,
output: true,
},
}
cases := [][]struct {
expectedInput string
expectedOutput string
operation string
input string
output string
}{
{
{
expectedInput: "FooOperationInput",
expectedOutput: "FooOperationOutput",
operation: "FooOperation",
input: "FooInputShape",
output: "FooOutputShape",
},
{
expectedInput: "BarOperationInput",
expectedOutput: "BarOperationOutput",
operation: "BarOperation",
input: "FooInputShape",
output: "FooOutputShape",
},
},
{
{
expectedInput: "FooOperationInput",
expectedOutput: "FooOperationOutput",
operation: "FooOperation",
input: "FooInputShape",
output: "FooOutputShape",
},
{
expectedInput: "OpOutputNoRenameInput",
expectedOutput: "OpOutputNoRenameOutputShape",
operation: "OpOutputNoRename",
input: "OpOutputNoRenameInputShape",
output: "OpOutputNoRenameOutputShape",
},
},
{
{
expectedInput: "FooOperationInput",
expectedOutput: "FooOperationOutput",
operation: "FooOperation",
input: "FooInputShape",
output: "FooOutputShape",
},
{
expectedInput: "OpInputNoRenameInputShape",
expectedOutput: "OpInputNoRenameOutput",
operation: "OpInputNoRename",
input: "OpInputNoRenameInputShape",
output: "OpInputNoRenameOutputShape",
},
},
{
{
expectedInput: "FooOperationInput",
expectedOutput: "FooOperationOutput",
operation: "FooOperation",
input: "FooInputShape",
output: "FooOutputShape",
},
{
expectedInput: "OpInputNoRenameInputShape",
expectedOutput: "OpInputNoRenameOutputShape",
operation: "OpBothNoRename",
input: "OpInputNoRenameInputShape",
output: "OpInputNoRenameOutputShape",
},
},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
a := &API{
name: serviceName,
Operations: map[string]*Operation{},
Shapes: map[string]*Shape{},
}
expected := map[string][]string{}
for _, op := range c {
o := &Operation{
Name: op.operation,
ExportedName: op.operation,
InputRef: ShapeRef{
API: a,
ShapeName: op.input,
Shape: &Shape{
API: a,
ShapeName: op.input,
},
},
OutputRef: ShapeRef{
API: a,
ShapeName: op.output,
Shape: &Shape{
API: a,
ShapeName: op.output,
},
},
}
o.InputRef.Shape.refs = append(o.InputRef.Shape.refs, &o.InputRef)
o.OutputRef.Shape.refs = append(o.OutputRef.Shape.refs, &o.OutputRef)
a.Operations[o.Name] = o
a.Shapes[op.input] = o.InputRef.Shape
a.Shapes[op.output] = o.OutputRef.Shape
expected[op.operation] = append(expected[op.operation],
op.expectedInput,
op.expectedOutput,
)
}
a.fixStutterNames()
a.applyShapeNameAliases()
a.createInputOutputShapes()
for k, v := range expected {
if e, ac := v[0], a.Operations[k].InputRef.Shape.ShapeName; e != ac {
t.Errorf("Error %s case: Expected %q, but received %q",
k, e, ac)
}
if e, ac := v[1], a.Operations[k].OutputRef.Shape.ShapeName; e != ac {
t.Errorf("Error %s case: Expected %q, but received %q",
k, e, ac)
}
}
})
}
}
func TestCollidingFields(t *testing.T) {
cases := map[string]struct {
MemberRefs map[string]*ShapeRef
Expect []string
IsException bool
}{
"SimpleMembers": {
MemberRefs: map[string]*ShapeRef{
"Code": {},
"Foo": {},
"GoString": {},
"Message": {},
"OrigErr": {},
"SetFoo": {},
"String": {},
"Validate": {},
},
Expect: []string{
"Code",
"Foo",
"GoString_",
"Message",
"OrigErr",
"SetFoo_",
"String_",
"Validate_",
},
},
"ExceptionShape": {
IsException: true,
MemberRefs: map[string]*ShapeRef{
"Code": {},
"Message": {},
"OrigErr": {},
"Other": {},
"String": {},
},
Expect: []string{
"Code_",
"Message_",
"OrigErr_",
"Other",
"String_",
},
},
}
for k, c := range cases {
t.Run(k, func(t *testing.T) {
a := &API{
Shapes: map[string]*Shape{
"shapename": {
ShapeName: k,
MemberRefs: c.MemberRefs,
Exception: c.IsException,
},
},
}
a.renameCollidingFields()
for i, name := range a.Shapes["shapename"].MemberNames() {
if e, a := c.Expect[i], name; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
})
}
}
func TestCollidingFields_MaintainOriginalName(t *testing.T) {
cases := map[string]struct {
MemberRefs map[string]*ShapeRef
Expect map[string]*ShapeRef
}{
"NoLocationName": {
MemberRefs: map[string]*ShapeRef{
"String": {},
},
Expect: map[string]*ShapeRef{
"String_": {LocationName: "String"},
},
},
"ExitingLocationName": {
MemberRefs: map[string]*ShapeRef{
"String": {LocationName: "OtherName"},
},
Expect: map[string]*ShapeRef{
"String_": {LocationName: "OtherName"},
},
},
}
for k, c := range cases {
t.Run(k, func(t *testing.T) {
a := &API{
Shapes: map[string]*Shape{
"shapename": {
ShapeName: k,
MemberRefs: c.MemberRefs,
},
},
}
a.renameCollidingFields()
if e, a := c.Expect, a.Shapes["shapename"].MemberRefs; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
func TestCreateInputOutputShapes(t *testing.T) {
meta := Metadata{
APIVersion: "0000-00-00",
EndpointPrefix: "rpcservice",
JSONVersion: "1.1",
Protocol: "json",
ServiceAbbreviation: "RPCService",
ServiceFullName: "RPC Service",
ServiceID: "RPCService",
SignatureVersion: "v4",
TargetPrefix: "RPCService_00000000",
UID: "RPCService-0000-00-00",
}
type OpExpect struct {
Input string
Output string
}
cases := map[string]struct {
API *API
ExpectOps map[string]OpExpect
ExpectShapes []string
}{
"allRename": {
API: &API{Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
OutputRef: ShapeRef{ShapeName: "FirstOpResponse"},
},
"SecondOp": {
Name: "SecondOp",
InputRef: ShapeRef{ShapeName: "SecondOpRequest"},
OutputRef: ShapeRef{ShapeName: "SecondOpResponse"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
},
"FirstOpResponse": {
ShapeName: "FirstOpResponse",
Type: "structure",
},
"SecondOpRequest": {
ShapeName: "SecondOpRequest",
Type: "structure",
},
"SecondOpResponse": {
ShapeName: "SecondOpResponse",
Type: "structure",
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
"SecondOp": {
Input: "SecondOpInput",
Output: "SecondOpOutput",
},
},
ExpectShapes: []string{
"FirstOpInput",
"FirstOpOutput",
"SecondOpInput",
"SecondOpOutput",
},
},
"noRename": {
API: &API{Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpInput"},
OutputRef: ShapeRef{ShapeName: "FirstOpOutput"},
},
"SecondOp": {
Name: "SecondOp",
InputRef: ShapeRef{ShapeName: "SecondOpInput"},
OutputRef: ShapeRef{ShapeName: "SecondOpOutput"},
},
},
Shapes: map[string]*Shape{
"FirstOpInput": {
ShapeName: "FirstOpInput",
Type: "structure",
},
"FirstOpOutput": {
ShapeName: "FirstOpOutput",
Type: "structure",
},
"SecondOpInput": {
ShapeName: "SecondOpInput",
Type: "structure",
},
"SecondOpOutput": {
ShapeName: "SecondOpOutput",
Type: "structure",
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
"SecondOp": {
Input: "SecondOpInput",
Output: "SecondOpOutput",
},
},
ExpectShapes: []string{
"FirstOpInput",
"FirstOpOutput",
"SecondOpInput",
"SecondOpOutput",
},
},
"renameWithNested": {
API: &API{Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpWriteMe"},
OutputRef: ShapeRef{ShapeName: "FirstOpReadMe"},
},
"SecondOp": {
Name: "SecondOp",
InputRef: ShapeRef{ShapeName: "SecondOpWriteMe"},
OutputRef: ShapeRef{ShapeName: "SecondOpReadMe"},
},
},
Shapes: map[string]*Shape{
"FirstOpWriteMe": {
ShapeName: "FirstOpWriteMe",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "String"},
},
},
"FirstOpReadMe": {
ShapeName: "FirstOpReadMe",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Bar": {ShapeName: "Struct"},
"Once": {ShapeName: "Once"},
},
},
"SecondOpWriteMe": {
ShapeName: "SecondOpWriteMe",
Type: "structure",
},
"SecondOpReadMe": {
ShapeName: "SecondOpReadMe",
Type: "structure",
},
"Once": {
ShapeName: "Once",
Type: "string",
},
"String": {
ShapeName: "String",
Type: "string",
},
"Struct": {
ShapeName: "Struct",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "String"},
"Bar": {ShapeName: "Struct"},
},
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
"SecondOp": {
Input: "SecondOpInput",
Output: "SecondOpOutput",
},
},
ExpectShapes: []string{
"FirstOpInput",
"FirstOpOutput",
"Once",
"SecondOpInput",
"SecondOpOutput",
"String",
"Struct",
},
},
"aliasedInput": {
API: &API{Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
OutputRef: ShapeRef{ShapeName: "FirstOpResponse"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
AliasedShapeName: true,
},
"FirstOpResponse": {
ShapeName: "FirstOpResponse",
Type: "structure",
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpRequest",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"FirstOpOutput",
"FirstOpRequest",
},
},
"aliasedOutput": {
API: &API{
Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
OutputRef: ShapeRef{ShapeName: "FirstOpResponse"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
},
"FirstOpResponse": {
ShapeName: "FirstOpResponse",
Type: "structure",
AliasedShapeName: true,
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpResponse",
},
},
ExpectShapes: []string{
"FirstOpInput", "FirstOpResponse",
},
},
"resusedShape": {
API: &API{
Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
OutputRef: ShapeRef{ShapeName: "ReusedShape"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "ReusedShape"},
"ooF": {ShapeName: "ReusedShapeList"},
},
},
"ReusedShape": {
ShapeName: "ReusedShape",
Type: "structure",
},
"ReusedShapeList": {
ShapeName: "ReusedShapeList",
Type: "list",
MemberRef: ShapeRef{ShapeName: "ReusedShape"},
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"FirstOpInput",
"FirstOpOutput",
"ReusedShape",
"ReusedShapeList",
},
},
"aliasedResusedShape": {
API: &API{
Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
OutputRef: ShapeRef{ShapeName: "ReusedShape"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "ReusedShape"},
"ooF": {ShapeName: "ReusedShapeList"},
},
},
"ReusedShape": {
ShapeName: "ReusedShape",
Type: "structure",
AliasedShapeName: true,
},
"ReusedShapeList": {
ShapeName: "ReusedShapeList",
Type: "list",
MemberRef: ShapeRef{ShapeName: "ReusedShape"},
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "ReusedShape",
},
},
ExpectShapes: []string{
"FirstOpInput",
"ReusedShape",
"ReusedShapeList",
},
},
"unsetInput": {
API: &API{Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
OutputRef: ShapeRef{ShapeName: "FirstOpResponse"},
},
},
Shapes: map[string]*Shape{
"FirstOpResponse": {
ShapeName: "FirstOpResponse",
Type: "structure",
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"FirstOpInput",
"FirstOpOutput",
},
},
"unsetOutput": {
API: &API{Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"FirstOpInput",
"FirstOpOutput",
},
},
"collidingShape": {
API: &API{
name: "APIClientName",
Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "APIClientName"},
"ooF": {ShapeName: "APIClientNameList"},
},
},
"APIClientName": {
ShapeName: "APIClientName", Type: "structure",
},
"APIClientNameList": {
ShapeName: "APIClientNameList", Type: "list",
MemberRef: ShapeRef{ShapeName: "APIClientName"},
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"APIClientNameList",
"APIClientName_",
"FirstOpInput",
"FirstOpOutput",
},
},
"MemberShapesWithInputAsSuffix": {
API: &API{
name: "APIClientName",
Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
InputRef: ShapeRef{ShapeName: "FirstOpRequest"},
},
},
Shapes: map[string]*Shape{
"FirstOpRequest": {
ShapeName: "FirstOpRequest",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "APIClientName"},
"ooF": {ShapeName: "FirstOpInput"},
},
},
"APIClientName": {
ShapeName: "APIClientName", Type: "structure",
},
"FirstOpInput": {
ShapeName: "FirstOpInput", Type: "list",
MemberRef: ShapeRef{
ShapeName: "APIClientName",
},
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"APIClientName_",
"FirstOpInput",
"FirstOpInput_",
"FirstOpOutput",
},
},
"MemberShapesWithOutputAsSuffix": {
API: &API{
name: "APIClientName",
Metadata: meta,
Operations: map[string]*Operation{
"FirstOp": {
Name: "FirstOp",
OutputRef: ShapeRef{ShapeName: "FirstOpResponse"},
},
},
Shapes: map[string]*Shape{
"FirstOpResponse": {
ShapeName: "FirstOpResponse",
Type: "structure",
MemberRefs: map[string]*ShapeRef{
"Foo": {ShapeName: "APIClientName"},
"ooF": {ShapeName: "FirstOpOutput"},
},
},
"APIClientName": {
ShapeName: "APIClientName", Type: "structure",
},
"FirstOpOutput": {
ShapeName: "FirstOpOutput", Type: "list",
MemberRef: ShapeRef{ShapeName: "APIClientName"},
},
},
},
ExpectOps: map[string]OpExpect{
"FirstOp": {
Input: "FirstOpInput",
Output: "FirstOpOutput",
},
},
ExpectShapes: []string{
"APIClientName_",
"FirstOpInput",
"FirstOpOutput",
"FirstOpOutput_",
},
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
a := c.API
a.Setup()
for opName, op := range a.Operations {
if e, a := op.InputRef.ShapeName, op.InputRef.Shape.ShapeName; e != a {
t.Errorf("expect input ref and shape names to match, %s, %s", e, a)
}
if e, a := c.ExpectOps[opName].Input, op.InputRef.ShapeName; e != a {
t.Errorf("expect %v input shape, got %v", e, a)
}
if e, a := op.OutputRef.ShapeName, op.OutputRef.Shape.ShapeName; e != a {
t.Errorf("expect output ref and shape names to match, %s, %s", e, a)
}
if e, a := c.ExpectOps[opName].Output, op.OutputRef.ShapeName; e != a {
t.Errorf("expect %v output shape, got %v", e, a)
}
}
if e, a := c.ExpectShapes, a.ShapeNames(); !reflect.DeepEqual(e, a) {
t.Errorf("expect %v shapes, got %v", e, a)
}
})
}
}
func TestValidateShapeNameMethod(t *testing.T) {
cases := map[string]struct {
inputShapeName string
shapeType string
expectedShapeName string
expectedError string
}{
"empty case": {
inputShapeName: "",
shapeType: "structure",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"No rename": {
inputShapeName: "Sample123Shape",
shapeType: "structure",
expectedShapeName: "Sample123Shape",
},
"starts with underscores": {
inputShapeName: "__Sample123Shape",
shapeType: "structure",
expectedShapeName: "Sample123Shape",
},
"Contains underscores": {
inputShapeName: "__sample_123_shape__",
shapeType: "structure",
expectedShapeName: "Sample123Shape",
},
"Starts with numeric character": {
inputShapeName: "123__sampleShape",
shapeType: "structure",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"Starts with non alphabetic or non underscore character": {
inputShapeName: "&&SampleShape",
shapeType: "structure",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"Contains non Alphanumeric or non underscore character": {
inputShapeName: "Sample&__Shape",
shapeType: "structure",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"Renamed Shape already exists": {
inputShapeName: "__sample_shape",
shapeType: "structure",
expectedShapeName: "",
expectedError: "rename would result in shape name collision",
},
"empty case for enums shape type": {
inputShapeName: "",
shapeType: "string",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"No rename for enums shape type": {
inputShapeName: "Sample123Shape",
shapeType: "string",
expectedShapeName: "Sample123Shape",
},
"starts with underscores for enums shape type": {
inputShapeName: "__Sample123Shape",
shapeType: "string",
expectedShapeName: "Sample123Shape",
},
"Contains underscores for enums shape type": {
inputShapeName: "__sample_123_shape__",
shapeType: "string",
expectedShapeName: "Sample123Shape",
},
"Starts with numeric character for enums shape type": {
inputShapeName: "123__sampleShape",
shapeType: "string",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"Starts with non alphabetic or non underscore character for enums shape type": {
inputShapeName: "&&SampleShape",
shapeType: "string",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"Contains non Alphanumeric or non underscore character for enums shape type": {
inputShapeName: "Sample&__Shape",
shapeType: "string",
expectedShapeName: "",
expectedError: "invalid shape name found",
},
"Renamed Shape already exists for enums shape type": {
inputShapeName: "__sample_shape",
shapeType: "string",
expectedShapeName: "",
expectedError: "rename would result in shape name collision",
},
}
for name, c := range cases {
operation := "FooOperation"
t.Run(name, func(t *testing.T) {
a := &API{
Operations: map[string]*Operation{},
Shapes: map[string]*Shape{},
}
// add another shape with name SampleShape to check for collision
a.Shapes["SampleShape"] = &Shape{ShapeName: "SampleShape"}
o := &Operation{
Name: operation,
ExportedName: operation,
InputRef: ShapeRef{
API: a,
ShapeName: c.inputShapeName,
Shape: &Shape{
API: a,
ShapeName: c.inputShapeName,
Type: c.shapeType,
Enum: []string{"x"},
},
},
}
o.InputRef.Shape.refs = append(o.InputRef.Shape.refs, &o.InputRef)
a.Operations[o.Name] = o
a.Shapes[c.inputShapeName] = o.InputRef.Shape
err := a.validateShapeNames()
if err != nil || c.expectedError != "" {
if err == nil {
t.Fatalf("Received no error, expected error with log: \n \t %v ", c.expectedError)
}
if c.expectedError == "" {
t.Fatalf("Expected no error, got %v", err.Error())
}
if e, a := err.Error(), c.expectedError; !strings.Contains(e, a) {
t.Fatalf("Expected to receive error containing %v, got %v", e, a)
}
return
}
if e, a := c.expectedShapeName, o.InputRef.Shape.ShapeName; e != a {
t.Fatalf("Expected shape name to be %v, got %v", e, a)
}
})
}
}
| 979 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"fmt"
"text/template"
)
// S3ManagerUploadInputGoCode returns the Go code for the S3 Upload Manager's
// input structure.
func S3ManagerUploadInputGoCode(a *API) string {
if v := a.PackageName(); v != "s3" {
panic(fmt.Sprintf("unexpected API model %s", v))
}
s, ok := a.Shapes["PutObjectInput"]
if !ok {
panic(fmt.Sprintf("unable to find PutObjectInput shape in S3 model"))
}
a.resetImports()
a.AddImport("io")
a.AddImport("time")
var w bytes.Buffer
if err := s3managerUploadInputTmpl.Execute(&w, s); err != nil {
panic(fmt.Sprintf("failed to execute %s template, %v",
s3managerUploadInputTmpl.Name(), err))
}
return a.importsGoCode() + w.String()
}
var s3managerUploadInputTmpl = template.Must(
template.New("s3managerUploadInputTmpl").
Funcs(template.FuncMap{
"GetDeprecatedMsg": getDeprecatedMessage,
}).
Parse(s3managerUploadInputTmplDef),
)
const s3managerUploadInputTmplDef = `
// UploadInput provides the input parameters for uploading a stream or buffer
// to an object in an Amazon S3 bucket. This type is similar to the s3
// package's PutObjectInput with the exception that the Body member is an
// io.Reader instead of an io.ReadSeeker.
type UploadInput struct {
_ struct{} {{ .GoTags true false }}
{{ range $name, $ref := $.MemberRefs -}}
{{ if eq $name "Body" }}
// The readable body payload to send to S3.
Body io.Reader
{{ else if eq $name "ContentLength" }}
{{/* S3 Upload Manager does not use modeled content length */}}
{{ else }}
{{ $isBlob := $.WillRefBeBase64Encoded $name -}}
{{ $isRequired := $.IsRequired $name -}}
{{ $doc := $ref.Docstring -}}
{{ if $doc -}}
{{ $doc }}
{{ if $ref.Deprecated -}}
//
// Deprecated: {{ GetDeprecatedMsg $ref.DeprecatedMsg $name }}
{{ end -}}
{{ end -}}
{{ if $isBlob -}}
{{ if $doc -}}
//
{{ end -}}
// {{ $name }} is automatically base64 encoded/decoded by the SDK.
{{ end -}}
{{ if $isRequired -}}
{{ if or $doc $isBlob -}}
//
{{ end -}}
// {{ $name }} is a required field
{{ end -}}
{{ $name }} {{ $.GoStructType $name $ref }} {{ $ref.GoTags false $isRequired }}
{{ end }}
{{ end }}
}
`
| 87 |
session-manager-plugin | aws | Go | // +build codegen
package api
// ServiceName returns the SDK's naming of the service. Has
// backwards compatibility built in for services that were
// incorrectly named with the service's endpoint prefix.
func ServiceName(a *API) string {
if oldName, ok := oldServiceNames[a.PackageName()]; ok {
return oldName
}
return ServiceID(a)
}
var oldServiceNames = map[string]string{
"migrationhub": "mgh",
"acmpca": "acm-pca",
"acm": "acm",
"alexaforbusiness": "a4b",
"apigateway": "apigateway",
"applicationautoscaling": "autoscaling",
"appstream": "appstream2",
"appsync": "appsync",
"athena": "athena",
"autoscalingplans": "autoscaling",
"autoscaling": "autoscaling",
"batch": "batch",
"budgets": "budgets",
"costexplorer": "ce",
"cloud9": "cloud9",
"clouddirectory": "clouddirectory",
"cloudformation": "cloudformation",
"cloudfront": "cloudfront",
"cloudhsm": "cloudhsm",
"cloudhsmv2": "cloudhsmv2",
"cloudsearch": "cloudsearch",
"cloudsearchdomain": "cloudsearchdomain",
"cloudtrail": "cloudtrail",
"codebuild": "codebuild",
"codecommit": "codecommit",
"codedeploy": "codedeploy",
"codepipeline": "codepipeline",
"codestar": "codestar",
"cognitoidentity": "cognito-identity",
"cognitoidentityprovider": "cognito-idp",
"cognitosync": "cognito-sync",
"comprehend": "comprehend",
"configservice": "config",
"connect": "connect",
"costandusagereportservice": "cur",
"datapipeline": "datapipeline",
"dax": "dax",
"devicefarm": "devicefarm",
"directconnect": "directconnect",
"applicationdiscoveryservice": "discovery",
"databasemigrationservice": "dms",
"directoryservice": "ds",
"dynamodb": "dynamodb",
"ec2": "ec2",
"ecr": "ecr",
"ecs": "ecs",
"eks": "eks",
"elasticache": "elasticache",
"elasticbeanstalk": "elasticbeanstalk",
"efs": "elasticfilesystem",
"elb": "elasticloadbalancing",
"elbv2": "elasticloadbalancing",
"emr": "elasticmapreduce",
"elastictranscoder": "elastictranscoder",
"ses": "email",
"marketplaceentitlementservice": "entitlement.marketplace",
"elasticsearchservice": "es",
"cloudwatchevents": "events",
"firehose": "firehose",
"fms": "fms",
"gamelift": "gamelift",
"glacier": "glacier",
"glue": "glue",
"greengrass": "greengrass",
"guardduty": "guardduty",
"health": "health",
"iam": "iam",
"inspector": "inspector",
"iotdataplane": "data.iot",
"iotjobsdataplane": "data.jobs.iot",
"iot": "iot",
"iot1clickdevicesservice": "devices.iot1click",
"iot1clickprojects": "projects.iot1click",
"iotanalytics": "iotanalytics",
"kinesisvideoarchivedmedia": "kinesisvideo",
"kinesisvideomedia": "kinesisvideo",
"kinesis": "kinesis",
"kinesisanalytics": "kinesisanalytics",
"kinesisvideo": "kinesisvideo",
"kms": "kms",
"lambda": "lambda",
"lexmodelbuildingservice": "models.lex",
"lightsail": "lightsail",
"cloudwatchlogs": "logs",
"machinelearning": "machinelearning",
"marketplacecommerceanalytics": "marketplacecommerceanalytics",
"mediaconvert": "mediaconvert",
"medialive": "medialive",
"mediapackage": "mediapackage",
"mediastoredata": "data.mediastore",
"mediastore": "mediastore",
"mediatailor": "api.mediatailor",
"marketplacemetering": "metering.marketplace",
"mobile": "mobile",
"mobileanalytics": "mobileanalytics",
"cloudwatch": "monitoring",
"mq": "mq",
"mturk": "mturk-requester",
"neptune": "rds",
"opsworks": "opsworks",
"opsworkscm": "opsworks-cm",
"organizations": "organizations",
"pi": "pi",
"pinpoint": "pinpoint",
"polly": "polly",
"pricing": "api.pricing",
"rds": "rds",
"redshift": "redshift",
"rekognition": "rekognition",
"resourcegroups": "resource-groups",
"resourcegroupstaggingapi": "tagging",
"route53": "route53",
"route53domains": "route53domains",
"lexruntimeservice": "runtime.lex",
"sagemakerruntime": "runtime.sagemaker",
"s3": "s3",
"sagemaker": "sagemaker",
"simpledb": "sdb",
"secretsmanager": "secretsmanager",
"serverlessapplicationrepository": "serverlessrepo",
"servicecatalog": "servicecatalog",
"servicediscovery": "servicediscovery",
"shield": "shield",
"sms": "sms",
"snowball": "snowball",
"sns": "sns",
"sqs": "sqs",
"ssm": "ssm",
"sfn": "states",
"storagegateway": "storagegateway",
"dynamodbstreams": "streams.dynamodb",
"sts": "sts",
"support": "support",
"swf": "swf",
"transcribeservice": "transcribe",
"translate": "translate",
"wafregional": "waf-regional",
"waf": "waf",
"workdocs": "workdocs",
"workmail": "workmail",
"workspaces": "workspaces",
"xray": "xray",
}
| 160 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"fmt"
"path"
"regexp"
"sort"
"strings"
"text/template"
"github.com/aws/aws-sdk-go/private/protocol"
)
// ErrorInfo represents the error block of a shape's structure
type ErrorInfo struct {
Type string
Code string
HTTPStatusCode int
}
// A XMLInfo defines URL and prefix for Shapes when rendered as XML
type XMLInfo struct {
Prefix string
URI string
}
// A ShapeRef defines the usage of a shape within the API.
type ShapeRef struct {
API *API `json:"-"`
Shape *Shape `json:"-"`
Documentation string
ShapeName string `json:"shape"`
Location string
LocationName string
QueryName string
Flattened bool
Streaming bool
XMLAttribute bool
// Ignore, if set, will not be sent over the wire
Ignore bool
XMLNamespace XMLInfo
Payload string
IdempotencyToken bool `json:"idempotencyToken"`
TimestampFormat string `json:"timestampFormat"`
JSONValue bool `json:"jsonvalue"`
Deprecated bool `json:"deprecated"`
DeprecatedMsg string `json:"deprecatedMessage"`
EndpointDiscoveryID bool `json:"endpointdiscoveryid"`
HostLabel bool `json:"hostLabel"`
OrigShapeName string `json:"-"`
GenerateGetter bool
IsEventPayload bool `json:"eventpayload"`
IsEventHeader bool `json:"eventheader"`
// Collection of custom tags the shape reference includes.
CustomTags ShapeTags
// Flags whether the member reference is a endpoint ARN
EndpointARN bool
// Flags whether the member reference is a Outpost ID
OutpostIDMember bool
// Flag whether the member reference is a Account ID when endpoint shape ARN is present
AccountIDMemberWithARN bool
}
// A Shape defines the definition of a shape type
type Shape struct {
API *API `json:"-"`
ShapeName string
Documentation string
MemberRefs map[string]*ShapeRef `json:"members"`
MemberRef ShapeRef `json:"member"` // List ref
KeyRef ShapeRef `json:"key"` // map key ref
ValueRef ShapeRef `json:"value"` // map value ref
Required []string
Payload string
Type string
Exception bool
Enum []string
EnumConsts []string
Flattened bool
Streaming bool
Location string
LocationName string
IdempotencyToken bool `json:"idempotencyToken"`
TimestampFormat string `json:"timestampFormat"`
XMLNamespace XMLInfo
Min float64 // optional Minimum length (string, list) or value (number)
OutputEventStreamAPI *EventStreamAPI
EventStream *EventStream
EventFor map[string]*EventStream `json:"-"`
IsInputEventStream bool `json:"-"`
IsOutputEventStream bool `json:"-"`
IsEventStream bool `json:"eventstream"`
IsEvent bool `json:"event"`
refs []*ShapeRef // References to this shape
resolvePkg string // use this package in the goType() if present
OrigShapeName string `json:"-"`
// Defines if the shape is a placeholder and should not be used directly
Placeholder bool
Deprecated bool `json:"deprecated"`
DeprecatedMsg string `json:"deprecatedMessage"`
Validations ShapeValidations
// Error information that is set if the shape is an error shape.
ErrorInfo ErrorInfo `json:"error"`
// Flags that the shape cannot be rename. Prevents the shape from being
// renamed further by the Input/Output.
AliasedShapeName bool
// Sensitive types should not be logged by SDK type loggers.
Sensitive bool `json:"sensitive"`
// Flags that a member of the shape is an EndpointARN
HasEndpointARNMember bool
// Flags that a member of the shape is an OutpostIDMember
HasOutpostIDMember bool
// Flags that the shape has an account id member along with EndpointARN member
HasAccountIdMemberWithARN bool
// Indicates the Shape is used as an operation input
UsedAsInput bool
// Indicates the Shape is used as an operation output
UsedAsOutput bool
}
// CanBeEmpty returns if the shape value can sent request as an empty value.
// String, blob, list, and map are types must not be empty when the member is
// serialized to the URI path, or decorated with HostLabel.
func (ref *ShapeRef) CanBeEmpty() bool {
switch ref.Shape.Type {
case "string":
return !(ref.Location == "uri" || ref.HostLabel)
case "blob", "map", "list":
return !(ref.Location == "uri")
default:
return true
}
}
// ErrorCodeName will return the error shape's name formated for
// error code const.
func (s *Shape) ErrorCodeName() string {
return "ErrCode" + s.ShapeName
}
// ErrorName will return the shape's name or error code if available based
// on the API's protocol. This is the error code string returned by the service.
func (s *Shape) ErrorName() string {
name := s.ErrorInfo.Type
switch s.API.Metadata.Protocol {
case "query", "ec2query", "rest-xml":
if len(s.ErrorInfo.Code) > 0 {
name = s.ErrorInfo.Code
}
}
if len(name) == 0 {
name = s.OrigShapeName
}
if len(name) == 0 {
name = s.ShapeName
}
return name
}
// PayloadRefName returns the payload member of the shape if there is one
// modeled. If no payload is modeled, empty string will be returned.
func (s *Shape) PayloadRefName() string {
if name := s.Payload; len(name) != 0 {
// Root shape
return name
}
for name, ref := range s.MemberRefs {
if ref.IsEventPayload {
return name
}
}
return ""
}
// GoTags returns the struct tags for a shape.
func (s *Shape) GoTags(root, required bool) string {
ref := &ShapeRef{ShapeName: s.ShapeName, API: s.API, Shape: s}
return ref.GoTags(root, required)
}
// Rename changes the name of the Shape to newName. Also updates
// the associated API's reference to use newName.
func (s *Shape) Rename(newName string) {
if s.AliasedShapeName {
panic(fmt.Sprintf("attempted to rename %s, but flagged as aliased",
s.ShapeName))
}
for _, r := range s.refs {
r.ShapeName = newName
}
delete(s.API.Shapes, s.ShapeName)
s.API.Shapes[newName] = s
s.ShapeName = newName
}
// MemberNames returns a slice of struct member names.
func (s *Shape) MemberNames() []string {
i, names := 0, make([]string, len(s.MemberRefs))
for n := range s.MemberRefs {
names[i] = n
i++
}
sort.Strings(names)
return names
}
// HasMember will return whether or not the shape has a given
// member by name.
func (s *Shape) HasMember(name string) bool {
_, ok := s.MemberRefs[name]
return ok
}
// GoTypeWithPkgName returns a shape's type as a string with the package name in
// <packageName>.<type> format. Package naming only applies to structures.
func (s *Shape) GoTypeWithPkgName() string {
return goType(s, true)
}
// GoTypeWithPkgNameElem returns the shapes type as a string with the "*"
// removed if there was one preset.
func (s *Shape) GoTypeWithPkgNameElem() string {
t := goType(s, true)
if strings.HasPrefix(t, "*") {
return t[1:]
}
return t
}
// UseIndirection returns if the shape's reference should use indirection or not.
func (s *ShapeRef) UseIndirection() bool {
switch s.Shape.Type {
case "map", "list", "blob", "structure", "jsonvalue":
return false
}
if s.Streaming || s.Shape.Streaming {
return false
}
if s.JSONValue {
return false
}
return true
}
func (s Shape) GetTimestampFormat() string {
format := s.TimestampFormat
if len(format) > 0 && !protocol.IsKnownTimestampFormat(format) {
panic(fmt.Sprintf("Unknown timestampFormat %s, for %s",
format, s.ShapeName))
}
return format
}
func (ref ShapeRef) GetTimestampFormat() string {
format := ref.TimestampFormat
if len(format) == 0 {
format = ref.Shape.TimestampFormat
}
if len(format) > 0 && !protocol.IsKnownTimestampFormat(format) {
panic(fmt.Sprintf("Unknown timestampFormat %s, for %s",
format, ref.ShapeName))
}
return format
}
// GoStructValueType returns the Shape's Go type value instead of a pointer
// for the type.
func (s *Shape) GoStructValueType(name string, ref *ShapeRef) string {
v := s.GoStructType(name, ref)
if ref.UseIndirection() && v[0] == '*' {
return v[1:]
}
return v
}
// GoStructType returns the type of a struct field based on the API
// model definition.
func (s *Shape) GoStructType(name string, ref *ShapeRef) string {
if (ref.Streaming || ref.Shape.Streaming) && s.Payload == name {
rtype := "io.ReadSeeker"
if strings.HasSuffix(s.ShapeName, "Output") {
rtype = "io.ReadCloser"
}
s.API.imports["io"] = true
return rtype
}
if ref.JSONValue {
s.API.AddSDKImport("aws")
return "aws.JSONValue"
}
for _, v := range s.Validations {
// TODO move this to shape validation resolution
if (v.Ref.Shape.Type == "map" || v.Ref.Shape.Type == "list") && v.Type == ShapeValidationNested {
s.API.imports["fmt"] = true
}
}
return ref.GoType()
}
// GoType returns a shape's Go type
func (s *Shape) GoType() string {
return goType(s, false)
}
// GoType returns a shape ref's Go type.
func (ref *ShapeRef) GoType() string {
if ref.Shape == nil {
panic(fmt.Errorf("missing shape definition on reference for %#v", ref))
}
return ref.Shape.GoType()
}
// GoTypeWithPkgName returns a shape's type as a string with the package name in
// <packageName>.<type> format. Package naming only applies to structures.
func (ref *ShapeRef) GoTypeWithPkgName() string {
if ref.Shape == nil {
panic(fmt.Errorf("missing shape definition on reference for %#v", ref))
}
return ref.Shape.GoTypeWithPkgName()
}
// Returns a string version of the Shape's type.
// If withPkgName is true, the package name will be added as a prefix
func goType(s *Shape, withPkgName bool) string {
switch s.Type {
case "structure":
if withPkgName || s.resolvePkg != "" {
pkg := s.resolvePkg
if pkg != "" {
s.API.imports[pkg] = true
pkg = path.Base(pkg)
} else {
pkg = s.API.PackageName()
}
return fmt.Sprintf("*%s.%s", pkg, s.ShapeName)
}
return "*" + s.ShapeName
case "map":
return "map[string]" + goType(s.ValueRef.Shape, withPkgName)
case "jsonvalue":
return "aws.JSONValue"
case "list":
return "[]" + goType(s.MemberRef.Shape, withPkgName)
case "boolean":
return "*bool"
case "string", "character":
return "*string"
case "blob":
return "[]byte"
case "byte", "short", "integer", "long":
return "*int64"
case "float", "double":
return "*float64"
case "timestamp":
s.API.imports["time"] = true
return "*time.Time"
default:
panic("Unsupported shape type: " + s.Type)
}
}
// GoTypeElem returns the Go type for the Shape. If the shape type is a pointer just
// the type will be returned minus the pointer *.
func (s *Shape) GoTypeElem() string {
t := s.GoType()
if strings.HasPrefix(t, "*") {
return t[1:]
}
return t
}
// GoTypeElem returns the Go type for the Shape. If the shape type is a pointer just
// the type will be returned minus the pointer *.
func (ref *ShapeRef) GoTypeElem() string {
if ref.Shape == nil {
panic(fmt.Errorf("missing shape definition on reference for %#v", ref))
}
return ref.Shape.GoTypeElem()
}
// ShapeTag is a struct tag that will be applied to a shape's generated code
type ShapeTag struct {
Key, Val string
}
// String returns the string representation of the shape tag
func (s ShapeTag) String() string {
return fmt.Sprintf(`%s:"%s"`, s.Key, s.Val)
}
// ShapeTags is a collection of shape tags and provides serialization of the
// tags in an ordered list.
type ShapeTags []ShapeTag
// Join returns an ordered serialization of the shape tags with the provided
// separator.
func (s ShapeTags) Join(sep string) string {
o := &bytes.Buffer{}
for i, t := range s {
o.WriteString(t.String())
if i < len(s)-1 {
o.WriteString(sep)
}
}
return o.String()
}
// String is an alias for Join with the empty space separator.
func (s ShapeTags) String() string {
return s.Join(" ")
}
// GoTags returns the rendered tags string for the ShapeRef
func (ref *ShapeRef) GoTags(toplevel bool, isRequired bool) string {
tags := append(ShapeTags{}, ref.CustomTags...)
if ref.Location != "" {
tags = append(tags, ShapeTag{"location", ref.Location})
} else if ref.Shape.Location != "" {
tags = append(tags, ShapeTag{"location", ref.Shape.Location})
} else if ref.IsEventHeader {
tags = append(tags, ShapeTag{"location", "header"})
}
if ref.LocationName != "" {
tags = append(tags, ShapeTag{"locationName", ref.LocationName})
} else if ref.Shape.LocationName != "" {
tags = append(tags, ShapeTag{"locationName", ref.Shape.LocationName})
} else if len(ref.Shape.EventFor) != 0 && ref.API.Metadata.Protocol == "rest-xml" {
// RPC JSON events need to have location name modeled for round trip testing.
tags = append(tags, ShapeTag{"locationName", ref.Shape.OrigShapeName})
}
if ref.QueryName != "" {
tags = append(tags, ShapeTag{"queryName", ref.QueryName})
}
if ref.Shape.MemberRef.LocationName != "" {
tags = append(tags, ShapeTag{"locationNameList", ref.Shape.MemberRef.LocationName})
}
if ref.Shape.KeyRef.LocationName != "" {
tags = append(tags, ShapeTag{"locationNameKey", ref.Shape.KeyRef.LocationName})
}
if ref.Shape.ValueRef.LocationName != "" {
tags = append(tags, ShapeTag{"locationNameValue", ref.Shape.ValueRef.LocationName})
}
if ref.Shape.Min > 0 {
tags = append(tags, ShapeTag{"min", fmt.Sprintf("%v", ref.Shape.Min)})
}
if ref.Deprecated || ref.Shape.Deprecated {
tags = append(tags, ShapeTag{"deprecated", "true"})
}
// All shapes have a type
tags = append(tags, ShapeTag{"type", ref.Shape.Type})
// embed the timestamp type for easier lookups
if ref.Shape.Type == "timestamp" {
if format := ref.GetTimestampFormat(); len(format) > 0 {
tags = append(tags, ShapeTag{
Key: "timestampFormat",
Val: format,
})
}
}
if ref.Shape.Flattened || ref.Flattened {
tags = append(tags, ShapeTag{"flattened", "true"})
}
if ref.XMLAttribute {
tags = append(tags, ShapeTag{"xmlAttribute", "true"})
}
if isRequired {
tags = append(tags, ShapeTag{"required", "true"})
}
if ref.Shape.IsEnum() {
tags = append(tags, ShapeTag{"enum", ref.ShapeName})
}
if toplevel {
if name := ref.Shape.PayloadRefName(); len(name) > 0 {
tags = append(tags, ShapeTag{"payload", name})
}
}
if ref.XMLNamespace.Prefix != "" {
tags = append(tags, ShapeTag{"xmlPrefix", ref.XMLNamespace.Prefix})
} else if ref.Shape.XMLNamespace.Prefix != "" {
tags = append(tags, ShapeTag{"xmlPrefix", ref.Shape.XMLNamespace.Prefix})
}
if ref.XMLNamespace.URI != "" {
tags = append(tags, ShapeTag{"xmlURI", ref.XMLNamespace.URI})
} else if ref.Shape.XMLNamespace.URI != "" {
tags = append(tags, ShapeTag{"xmlURI", ref.Shape.XMLNamespace.URI})
}
if ref.IdempotencyToken || ref.Shape.IdempotencyToken {
tags = append(tags, ShapeTag{"idempotencyToken", "true"})
}
if ref.Ignore {
tags = append(tags, ShapeTag{"ignore", "true"})
}
if ref.Shape.Sensitive {
tags = append(tags, ShapeTag{"sensitive", "true"})
}
return fmt.Sprintf("`%s`", tags)
}
// Docstring returns the godocs formated documentation
func (ref *ShapeRef) Docstring() string {
if ref.Documentation != "" {
return strings.Trim(ref.Documentation, "\n ")
}
return ref.Shape.Docstring()
}
// Docstring returns the godocs formated documentation
func (s *Shape) Docstring() string {
return strings.Trim(s.Documentation, "\n ")
}
// IndentedDocstring is the indented form of the doc string.
func (ref *ShapeRef) IndentedDocstring() string {
doc := ref.Docstring()
return strings.Replace(doc, "// ", "// ", -1)
}
var goCodeStringerTmpl = template.Must(template.New("goCodeStringerTmpl").Parse(`
// String returns the string representation
func (s {{ $.ShapeName }}) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s {{ $.ShapeName }}) GoString() string {
return s.String()
}
`))
// GoCodeStringers renders the Stringers for API input/output shapes
func (s *Shape) GoCodeStringers() string {
w := bytes.Buffer{}
if err := goCodeStringerTmpl.Execute(&w, s); err != nil {
panic(fmt.Sprintln("Unexpected error executing GoCodeStringers template", err))
}
return w.String()
}
var enumStrip = regexp.MustCompile(`[^a-zA-Z0-9_:\./-]`)
var enumDelims = regexp.MustCompile(`[-_:\./]+`)
var enumCamelCase = regexp.MustCompile(`([a-z])([A-Z])`)
// EnumName returns the Nth enum in the shapes Enum list
func (s *Shape) EnumName(n int) string {
enum := s.Enum[n]
enum = enumStrip.ReplaceAllLiteralString(enum, "")
enum = enumCamelCase.ReplaceAllString(enum, "$1-$2")
parts := enumDelims.Split(enum, -1)
for i, v := range parts {
v = strings.ToLower(v)
parts[i] = ""
if len(v) > 0 {
parts[i] = strings.ToUpper(v[0:1])
}
if len(v) > 1 {
parts[i] += v[1:]
}
}
enum = strings.Join(parts, "")
enum = strings.ToUpper(enum[0:1]) + enum[1:]
return enum
}
// NestedShape returns the shape pointer value for the shape which is nested
// under the current shape. If the shape is not nested nil will be returned.
//
// strucutures, the current shape is returned
// map: the value shape of the map is returned
// list: the element shape of the list is returned
func (s *Shape) NestedShape() *Shape {
var nestedShape *Shape
switch s.Type {
case "structure":
nestedShape = s
case "map":
nestedShape = s.ValueRef.Shape
case "list":
nestedShape = s.MemberRef.Shape
}
return nestedShape
}
var structShapeTmpl = func() *template.Template {
shapeTmpl := template.Must(
template.New("structShapeTmpl").
Funcs(template.FuncMap{
"GetDeprecatedMsg": getDeprecatedMessage,
"TrimExportedMembers": func(s *Shape) map[string]*ShapeRef {
members := map[string]*ShapeRef{}
for name, ref := range s.MemberRefs {
if ref.Shape.IsEventStream {
continue
}
members[name] = ref
}
return members
},
}).
Parse(structShapeTmplDef),
)
template.Must(
shapeTmpl.AddParseTree(
"eventStreamEventShapeTmpl", eventStreamEventShapeTmpl.Tree),
)
template.Must(
shapeTmpl.AddParseTree(
"exceptionShapeMethodTmpl",
exceptionShapeMethodTmpl.Tree),
)
shapeTmpl.Funcs(eventStreamEventShapeTmplFuncs)
template.Must(
shapeTmpl.AddParseTree(
"hostLabelsShapeTmpl",
hostLabelsShapeTmpl.Tree),
)
template.Must(
shapeTmpl.AddParseTree(
"endpointARNShapeTmpl",
endpointARNShapeTmpl.Tree),
)
template.Must(
shapeTmpl.AddParseTree(
"outpostIDShapeTmpl",
outpostIDShapeTmpl.Tree),
)
template.Must(
shapeTmpl.AddParseTree(
"accountIDWithARNShapeTmpl",
accountIDWithARNShapeTmpl.Tree),
)
return shapeTmpl
}()
const structShapeTmplDef = `
{{ $.Docstring }}
{{ if $.Deprecated -}}
{{ if $.Docstring -}}
//
{{ end -}}
// Deprecated: {{ GetDeprecatedMsg $.DeprecatedMsg $.ShapeName }}
{{ end -}}
type {{ $.ShapeName }} struct {
_ struct{} {{ $.GoTags true false }}
{{- if $.Exception }}
{{- $_ := $.API.AddSDKImport "private/protocol" }}
RespMetadata protocol.ResponseMetadata` + "`json:\"-\" xml:\"-\"`" + `
{{- end }}
{{- if $.OutputEventStreamAPI }}
{{ $.OutputEventStreamAPI.OutputMemberName }} *{{ $.OutputEventStreamAPI.Name }}
{{- end }}
{{- range $name, $elem := (TrimExportedMembers $) }}
{{ $isBlob := $.WillRefBeBase64Encoded $name -}}
{{ $isRequired := $.IsRequired $name -}}
{{ $doc := $elem.Docstring -}}
{{ if $doc -}}
{{ $doc }}
{{ if $elem.Deprecated -}}
//
// Deprecated: {{ GetDeprecatedMsg $elem.DeprecatedMsg $name }}
{{ end -}}
{{ end -}}
{{ if $isBlob -}}
{{ if $doc -}}
//
{{ end -}}
// {{ $name }} is automatically base64 encoded/decoded by the SDK.
{{ end -}}
{{ if $isRequired -}}
{{ if or $doc $isBlob -}}
//
{{ end -}}
// {{ $name }} is a required field
{{ end -}}
{{ $name }} {{ $.GoStructType $name $elem }} {{ $elem.GoTags false $isRequired }}
{{- end }}
}
{{- if not $.API.NoStringerMethods }}
{{ $.GoCodeStringers }}
{{- end }}
{{- if not (or $.API.NoValidataShapeMethods $.Exception) }}
{{- if $.Validations }}
{{ $.Validations.GoCode $ }}
{{- end }}
{{- end }}
{{- if not (or $.API.NoGenStructFieldAccessors $.Exception) }}
{{- $builderShapeName := print $.ShapeName }}
{{- range $name, $elem := (TrimExportedMembers $) }}
// Set{{ $name }} sets the {{ $name }} field's value.
func (s *{{ $builderShapeName }}) Set{{ $name }}(v {{ $.GoStructValueType $name $elem }}) *{{ $builderShapeName }} {
{{- if $elem.UseIndirection }}
s.{{ $name }} = &v
{{- else }}
s.{{ $name }} = v
{{- end }}
return s
}
{{- if $elem.GenerateGetter }}
func (s *{{ $builderShapeName }}) get{{ $name }}() (v {{ $.GoStructValueType $name $elem }}) {
{{- if $elem.UseIndirection }}
if s.{{ $name }} == nil {
return v
}
return *s.{{ $name }}
{{- else }}
return s.{{ $name }}
{{- end }}
}
{{- end }}
{{- end }}
{{- end }}
{{- if $.OutputEventStreamAPI }}
{{- $esMemberName := $.OutputEventStreamAPI.OutputMemberName }}
{{- if $.OutputEventStreamAPI.Legacy }}
func (s *{{ $.ShapeName }}) Set{{ $esMemberName }}(v *{{ $.OutputEventStreamAPI.Name }}) *{{ $.ShapeName }} {
s.{{ $esMemberName }} = v
return s
}
func (s *{{ $.ShapeName }}) Get{{ $esMemberName }}() *{{ $.OutputEventStreamAPI.Name }} {
return s.{{ $esMemberName }}
}
{{- end }}
// GetStream returns the type to interact with the event stream.
func (s *{{ $.ShapeName }}) GetStream() *{{ $.OutputEventStreamAPI.Name }} {
return s.{{ $esMemberName }}
}
{{- end }}
{{- if $.EventFor }}
{{ template "eventStreamEventShapeTmpl" $ }}
{{- end }}
{{- if and $.Exception (or $.API.WithGeneratedTypedErrors $.EventFor) }}
{{ template "exceptionShapeMethodTmpl" $ }}
{{- end }}
{{- if $.HasHostLabelMembers }}
{{ template "hostLabelsShapeTmpl" $ }}
{{- end }}
{{- if $.HasEndpointARNMember }}
{{ template "endpointARNShapeTmpl" $ }}
{{- end }}
{{- if $.HasOutpostIDMember }}
{{ template "outpostIDShapeTmpl" $ }}
{{- end }}
{{- if $.HasAccountIdMemberWithARN }}
{{ template "accountIDWithARNShapeTmpl" $ }}
{{- end }}
`
var exceptionShapeMethodTmpl = template.Must(
template.New("exceptionShapeMethodTmpl").Parse(`
{{- $_ := $.API.AddImport "fmt" }}
{{/* TODO allow service custom input to be used */}}
func newError{{ $.ShapeName }}(v protocol.ResponseMetadata) error {
return &{{ $.ShapeName }}{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *{{ $.ShapeName }}) Code() string {
return "{{ $.ErrorName }}"
}
// Message returns the exception's message.
func (s *{{ $.ShapeName }}) Message() string {
{{- if index $.MemberRefs "Message_" }}
if s.Message_ != nil {
return *s.Message_
}
{{ end -}}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *{{ $.ShapeName }}) OrigErr() error {
return nil
}
func (s *{{ $.ShapeName }}) Error() string {
{{- if or (and (eq (len $.MemberRefs) 1) (not (index $.MemberRefs "Message_"))) (gt (len $.MemberRefs) 1) }}
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
{{- else }}
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
{{- end }}
}
// Status code returns the HTTP status code for the request's response error.
func (s *{{ $.ShapeName }}) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *{{ $.ShapeName }}) RequestID() string {
return s.RespMetadata.RequestID
}
`))
var enumShapeTmpl = template.Must(template.New("EnumShape").Parse(`
{{ $.Docstring }}
const (
{{ range $index, $elem := $.Enum -}}
{{ $name := index $.EnumConsts $index -}}
// {{ $name }} is a {{ $.ShapeName }} enum value
{{ $name }} = "{{ $elem }}"
{{ end }}
)
{{/* Enum iterators use non-idomatic _Values suffix to avoid naming collisions with other generated types, and enum values */}}
// {{ $.ShapeName }}_Values returns all elements of the {{ $.ShapeName }} enum
func {{ $.ShapeName }}_Values() []string {
return []string{
{{ range $index, $elem := $.Enum -}}
{{ index $.EnumConsts $index }},
{{ end }}
}
}
`))
// GoCode returns the rendered Go code for the Shape.
func (s *Shape) GoCode() string {
w := &bytes.Buffer{}
switch {
case s.IsEventStream:
if err := renderEventStreamShape(w, s); err != nil {
panic(
fmt.Sprintf(
"failed to generate eventstream API shape, %s, %v",
s.ShapeName, err),
)
}
case s.Type == "structure":
if err := structShapeTmpl.Execute(w, s); err != nil {
panic(
fmt.Sprintf(
"Failed to generate struct shape %s, %v",
s.ShapeName, err),
)
}
case s.IsEnum():
if err := enumShapeTmpl.Execute(w, s); err != nil {
panic(
fmt.Sprintf(
"Failed to generate enum shape %s, %v",
s.ShapeName, err),
)
}
default:
panic(fmt.Sprintln("Cannot generate toplevel shape for", s.Type))
}
return w.String()
}
// IsEnum returns whether this shape is an enum list
func (s *Shape) IsEnum() bool {
return s.Type == "string" && len(s.Enum) > 0
}
// IsRequired returns if member is a required field. Required fields are fields
// marked as required, hostLabels, or location of uri path.
func (s *Shape) IsRequired(member string) bool {
ref, ok := s.MemberRefs[member]
if !ok {
panic(fmt.Sprintf(
"attempted to check required for unknown member, %s.%s",
s.ShapeName, member,
))
}
if ref.IdempotencyToken || ref.Shape.IdempotencyToken {
return false
}
if ref.Location == "uri" || ref.HostLabel {
return true
}
for _, n := range s.Required {
if n == member {
if ref.Shape.IsEventStream {
return false
}
return true
}
}
return false
}
// IsInternal returns whether the shape was defined in this package
func (s *Shape) IsInternal() bool {
return s.resolvePkg == ""
}
// removeRef removes a shape reference from the list of references this
// shape is used in.
func (s *Shape) removeRef(ref *ShapeRef) {
r := s.refs
for i := 0; i < len(r); i++ {
if r[i] == ref {
j := i + 1
copy(r[i:], r[j:])
for k, n := len(r)-j+i, len(r); k < n; k++ {
r[k] = nil // free up the end of the list
} // for k
s.refs = r[:len(r)-j+i]
break
}
}
}
func (s *Shape) WillRefBeBase64Encoded(refName string) bool {
payloadRefName := s.Payload
if payloadRefName == refName {
return false
}
ref, ok := s.MemberRefs[refName]
if !ok {
panic(fmt.Sprintf("shape %s does not contain %q refName", s.ShapeName, refName))
}
return ref.Shape.Type == "blob"
}
// Clone returns a cloned version of the shape with all references clones.
//
// Does not clone EventStream or Validate related values.
func (s *Shape) Clone(newName string) *Shape {
if s.AliasedShapeName {
panic(fmt.Sprintf("attempted to clone and rename %s, but flagged as aliased",
s.ShapeName))
}
n := new(Shape)
*n = *s
debugLogger.Logln("cloning", s.ShapeName, "to", newName)
n.MemberRefs = map[string]*ShapeRef{}
for k, r := range s.MemberRefs {
nr := new(ShapeRef)
*nr = *r
nr.Shape.refs = append(nr.Shape.refs, nr)
n.MemberRefs[k] = nr
}
if n.MemberRef.Shape != nil {
n.MemberRef.Shape.refs = append(n.MemberRef.Shape.refs, &n.MemberRef)
}
if n.KeyRef.Shape != nil {
n.KeyRef.Shape.refs = append(n.KeyRef.Shape.refs, &n.KeyRef)
}
if n.ValueRef.Shape != nil {
n.ValueRef.Shape.refs = append(n.ValueRef.Shape.refs, &n.ValueRef)
}
n.refs = []*ShapeRef{}
n.Required = append([]string{}, n.Required...)
n.Enum = append([]string{}, n.Enum...)
n.EnumConsts = append([]string{}, n.EnumConsts...)
n.API.Shapes[newName] = n
n.ShapeName = newName
n.OrigShapeName = s.OrigShapeName
return n
}
| 1,058 |
session-manager-plugin | aws | Go | // +build 1.6,codegen
package api_test
import (
"testing"
"github.com/aws/aws-sdk-go/private/model/api"
)
func TestShapeTagJoin(t *testing.T) {
s := api.ShapeTags{
{Key: "location", Val: "query"},
{Key: "locationName", Val: "abc"},
{Key: "type", Val: "string"},
}
expected := `location:"query" locationName:"abc" type:"string"`
o := s.Join(" ")
o2 := s.String()
if expected != o {
t.Errorf("Expected %s, but received %s", expected, o)
}
if expected != o2 {
t.Errorf("Expected %s, but received %s", expected, o2)
}
}
| 29 |
session-manager-plugin | aws | Go | package api
var shapeNameAliases = map[string]map[string]string{
"APIGateway": map[string]string{
"RequestValidator": "UpdateRequestValidatorOutput",
"VpcLink": "UpdateVpcLinkOutput",
"GatewayResponse": "UpdateGatewayResponseOutput",
},
"Lambda": map[string]string{
"Concurrency": "PutFunctionConcurrencyOutput",
},
"Neptune": map[string]string{
"DBClusterParameterGroupNameMessage": "ResetDBClusterParameterGroupOutput",
"DBParameterGroupNameMessage": "ResetDBParameterGroupOutput",
},
"RDS": map[string]string{
"DBClusterBacktrack": "BacktrackDBClusterOutput",
},
}
| 20 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"fmt"
"text/template"
)
// A ShapeValidationType is the type of validation that a shape needs
type ShapeValidationType int
const (
// ShapeValidationRequired states the shape must be set
ShapeValidationRequired = iota
// ShapeValidationMinVal states the shape must have at least a number of
// elements, or for numbers a minimum value
ShapeValidationMinVal
// ShapeValidationNested states the shape has nested values that need
// to be validated
ShapeValidationNested
)
// A ShapeValidation contains information about a shape and the type of validation
// that is needed
type ShapeValidation struct {
// Name of the shape to be validated
Name string
// Reference to the shape within the context the shape is referenced
Ref *ShapeRef
// Type of validation needed
Type ShapeValidationType
}
var validationGoCodeTmpls = template.Must(
template.New("validationGoCodeTmpls").
Funcs(template.FuncMap{
"getMin": func(ref *ShapeRef) float64 {
if !ref.CanBeEmpty() && ref.Shape.Min <= 0 {
return 1
}
return ref.Shape.Min
},
}).
Parse(`
{{ define "requiredValue" -}}
if s.{{ .Name }} == nil {
invalidParams.Add(request.NewErrParamRequired("{{ .Name }}"))
}
{{- end }}
{{ define "minLen" -}}
{{- $min := getMin .Ref -}}
if s.{{ .Name }} != nil && len(s.{{ .Name }}) < {{ $min }} {
invalidParams.Add(request.NewErrParamMinLen("{{ .Name }}", {{ $min }}))
}
{{- end }}
{{ define "minLenString" -}}
{{- $min := getMin .Ref -}}
if s.{{ .Name }} != nil && len(*s.{{ .Name }}) < {{ $min }} {
invalidParams.Add(request.NewErrParamMinLen("{{ .Name }}", {{ $min }}))
}
{{- end }}
{{ define "minVal" -}}
{{- $min := getMin .Ref -}}
if s.{{ .Name }} != nil && *s.{{ .Name }} < {{ $min }} {
invalidParams.Add(request.NewErrParamMinValue("{{ .Name }}", {{ $min }}))
}
{{- end }}
{{ define "nestedMapList" -}}
if s.{{ .Name }} != nil {
for i, v := range s.{{ .Name }} {
if v == nil { continue }
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "{{ .Name }}", i), err.(request.ErrInvalidParams))
}
}
}
{{- end }}
{{ define "nestedStruct" -}}
if s.{{ .Name }} != nil {
if err := s.{{ .Name }}.Validate(); err != nil {
invalidParams.AddNested("{{ .Name }}", err.(request.ErrInvalidParams))
}
}
{{- end }}
`))
// GoCode returns the generated Go code for the Shape with its validation type.
func (sv ShapeValidation) GoCode() string {
var err error
w := &bytes.Buffer{}
switch sv.Type {
case ShapeValidationRequired:
err = validationGoCodeTmpls.ExecuteTemplate(w, "requiredValue", sv)
case ShapeValidationMinVal:
switch sv.Ref.Shape.Type {
case "list", "map", "blob":
err = validationGoCodeTmpls.ExecuteTemplate(w, "minLen", sv)
case "string":
err = validationGoCodeTmpls.ExecuteTemplate(w, "minLenString", sv)
case "integer", "long", "float", "double":
err = validationGoCodeTmpls.ExecuteTemplate(w, "minVal", sv)
default:
panic(fmt.Sprintf("ShapeValidation.GoCode, %s's type %s, no min value handling",
sv.Name, sv.Ref.Shape.Type))
}
case ShapeValidationNested:
switch sv.Ref.Shape.Type {
case "map", "list":
err = validationGoCodeTmpls.ExecuteTemplate(w, "nestedMapList", sv)
default:
err = validationGoCodeTmpls.ExecuteTemplate(w, "nestedStruct", sv)
}
default:
panic(fmt.Sprintf("ShapeValidation.GoCode, %s's type %d, unknown validation type",
sv.Name, sv.Type))
}
if err != nil {
panic(fmt.Sprintf("ShapeValidation.GoCode failed, err: %v", err))
}
return w.String()
}
// A ShapeValidations is a collection of shape validations needed nested within
// a parent shape
type ShapeValidations []ShapeValidation
var validateShapeTmpl = template.Must(template.New("ValidateShape").Parse(`
// Validate inspects the fields of the type to determine if they are valid.
func (s *{{ .Shape.ShapeName }}) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "{{ .Shape.ShapeName }}"}
{{ range $_, $v := .Validations -}}
{{ $v.GoCode }}
{{ end }}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
`))
// GoCode generates the Go code needed to perform validations for the
// shape and its nested fields.
func (vs ShapeValidations) GoCode(shape *Shape) string {
buf := &bytes.Buffer{}
validateShapeTmpl.Execute(buf, map[string]interface{}{
"Shape": shape,
"Validations": vs,
})
return buf.String()
}
// Has returns true or false if the ShapeValidations already contains the
// the reference and validation type.
func (vs ShapeValidations) Has(ref *ShapeRef, typ ShapeValidationType) bool {
for _, v := range vs {
if v.Ref == ref && v.Type == typ {
return true
}
}
return false
}
| 170 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/private/protocol"
)
// ShapeValueBuilder provides the logic to build the nested values for a shape.
// Base64BlobValues is true if the blob field in shapeRef.Shape.Type is base64
// encoded.
type ShapeValueBuilder struct {
// Specifies if API shapes modeled as blob types, input values are base64
// encoded or not, and strings values instead.
Base64BlobValues bool
// The helper that will provide the logic and formated code to convert a
// timestamp input value into a Go time.Time.
ParseTimeString func(ref *ShapeRef, memberName, v string) string
}
// NewShapeValueBuilder returns an initialized ShapeValueBuilder for generating
// API shape types initialized with values.
func NewShapeValueBuilder() ShapeValueBuilder {
return ShapeValueBuilder{ParseTimeString: parseUnixTimeString}
}
// BuildShape will recursively build the referenced shape based on the json
// object provided. isMap will dictate how the field name is specified. If
// isMap is true, we will expect the member name to be quotes like "Foo".
func (b ShapeValueBuilder) BuildShape(ref *ShapeRef, shapes map[string]interface{}, isMap bool) string {
order := make([]string, len(shapes))
for k := range shapes {
order = append(order, k)
}
sort.Strings(order)
ret := ""
for _, name := range order {
if name == "" {
continue
}
shape := shapes[name]
// If the shape isn't a map, we want to export the value, since every field
// defined in our shapes are exported.
if len(name) > 0 && !isMap && strings.ToLower(name[0:1]) == name[0:1] {
name = strings.Title(name)
}
memName := name
passRef := ref.Shape.MemberRefs[name]
if isMap {
memName = fmt.Sprintf("%q", memName)
passRef = &ref.Shape.ValueRef
}
switch v := shape.(type) {
case map[string]interface{}:
ret += b.BuildComplex(name, memName, passRef, ref.Shape, v)
case []interface{}:
ret += b.BuildList(name, memName, passRef, v)
default:
ret += b.BuildScalar(name, memName, passRef, v, ref.Shape.Payload == name)
}
}
return ret
}
// BuildList will construct a list shape based off the service's definition of
// that list.
func (b ShapeValueBuilder) BuildList(name, memName string, ref *ShapeRef, v []interface{}) string {
ret := ""
if len(v) == 0 || ref == nil {
return ""
}
passRef := &ref.Shape.MemberRef
ret += fmt.Sprintf("%s: %s {\n", memName, b.GoType(ref, false))
ret += b.buildListElements(passRef, v)
ret += "},\n"
return ret
}
func (b ShapeValueBuilder) buildListElements(ref *ShapeRef, v []interface{}) string {
if len(v) == 0 || ref == nil {
return ""
}
ret := ""
format := ""
isComplex := false
isList := false
// get format for atomic type. If it is not an atomic type,
// get the element.
switch v[0].(type) {
case string:
format = "%s"
case bool:
format = "%t"
case float64:
switch ref.Shape.Type {
case "integer", "int64", "long":
format = "%d"
default:
format = "%f"
}
case []interface{}:
isList = true
case map[string]interface{}:
isComplex = true
}
for _, elem := range v {
if isComplex {
ret += fmt.Sprintf("{\n%s\n},\n", b.BuildShape(ref, elem.(map[string]interface{}), ref.Shape.Type == "map"))
} else if isList {
ret += fmt.Sprintf("{\n%s\n},\n", b.buildListElements(&ref.Shape.MemberRef, elem.([]interface{})))
} else {
switch ref.Shape.Type {
case "integer", "int64", "long":
elem = int(elem.(float64))
}
ret += fmt.Sprintf("%s,\n", getValue(ref.Shape.Type, fmt.Sprintf(format, elem)))
}
}
return ret
}
// BuildScalar will build atomic Go types.
func (b ShapeValueBuilder) BuildScalar(name, memName string, ref *ShapeRef, shape interface{}, isPayload bool) string {
if ref == nil || ref.Shape == nil {
return ""
}
switch v := shape.(type) {
case bool:
return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%t", v))
case int:
if ref.Shape.Type == "timestamp" {
return b.ParseTimeString(ref, memName, fmt.Sprintf("%d", v))
}
return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%d", v))
case float64:
dataType := ref.Shape.Type
if dataType == "timestamp" {
return b.ParseTimeString(ref, memName, fmt.Sprintf("%f", v))
}
if dataType == "integer" || dataType == "int64" || dataType == "long" {
return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%d", int(shape.(float64))))
}
return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%f", v))
case string:
t := ref.Shape.Type
switch t {
case "timestamp":
return b.ParseTimeString(ref, memName, fmt.Sprintf("%s", v))
case "jsonvalue":
return fmt.Sprintf("%s: %#v,\n", memName, parseJSONString(v))
case "blob":
if (ref.Streaming || ref.Shape.Streaming) && isPayload {
return fmt.Sprintf("%s: aws.ReadSeekCloser(strings.NewReader(%q)),\n", memName, v)
}
if b.Base64BlobValues {
decodedBlob, err := base64.StdEncoding.DecodeString(v)
if err != nil {
panic(fmt.Errorf("Failed to decode string: %v", err))
}
return fmt.Sprintf("%s: []byte(%q),\n", memName, decodedBlob)
}
return fmt.Sprintf("%s: []byte(%q),\n", memName, v)
default:
return convertToCorrectType(memName, t, v)
}
default:
panic(fmt.Errorf("Unsupported scalar type: %v", reflect.TypeOf(v)))
}
}
// BuildComplex will build the shape's value for complex types such as structs,
// and maps.
func (b ShapeValueBuilder) BuildComplex(name, memName string, ref *ShapeRef, parent *Shape, v map[string]interface{}) string {
switch parent.Type {
case "structure":
if ref.Shape.Type == "map" {
return fmt.Sprintf(`%s: %s{
%s
},
`, memName, b.GoType(ref, true), b.BuildShape(ref, v, true))
} else {
return fmt.Sprintf(`%s: &%s{
%s
},
`, memName, b.GoType(ref, true), b.BuildShape(ref, v, false))
}
case "map":
if ref.Shape.Type == "map" {
return fmt.Sprintf(`%q: %s{
%s
},
`, name, b.GoType(ref, false), b.BuildShape(ref, v, true))
} else {
return fmt.Sprintf(`%s: &%s{
%s
},
`, memName, b.GoType(ref, true), b.BuildShape(ref, v, false))
}
default:
panic(fmt.Sprintf("Expected complex type but received %q", ref.Shape.Type))
}
}
// GoType returns the string of the shape's Go type identifier.
func (b ShapeValueBuilder) GoType(ref *ShapeRef, elem bool) string {
if ref.Shape.Type != "structure" && ref.Shape.Type != "list" && ref.Shape.Type != "map" {
// Scalars are always pointers.
return ref.GoTypeWithPkgName()
}
prefix := ""
if ref.Shape.Type == "list" {
ref = &ref.Shape.MemberRef
prefix = "[]"
}
if elem {
return prefix + ref.Shape.GoTypeWithPkgNameElem()
}
return prefix + ref.GoTypeWithPkgName()
}
// parseJSONString a json string and returns aws.JSONValue.
func parseJSONString(input string) aws.JSONValue {
var v aws.JSONValue
if err := json.Unmarshal([]byte(input), &v); err != nil {
panic(fmt.Sprintf("unable to unmarshal JSONValue, %v", err))
}
return v
}
// InlineParseModeledTime returns the string of an inline function which
// returns time.
func inlineParseModeledTime(format, v string) string {
const formatTimeTmpl = `func() *time.Time{
v, err := protocol.ParseTime("%s", "%s")
if err != nil {
panic(err)
}
return &v
}()`
return fmt.Sprintf(formatTimeTmpl, format, v)
}
// parseUnixTimeString returns a string which assigns the value of a time
// member using an inline function Defined inline function parses time in
// UnixTimeFormat.
func parseUnixTimeString(ref *ShapeRef, memName, v string) string {
ref.API.AddSDKImport("private/protocol")
return fmt.Sprintf("%s: %s,\n", memName, inlineParseModeledTime(protocol.UnixTimeFormatName, v))
}
| 277 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"encoding/json"
"fmt"
"os"
"text/template"
)
// SmokeTestSuite defines the test suite for smoke tests.
type SmokeTestSuite struct {
Version int `json:"version"`
DefaultRegion string `json:"defaultRegion"`
TestCases []SmokeTestCase `json:"testCases"`
}
// SmokeTestCase provides the definition for a integration smoke test case.
type SmokeTestCase struct {
OpName string `json:"operationName"`
Input map[string]interface{} `json:"input"`
ExpectErr bool `json:"errorExpectedFromService"`
}
// BuildInputShape returns the Go code as a string for initializing the test
// case's input shape.
func (c SmokeTestCase) BuildInputShape(ref *ShapeRef) string {
b := NewShapeValueBuilder()
return fmt.Sprintf("&%s{\n%s\n}",
b.GoType(ref, true),
b.BuildShape(ref, c.Input, false),
)
}
// AttachSmokeTests attaches the smoke test cases to the API model.
func (a *API) AttachSmokeTests(filename string) error {
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf("failed to open smoke tests %s, err: %v", filename, err)
}
defer f.Close()
if err := json.NewDecoder(f).Decode(&a.SmokeTests); err != nil {
return fmt.Errorf("failed to decode smoke tests %s, err: %v", filename, err)
}
if v := a.SmokeTests.Version; v != 1 {
return fmt.Errorf("invalid smoke test version, %d", v)
}
return nil
}
// APISmokeTestsGoCode returns the Go Code string for the smoke tests.
func (a *API) APISmokeTestsGoCode() string {
w := bytes.NewBuffer(nil)
a.resetImports()
a.AddImport("context")
a.AddImport("testing")
a.AddImport("time")
a.AddSDKImport("aws")
a.AddSDKImport("aws/request")
a.AddSDKImport("aws/awserr")
a.AddSDKImport("aws/request")
a.AddSDKImport("awstesting/integration")
a.AddImport(a.ImportPath())
smokeTests := struct {
API *API
SmokeTestSuite
}{
API: a,
SmokeTestSuite: a.SmokeTests,
}
if err := smokeTestTmpl.Execute(w, smokeTests); err != nil {
panic(fmt.Sprintf("failed to create smoke tests, %v", err))
}
ignoreImports := `
var _ aws.Config
var _ awserr.Error
var _ request.Request
`
return a.importsGoCode() + ignoreImports + w.String()
}
var smokeTestTmpl = template.Must(template.New(`smokeTestTmpl`).Parse(`
{{- range $i, $testCase := $.TestCases }}
{{- $op := index $.API.Operations $testCase.OpName }}
func TestInteg_{{ printf "%02d" $i }}_{{ $op.ExportedName }}(t *testing.T) {
ctx, cancelFn := context.WithTimeout(context.Background(), 5 *time.Second)
defer cancelFn()
sess := integration.SessionWithDefaultRegion("{{ $.DefaultRegion }}")
svc := {{ $.API.PackageName }}.New(sess)
params := {{ $testCase.BuildInputShape $op.InputRef }}
_, err := svc.{{ $op.ExportedName }}WithContext(ctx, params, func(r *request.Request) {
r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
})
{{- if $testCase.ExpectErr }}
if err == nil {
t.Fatalf("expect request to fail")
}
aerr, ok := err.(awserr.RequestFailure)
if !ok {
t.Fatalf("expect awserr, was %T", err)
}
if len(aerr.Code()) == 0 {
t.Errorf("expect non-empty error code")
}
if len(aerr.Message()) == 0 {
t.Errorf("expect non-empty error message")
}
if v := aerr.Code(); v == request.ErrCodeSerialization {
t.Errorf("expect API error code got serialization failure")
}
{{- else }}
if err != nil {
t.Errorf("expect no error, got %v", err)
}
{{- end }}
}
{{- end }}
`))
| 130 |
session-manager-plugin | aws | Go | // +build codegen
package api
import (
"bytes"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"text/template"
)
// WaiterAcceptor is the acceptors defined in the model the SDK will use
// to wait on resource states with.
type WaiterAcceptor struct {
State string
Matcher string
Argument string
Expected interface{}
}
// ExpectedString returns the string that was expected by the WaiterAcceptor
func (a *WaiterAcceptor) ExpectedString() string {
switch a.Expected.(type) {
case string:
return fmt.Sprintf("%q", a.Expected)
default:
return fmt.Sprintf("%v", a.Expected)
}
}
// A Waiter is an individual waiter definition.
type Waiter struct {
Name string
Delay int
MaxAttempts int
OperationName string `json:"operation"`
Operation *Operation
Acceptors []WaiterAcceptor
}
// WaitersGoCode generates and returns Go code for each of the waiters of
// this API.
func (a *API) WaitersGoCode() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "import (\n%q\n\n%q\n%q\n)",
"time",
SDKImportRoot+"/aws",
SDKImportRoot+"/aws/request",
)
for _, w := range a.Waiters {
buf.WriteString(w.GoCode())
}
return buf.String()
}
// used for unmarshaling from the waiter JSON file
type waiterDefinitions struct {
*API
Waiters map[string]Waiter
}
// AttachWaiters reads a file of waiter definitions, and adds those to the API.
// Will panic if an error occurs.
func (a *API) AttachWaiters(filename string) error {
p := waiterDefinitions{API: a}
f, err := os.Open(filename)
defer f.Close()
if err != nil {
return err
}
err = json.NewDecoder(f).Decode(&p)
if err != nil {
return err
}
return p.setup()
}
func (p *waiterDefinitions) setup() error {
p.API.Waiters = []Waiter{}
i, keys := 0, make([]string, len(p.Waiters))
for k := range p.Waiters {
keys[i] = k
i++
}
sort.Strings(keys)
for _, n := range keys {
e := p.Waiters[n]
n = p.ExportableName(n)
e.Name = n
e.OperationName = p.ExportableName(e.OperationName)
e.Operation = p.API.Operations[e.OperationName]
if e.Operation == nil {
return fmt.Errorf("unknown operation %s for waiter %s",
e.OperationName, n)
}
p.API.Waiters = append(p.API.Waiters, e)
}
return nil
}
var waiterTmpls = template.Must(template.New("waiterTmpls").Funcs(
template.FuncMap{
"titleCase": func(v string) string {
return strings.Title(v)
},
},
).Parse(`
{{ define "waiter"}}
// WaitUntil{{ .Name }} uses the {{ .Operation.API.NiceName }} API operation
// {{ .OperationName }} to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *{{ .Operation.API.StructName }}) WaitUntil{{ .Name }}(input {{ .Operation.InputRef.GoType }}) error {
return c.WaitUntil{{ .Name }}WithContext(aws.BackgroundContext(), input)
}
// WaitUntil{{ .Name }}WithContext is an extended version of WaitUntil{{ .Name }}.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *{{ .Operation.API.StructName }}) WaitUntil{{ .Name }}WithContext(` +
`ctx aws.Context, input {{ .Operation.InputRef.GoType }}, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntil{{ .Name }}",
MaxAttempts: {{ .MaxAttempts }},
Delay: request.ConstantWaiterDelay({{ .Delay }} * time.Second),
Acceptors: []request.WaiterAcceptor{
{{ range $_, $a := .Acceptors }}{
State: request.{{ titleCase .State }}WaiterState,
Matcher: request.{{ titleCase .Matcher }}WaiterMatch,
{{- if .Argument }}Argument: "{{ .Argument }}",{{ end }}
Expected: {{ .ExpectedString }},
},
{{ end }}
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy {{ .Operation.InputRef.GoType }}
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.{{ .OperationName }}Request(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
{{- end }}
{{ define "waiter interface" }}
WaitUntil{{ .Name }}({{ .Operation.InputRef.GoTypeWithPkgName }}) error
WaitUntil{{ .Name }}WithContext(aws.Context, {{ .Operation.InputRef.GoTypeWithPkgName }}, ...request.WaiterOption) error
{{- end }}
`))
// InterfaceSignature returns a string representing the Waiter's interface
// function signature.
func (w *Waiter) InterfaceSignature() string {
var buf bytes.Buffer
if err := waiterTmpls.ExecuteTemplate(&buf, "waiter interface", w); err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
}
// GoCode returns the generated Go code for an individual waiter.
func (w *Waiter) GoCode() string {
var buf bytes.Buffer
if err := waiterTmpls.ExecuteTemplate(&buf, "waiter", w); err != nil {
panic(err)
}
return buf.String()
}
| 193 |
session-manager-plugin | aws | Go | // Package service contains automatically generated AWS clients.
package service
//go:generate go run -tags codegen ../../../cli/gen-api/main.go -path=../service -svc-import-path "github.com/aws/aws-sdk-go/private/model/api/codegentest/service" ../models/*/*/api-2.json
//go:generate gofmt -s -w ../service
| 6 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package awsendpointdiscoverytest
import (
"fmt"
"net/url"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/crr"
"github.com/aws/aws-sdk-go/aws/request"
)
const opDescribeEndpoints = "DescribeEndpoints"
// DescribeEndpointsRequest generates a "aws/request.Request" representing the
// client's request for the DescribeEndpoints operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeEndpoints for more information on using the DescribeEndpoints
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DescribeEndpointsRequest method.
// req, resp := client.DescribeEndpointsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *AwsEndpointDiscoveryTest) DescribeEndpointsRequest(input *DescribeEndpointsInput) (req *request.Request, output *DescribeEndpointsOutput) {
op := &request.Operation{
Name: opDescribeEndpoints,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &DescribeEndpointsInput{}
}
output = &DescribeEndpointsOutput{}
req = c.newRequest(op, input, output)
return
}
// DescribeEndpoints API operation for AwsEndpointDiscoveryTest.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AwsEndpointDiscoveryTest's
// API operation DescribeEndpoints for usage and error information.
func (c *AwsEndpointDiscoveryTest) DescribeEndpoints(input *DescribeEndpointsInput) (*DescribeEndpointsOutput, error) {
req, out := c.DescribeEndpointsRequest(input)
return out, req.Send()
}
// DescribeEndpointsWithContext is the same as DescribeEndpoints with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeEndpoints for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AwsEndpointDiscoveryTest) DescribeEndpointsWithContext(ctx aws.Context, input *DescribeEndpointsInput, opts ...request.Option) (*DescribeEndpointsOutput, error) {
req, out := c.DescribeEndpointsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type discovererDescribeEndpoints struct {
Client *AwsEndpointDiscoveryTest
Required bool
EndpointCache *crr.EndpointCache
Params map[string]*string
Key string
req *request.Request
}
func (d *discovererDescribeEndpoints) Discover() (crr.Endpoint, error) {
input := &DescribeEndpointsInput{
Operation: d.Params["op"],
}
resp, err := d.Client.DescribeEndpoints(input)
if err != nil {
return crr.Endpoint{}, err
}
endpoint := crr.Endpoint{
Key: d.Key,
}
for _, e := range resp.Endpoints {
if e.Address == nil {
continue
}
address := *e.Address
var scheme string
if idx := strings.Index(address, "://"); idx != -1 {
scheme = address[:idx]
}
if len(scheme) == 0 {
address = fmt.Sprintf("%s://%s", d.req.HTTPRequest.URL.Scheme, address)
}
cachedInMinutes := aws.Int64Value(e.CachePeriodInMinutes)
u, err := url.Parse(address)
if err != nil {
continue
}
addr := crr.WeightedAddress{
URL: u,
Expired: time.Now().Add(time.Duration(cachedInMinutes) * time.Minute),
}
endpoint.Add(addr)
}
d.EndpointCache.Add(endpoint)
return endpoint, nil
}
func (d *discovererDescribeEndpoints) Handler(r *request.Request) {
endpointKey := crr.BuildEndpointKey(d.Params)
d.Key = endpointKey
d.req = r
endpoint, err := d.EndpointCache.Get(d, endpointKey, d.Required)
if err != nil {
r.Error = err
return
}
if endpoint.URL != nil && len(endpoint.URL.String()) > 0 {
r.HTTPRequest.URL = endpoint.URL
}
}
const opTestDiscoveryIdentifiersRequired = "TestDiscoveryIdentifiersRequired"
// TestDiscoveryIdentifiersRequiredRequest generates a "aws/request.Request" representing the
// client's request for the TestDiscoveryIdentifiersRequired operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See TestDiscoveryIdentifiersRequired for more information on using the TestDiscoveryIdentifiersRequired
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the TestDiscoveryIdentifiersRequiredRequest method.
// req, resp := client.TestDiscoveryIdentifiersRequiredRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *AwsEndpointDiscoveryTest) TestDiscoveryIdentifiersRequiredRequest(input *TestDiscoveryIdentifiersRequiredInput) (req *request.Request, output *TestDiscoveryIdentifiersRequiredOutput) {
op := &request.Operation{
Name: opTestDiscoveryIdentifiersRequired,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &TestDiscoveryIdentifiersRequiredInput{}
}
output = &TestDiscoveryIdentifiersRequiredOutput{}
req = c.newRequest(op, input, output)
// if custom endpoint for the request is set to a non empty string,
// we skip the endpoint discovery workflow.
if req.Config.Endpoint == nil || *req.Config.Endpoint == "" {
de := discovererDescribeEndpoints{
Required: true,
EndpointCache: c.endpointCache,
Params: map[string]*string{
"op": aws.String(req.Operation.Name),
"Sdk": input.Sdk,
},
Client: c,
}
for k, v := range de.Params {
if v == nil {
delete(de.Params, k)
}
}
req.Handlers.Build.PushFrontNamed(request.NamedHandler{
Name: "crr.endpointdiscovery",
Fn: de.Handler,
})
}
return
}
// TestDiscoveryIdentifiersRequired API operation for AwsEndpointDiscoveryTest.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AwsEndpointDiscoveryTest's
// API operation TestDiscoveryIdentifiersRequired for usage and error information.
func (c *AwsEndpointDiscoveryTest) TestDiscoveryIdentifiersRequired(input *TestDiscoveryIdentifiersRequiredInput) (*TestDiscoveryIdentifiersRequiredOutput, error) {
req, out := c.TestDiscoveryIdentifiersRequiredRequest(input)
return out, req.Send()
}
// TestDiscoveryIdentifiersRequiredWithContext is the same as TestDiscoveryIdentifiersRequired with the addition of
// the ability to pass a context and additional request options.
//
// See TestDiscoveryIdentifiersRequired for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AwsEndpointDiscoveryTest) TestDiscoveryIdentifiersRequiredWithContext(ctx aws.Context, input *TestDiscoveryIdentifiersRequiredInput, opts ...request.Option) (*TestDiscoveryIdentifiersRequiredOutput, error) {
req, out := c.TestDiscoveryIdentifiersRequiredRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opTestDiscoveryOptional = "TestDiscoveryOptional"
// TestDiscoveryOptionalRequest generates a "aws/request.Request" representing the
// client's request for the TestDiscoveryOptional operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See TestDiscoveryOptional for more information on using the TestDiscoveryOptional
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the TestDiscoveryOptionalRequest method.
// req, resp := client.TestDiscoveryOptionalRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *AwsEndpointDiscoveryTest) TestDiscoveryOptionalRequest(input *TestDiscoveryOptionalInput) (req *request.Request, output *TestDiscoveryOptionalOutput) {
op := &request.Operation{
Name: opTestDiscoveryOptional,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &TestDiscoveryOptionalInput{}
}
output = &TestDiscoveryOptionalOutput{}
req = c.newRequest(op, input, output)
// if custom endpoint for the request is set to a non empty string,
// we skip the endpoint discovery workflow.
if req.Config.Endpoint == nil || *req.Config.Endpoint == "" {
if aws.BoolValue(req.Config.EnableEndpointDiscovery) {
de := discovererDescribeEndpoints{
Required: false,
EndpointCache: c.endpointCache,
Params: map[string]*string{
"op": aws.String(req.Operation.Name),
},
Client: c,
}
for k, v := range de.Params {
if v == nil {
delete(de.Params, k)
}
}
req.Handlers.Build.PushFrontNamed(request.NamedHandler{
Name: "crr.endpointdiscovery",
Fn: de.Handler,
})
}
}
return
}
// TestDiscoveryOptional API operation for AwsEndpointDiscoveryTest.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AwsEndpointDiscoveryTest's
// API operation TestDiscoveryOptional for usage and error information.
func (c *AwsEndpointDiscoveryTest) TestDiscoveryOptional(input *TestDiscoveryOptionalInput) (*TestDiscoveryOptionalOutput, error) {
req, out := c.TestDiscoveryOptionalRequest(input)
return out, req.Send()
}
// TestDiscoveryOptionalWithContext is the same as TestDiscoveryOptional with the addition of
// the ability to pass a context and additional request options.
//
// See TestDiscoveryOptional for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AwsEndpointDiscoveryTest) TestDiscoveryOptionalWithContext(ctx aws.Context, input *TestDiscoveryOptionalInput, opts ...request.Option) (*TestDiscoveryOptionalOutput, error) {
req, out := c.TestDiscoveryOptionalRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opTestDiscoveryRequired = "TestDiscoveryRequired"
// TestDiscoveryRequiredRequest generates a "aws/request.Request" representing the
// client's request for the TestDiscoveryRequired operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See TestDiscoveryRequired for more information on using the TestDiscoveryRequired
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the TestDiscoveryRequiredRequest method.
// req, resp := client.TestDiscoveryRequiredRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *AwsEndpointDiscoveryTest) TestDiscoveryRequiredRequest(input *TestDiscoveryRequiredInput) (req *request.Request, output *TestDiscoveryRequiredOutput) {
op := &request.Operation{
Name: opTestDiscoveryRequired,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &TestDiscoveryRequiredInput{}
}
output = &TestDiscoveryRequiredOutput{}
req = c.newRequest(op, input, output)
// if custom endpoint for the request is set to a non empty string,
// we skip the endpoint discovery workflow.
if req.Config.Endpoint == nil || *req.Config.Endpoint == "" {
if aws.BoolValue(req.Config.EnableEndpointDiscovery) {
de := discovererDescribeEndpoints{
Required: false,
EndpointCache: c.endpointCache,
Params: map[string]*string{
"op": aws.String(req.Operation.Name),
},
Client: c,
}
for k, v := range de.Params {
if v == nil {
delete(de.Params, k)
}
}
req.Handlers.Build.PushFrontNamed(request.NamedHandler{
Name: "crr.endpointdiscovery",
Fn: de.Handler,
})
}
}
return
}
// TestDiscoveryRequired API operation for AwsEndpointDiscoveryTest.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for AwsEndpointDiscoveryTest's
// API operation TestDiscoveryRequired for usage and error information.
func (c *AwsEndpointDiscoveryTest) TestDiscoveryRequired(input *TestDiscoveryRequiredInput) (*TestDiscoveryRequiredOutput, error) {
req, out := c.TestDiscoveryRequiredRequest(input)
return out, req.Send()
}
// TestDiscoveryRequiredWithContext is the same as TestDiscoveryRequired with the addition of
// the ability to pass a context and additional request options.
//
// See TestDiscoveryRequired for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *AwsEndpointDiscoveryTest) TestDiscoveryRequiredWithContext(ctx aws.Context, input *TestDiscoveryRequiredInput, opts ...request.Option) (*TestDiscoveryRequiredOutput, error) {
req, out := c.TestDiscoveryRequiredRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type DescribeEndpointsInput struct {
_ struct{} `type:"structure"`
Operation *string `type:"string"`
}
// String returns the string representation
func (s DescribeEndpointsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DescribeEndpointsInput) GoString() string {
return s.String()
}
// SetOperation sets the Operation field's value.
func (s *DescribeEndpointsInput) SetOperation(v string) *DescribeEndpointsInput {
s.Operation = &v
return s
}
type DescribeEndpointsOutput struct {
_ struct{} `type:"structure"`
// Endpoints is a required field
Endpoints []*Endpoint `type:"list" required:"true"`
}
// String returns the string representation
func (s DescribeEndpointsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DescribeEndpointsOutput) GoString() string {
return s.String()
}
// SetEndpoints sets the Endpoints field's value.
func (s *DescribeEndpointsOutput) SetEndpoints(v []*Endpoint) *DescribeEndpointsOutput {
s.Endpoints = v
return s
}
type Endpoint struct {
_ struct{} `type:"structure"`
// Address is a required field
Address *string `type:"string" required:"true"`
// CachePeriodInMinutes is a required field
CachePeriodInMinutes *int64 `type:"long" required:"true"`
}
// String returns the string representation
func (s Endpoint) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s Endpoint) GoString() string {
return s.String()
}
// SetAddress sets the Address field's value.
func (s *Endpoint) SetAddress(v string) *Endpoint {
s.Address = &v
return s
}
// SetCachePeriodInMinutes sets the CachePeriodInMinutes field's value.
func (s *Endpoint) SetCachePeriodInMinutes(v int64) *Endpoint {
s.CachePeriodInMinutes = &v
return s
}
type TestDiscoveryIdentifiersRequiredInput struct {
_ struct{} `type:"structure"`
// Sdk is a required field
Sdk *string `type:"string" required:"true"`
}
// String returns the string representation
func (s TestDiscoveryIdentifiersRequiredInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TestDiscoveryIdentifiersRequiredInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TestDiscoveryIdentifiersRequiredInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TestDiscoveryIdentifiersRequiredInput"}
if s.Sdk == nil {
invalidParams.Add(request.NewErrParamRequired("Sdk"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetSdk sets the Sdk field's value.
func (s *TestDiscoveryIdentifiersRequiredInput) SetSdk(v string) *TestDiscoveryIdentifiersRequiredInput {
s.Sdk = &v
return s
}
type TestDiscoveryIdentifiersRequiredOutput struct {
_ struct{} `type:"structure"`
RequestSuccessful *bool `type:"boolean"`
}
// String returns the string representation
func (s TestDiscoveryIdentifiersRequiredOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TestDiscoveryIdentifiersRequiredOutput) GoString() string {
return s.String()
}
// SetRequestSuccessful sets the RequestSuccessful field's value.
func (s *TestDiscoveryIdentifiersRequiredOutput) SetRequestSuccessful(v bool) *TestDiscoveryIdentifiersRequiredOutput {
s.RequestSuccessful = &v
return s
}
type TestDiscoveryOptionalInput struct {
_ struct{} `type:"structure"`
Sdk *string `type:"string"`
}
// String returns the string representation
func (s TestDiscoveryOptionalInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TestDiscoveryOptionalInput) GoString() string {
return s.String()
}
// SetSdk sets the Sdk field's value.
func (s *TestDiscoveryOptionalInput) SetSdk(v string) *TestDiscoveryOptionalInput {
s.Sdk = &v
return s
}
type TestDiscoveryOptionalOutput struct {
_ struct{} `type:"structure"`
RequestSuccessful *bool `type:"boolean"`
}
// String returns the string representation
func (s TestDiscoveryOptionalOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TestDiscoveryOptionalOutput) GoString() string {
return s.String()
}
// SetRequestSuccessful sets the RequestSuccessful field's value.
func (s *TestDiscoveryOptionalOutput) SetRequestSuccessful(v bool) *TestDiscoveryOptionalOutput {
s.RequestSuccessful = &v
return s
}
type TestDiscoveryRequiredInput struct {
_ struct{} `type:"structure"`
Sdk *string `type:"string"`
}
// String returns the string representation
func (s TestDiscoveryRequiredInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TestDiscoveryRequiredInput) GoString() string {
return s.String()
}
// SetSdk sets the Sdk field's value.
func (s *TestDiscoveryRequiredInput) SetSdk(v string) *TestDiscoveryRequiredInput {
s.Sdk = &v
return s
}
type TestDiscoveryRequiredOutput struct {
_ struct{} `type:"structure"`
RequestSuccessful *bool `type:"boolean"`
}
// String returns the string representation
func (s TestDiscoveryRequiredOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TestDiscoveryRequiredOutput) GoString() string {
return s.String()
}
// SetRequestSuccessful sets the RequestSuccessful field's value.
func (s *TestDiscoveryRequiredOutput) SetRequestSuccessful(v bool) *TestDiscoveryRequiredOutput {
s.RequestSuccessful = &v
return s
}
| 663 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package awsendpointdiscoverytest provides the client and types for making API
// requests to AwsEndpointDiscoveryTest.
//
// See awsendpointdiscoverytest package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/awsendpointdiscoverytest/
//
// Using the Client
//
// To contact AwsEndpointDiscoveryTest with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the AwsEndpointDiscoveryTest client AwsEndpointDiscoveryTest for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/awsendpointdiscoverytest/#New
package awsendpointdiscoverytest
| 25 |
session-manager-plugin | aws | Go | // +build go1.7
package awsendpointdiscoverytest
import (
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting/unit"
)
func TestEndpointDiscoveryWithCustomEndpoint(t *testing.T) {
mockEndpointResolver := endpoints.ResolverFunc(func(service string, region string, opts ...func(options *endpoints.Options)) (endpoints.ResolvedEndpoint, error) {
return endpoints.ResolvedEndpoint{
URL: "https://mockEndpointForDiscovery",
}, nil
})
cases := map[string]struct {
hasDiscoveryEnabled bool
hasCustomEndpoint bool
isOperationRequired bool
customEndpoint string
expectedEndpoint string
}{
"HasCustomEndpoint_RequiredOperation": {
hasDiscoveryEnabled: true,
hasCustomEndpoint: true,
isOperationRequired: true,
customEndpoint: "https://mockCustomEndpoint",
expectedEndpoint: "https://mockCustomEndpoint/",
},
"HasCustomEndpoint_OptionalOperation": {
hasDiscoveryEnabled: true,
hasCustomEndpoint: true,
customEndpoint: "https://mockCustomEndpoint",
expectedEndpoint: "https://mockCustomEndpoint/",
},
"NoCustomEndpoint_DiscoveryDisabled": {
expectedEndpoint: "https://mockEndpointForDiscovery/",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
cfg := &aws.Config{
EnableEndpointDiscovery: aws.Bool(c.hasDiscoveryEnabled),
EndpointResolver: mockEndpointResolver,
}
if c.hasCustomEndpoint {
cfg.Endpoint = aws.String(c.customEndpoint)
}
svc := New(unit.Session, cfg)
svc.Handlers.Clear()
// Add a handler to verify no call goes to DescribeEndpoints operation
svc.Handlers.Send.PushBack(func(r *request.Request) {
if ne, a := opDescribeEndpoints, r.Operation.Name; strings.EqualFold(ne, a) {
t.Errorf("expected no call to %q operation", a)
}
})
var req *request.Request
if c.isOperationRequired {
req, _ = svc.TestDiscoveryIdentifiersRequiredRequest(
&TestDiscoveryIdentifiersRequiredInput{
Sdk: aws.String("sdk"),
},
)
} else {
req, _ = svc.TestDiscoveryOptionalRequest(
&TestDiscoveryOptionalInput{
Sdk: aws.String("sdk"),
},
)
}
req.Handlers.Send.PushBack(func(r *request.Request) {
if e, a := c.expectedEndpoint, r.HTTPRequest.URL.String(); e != a {
t.Errorf("expected %q, but received %q", e, a)
}
})
if err := req.Send(); err != nil {
t.Fatal(err)
}
})
}
}
func TestEndpointDiscoveryWithAttemptedDiscovery(t *testing.T) {
mockEndpointResolver := endpoints.ResolverFunc(func(service string, region string, opts ...func(options *endpoints.Options)) (endpoints.ResolvedEndpoint, error) {
return endpoints.ResolvedEndpoint{
URL: "https://mockEndpointForDiscovery",
}, nil
})
cases := map[string]struct {
hasDiscoveryEnabled bool
hasCustomEndpoint bool
isOperationRequired bool
customEndpoint string
expectedEndpoint string
}{
"NoCustomEndpoint_RequiredOperation": {
hasDiscoveryEnabled: true,
isOperationRequired: true,
expectedEndpoint: "https://mockEndpointForDiscovery/",
},
"NoCustomEndpoint_OptionalOperation": {
hasDiscoveryEnabled: true,
expectedEndpoint: "https://mockEndpointForDiscovery/",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
cfg := &aws.Config{
EnableEndpointDiscovery: aws.Bool(c.hasDiscoveryEnabled),
EndpointResolver: mockEndpointResolver,
}
if c.hasCustomEndpoint {
cfg.Endpoint = aws.String(c.customEndpoint)
}
svc := New(unit.Session, cfg)
svc.Handlers.Clear()
req, _ := svc.TestDiscoveryIdentifiersRequiredRequest(
&TestDiscoveryIdentifiersRequiredInput{
Sdk: aws.String("sdk"),
},
)
svc.Handlers.Send.PushBack(func(r *request.Request) {
if e, a := opDescribeEndpoints, r.Operation.Name; e != a {
t.Fatalf("expected operaton to be %q, called %q instead", e, a)
}
})
req.Handlers.Send.PushBack(func(r *request.Request) {
if e, a := c.expectedEndpoint, r.HTTPRequest.URL.String(); e != a {
t.Errorf("expected %q, but received %q", e, a)
}
})
if err := req.Send(); err != nil {
t.Fatal(err)
}
})
}
}
func TestEndpointDiscovery(t *testing.T) {
svc := New(unit.Session, &aws.Config{
EnableEndpointDiscovery: aws.Bool(true),
})
svc.Handlers.Clear()
svc.Handlers.Send.PushBack(mockSendDescEndpoint("http://foo"))
var descCount int32
svc.Handlers.Complete.PushBack(func(r *request.Request) {
if r.Operation.Name != opDescribeEndpoints {
return
}
atomic.AddInt32(&descCount, 1)
})
for i := 0; i < 2; i++ {
req, _ := svc.TestDiscoveryIdentifiersRequiredRequest(
&TestDiscoveryIdentifiersRequiredInput{
Sdk: aws.String("sdk"),
},
)
req.Handlers.Send.PushBack(func(r *request.Request) {
if e, a := "http://foo", r.HTTPRequest.URL.String(); e != a {
t.Errorf("expected %q, but received %q", e, a)
}
})
if err := req.Send(); err != nil {
t.Fatal(err)
}
}
if e, a := int32(1), atomic.LoadInt32(&descCount); e != a {
t.Errorf("expect desc endpoint called %d, got %d", e, a)
}
}
func TestAsyncEndpointDiscovery(t *testing.T) {
t.Parallel()
svc := New(unit.Session, &aws.Config{
EnableEndpointDiscovery: aws.Bool(true),
})
svc.Handlers.Clear()
var firstAsyncReq sync.WaitGroup
firstAsyncReq.Add(1)
svc.Handlers.Build.PushBack(func(r *request.Request) {
if r.Operation.Name == opDescribeEndpoints {
firstAsyncReq.Wait()
}
})
svc.Handlers.Send.PushBack(mockSendDescEndpoint("http://foo"))
req, _ := svc.TestDiscoveryOptionalRequest(&TestDiscoveryOptionalInput{
Sdk: aws.String("sdk"),
})
const clientHost = "awsendpointdiscoverytestservice.mock-region.amazonaws.com"
req.Handlers.Send.PushBack(func(r *request.Request) {
if e, a := clientHost, r.HTTPRequest.URL.Host; e != a {
t.Errorf("expected %q, but received %q", e, a)
}
})
req.Handlers.Complete.PushBack(func(r *request.Request) {
firstAsyncReq.Done()
})
if err := req.Send(); err != nil {
t.Fatal(err)
}
var cacheUpdated bool
for s := time.Now().Add(10 * time.Second); s.After(time.Now()); {
// Wait for the cache to be updated before making second request.
if svc.endpointCache.Has(req.Operation.Name) {
cacheUpdated = true
break
}
time.Sleep(10 * time.Millisecond)
}
if !cacheUpdated {
t.Fatalf("expect endpoint cache to be updated, was not")
}
req, _ = svc.TestDiscoveryOptionalRequest(&TestDiscoveryOptionalInput{
Sdk: aws.String("sdk"),
})
req.Handlers.Send.PushBack(func(r *request.Request) {
if e, a := "http://foo", r.HTTPRequest.URL.String(); e != a {
t.Errorf("expected %q, but received %q", e, a)
}
})
if err := req.Send(); err != nil {
t.Fatal(err)
}
}
func TestEndpointDiscovery_EndpointScheme(t *testing.T) {
cases := []struct {
address string
expectedAddress string
err string
}{
0: {
address: "https://foo",
expectedAddress: "https://foo",
},
1: {
address: "bar",
expectedAddress: "https://bar",
},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
svc := New(unit.Session, &aws.Config{
EnableEndpointDiscovery: aws.Bool(true),
})
svc.Handlers.Clear()
svc.Handlers.Send.PushBack(mockSendDescEndpoint(c.address))
for i := 0; i < 2; i++ {
req, _ := svc.TestDiscoveryIdentifiersRequiredRequest(
&TestDiscoveryIdentifiersRequiredInput{
Sdk: aws.String("sdk"),
},
)
req.Handlers.Send.PushBack(func(r *request.Request) {
if len(c.err) == 0 {
if e, a := c.expectedAddress, r.HTTPRequest.URL.String(); e != a {
t.Errorf("expected %q, but received %q", e, a)
}
}
})
err := req.Send()
if err != nil && len(c.err) == 0 {
t.Fatalf("expected no error, got %v", err)
} else if err == nil && len(c.err) > 0 {
t.Fatalf("expected error, got none")
} else if err != nil && len(c.err) > 0 {
if e, a := c.err, err.Error(); !strings.Contains(a, e) {
t.Fatalf("expected %v, got %v", c.err, err)
}
}
}
})
}
}
func removeHandlers(h request.Handlers, removeSendHandlers bool) request.Handlers {
if removeSendHandlers {
h.Send.Clear()
}
h.Unmarshal.Clear()
h.UnmarshalStream.Clear()
h.UnmarshalMeta.Clear()
h.UnmarshalError.Clear()
h.Validate.Clear()
h.Complete.Clear()
h.ValidateResponse.Clear()
return h
}
func mockSendDescEndpoint(address string) func(r *request.Request) {
return func(r *request.Request) {
if r.Operation.Name != opDescribeEndpoints {
return
}
out, _ := r.Data.(*DescribeEndpointsOutput)
out.Endpoints = []*Endpoint{
{
Address: &address,
CachePeriodInMinutes: aws.Int64(5),
},
}
r.Data = out
}
}
| 337 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package awsendpointdiscoverytest
import (
"github.com/aws/aws-sdk-go/private/protocol"
)
var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{}
| 10 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package awsendpointdiscoverytest
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/crr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)
// AwsEndpointDiscoveryTest provides the API operation methods for making requests to
// AwsEndpointDiscoveryTest. See this package's package overview docs
// for details on the service.
//
// AwsEndpointDiscoveryTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type AwsEndpointDiscoveryTest struct {
*client.Client
endpointCache *crr.EndpointCache
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "AwsEndpointDiscoveryTest" // Name of service.
EndpointsID = "awsendpointdiscoverytestservice" // ID to lookup a service endpoint with.
ServiceID = "AwsEndpointDiscoveryTest" // ServiceID is a unique identifier of a specific service.
)
// New creates a new instance of the AwsEndpointDiscoveryTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a AwsEndpointDiscoveryTest client from just a session.
// svc := awsendpointdiscoverytest.New(mySession)
//
// // Create a AwsEndpointDiscoveryTest client with additional configuration
// svc := awsendpointdiscoverytest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *AwsEndpointDiscoveryTest {
c := p.ClientConfig(EndpointsID, cfgs...)
if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = "awsendpointdiscoverytestservice"
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *AwsEndpointDiscoveryTest {
svc := &AwsEndpointDiscoveryTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2018-08-31",
JSONVersion: "1.1",
TargetPrefix: "AwsEndpointDiscoveryTestService",
},
handlers,
),
}
svc.endpointCache = crr.NewEndpointCache(10)
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a AwsEndpointDiscoveryTest operation and runs any
// custom request initialization.
func (c *AwsEndpointDiscoveryTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
| 107 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package awsendpointdiscoverytestiface provides an interface to enable mocking the AwsEndpointDiscoveryTest service client
// for testing your code.
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters.
package awsendpointdiscoverytestiface
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/model/api/codegentest/service/awsendpointdiscoverytest"
)
// AwsEndpointDiscoveryTestAPI provides an interface to enable mocking the
// awsendpointdiscoverytest.AwsEndpointDiscoveryTest service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
// // myFunc uses an SDK service client to make a request to
// // AwsEndpointDiscoveryTest.
// func myFunc(svc awsendpointdiscoverytestiface.AwsEndpointDiscoveryTestAPI) bool {
// // Make svc.DescribeEndpoints request
// }
//
// func main() {
// sess := session.New()
// svc := awsendpointdiscoverytest.New(sess)
//
// myFunc(svc)
// }
//
// In your _test.go file:
//
// // Define a mock struct to be used in your unit tests of myFunc.
// type mockAwsEndpointDiscoveryTestClient struct {
// awsendpointdiscoverytestiface.AwsEndpointDiscoveryTestAPI
// }
// func (m *mockAwsEndpointDiscoveryTestClient) DescribeEndpoints(input *awsendpointdiscoverytest.DescribeEndpointsInput) (*awsendpointdiscoverytest.DescribeEndpointsOutput, error) {
// // mock response/functionality
// }
//
// func TestMyFunc(t *testing.T) {
// // Setup Test
// mockSvc := &mockAwsEndpointDiscoveryTestClient{}
//
// myfunc(mockSvc)
//
// // Verify myFunc's functionality
// }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type AwsEndpointDiscoveryTestAPI interface {
DescribeEndpoints(*awsendpointdiscoverytest.DescribeEndpointsInput) (*awsendpointdiscoverytest.DescribeEndpointsOutput, error)
DescribeEndpointsWithContext(aws.Context, *awsendpointdiscoverytest.DescribeEndpointsInput, ...request.Option) (*awsendpointdiscoverytest.DescribeEndpointsOutput, error)
DescribeEndpointsRequest(*awsendpointdiscoverytest.DescribeEndpointsInput) (*request.Request, *awsendpointdiscoverytest.DescribeEndpointsOutput)
TestDiscoveryIdentifiersRequired(*awsendpointdiscoverytest.TestDiscoveryIdentifiersRequiredInput) (*awsendpointdiscoverytest.TestDiscoveryIdentifiersRequiredOutput, error)
TestDiscoveryIdentifiersRequiredWithContext(aws.Context, *awsendpointdiscoverytest.TestDiscoveryIdentifiersRequiredInput, ...request.Option) (*awsendpointdiscoverytest.TestDiscoveryIdentifiersRequiredOutput, error)
TestDiscoveryIdentifiersRequiredRequest(*awsendpointdiscoverytest.TestDiscoveryIdentifiersRequiredInput) (*request.Request, *awsendpointdiscoverytest.TestDiscoveryIdentifiersRequiredOutput)
TestDiscoveryOptional(*awsendpointdiscoverytest.TestDiscoveryOptionalInput) (*awsendpointdiscoverytest.TestDiscoveryOptionalOutput, error)
TestDiscoveryOptionalWithContext(aws.Context, *awsendpointdiscoverytest.TestDiscoveryOptionalInput, ...request.Option) (*awsendpointdiscoverytest.TestDiscoveryOptionalOutput, error)
TestDiscoveryOptionalRequest(*awsendpointdiscoverytest.TestDiscoveryOptionalInput) (*request.Request, *awsendpointdiscoverytest.TestDiscoveryOptionalOutput)
TestDiscoveryRequired(*awsendpointdiscoverytest.TestDiscoveryRequiredInput) (*awsendpointdiscoverytest.TestDiscoveryRequiredOutput, error)
TestDiscoveryRequiredWithContext(aws.Context, *awsendpointdiscoverytest.TestDiscoveryRequiredInput, ...request.Option) (*awsendpointdiscoverytest.TestDiscoveryRequiredOutput, error)
TestDiscoveryRequiredRequest(*awsendpointdiscoverytest.TestDiscoveryRequiredInput) (*request.Request, *awsendpointdiscoverytest.TestDiscoveryRequiredOutput)
}
var _ AwsEndpointDiscoveryTestAPI = (*awsendpointdiscoverytest.AwsEndpointDiscoveryTest)(nil)
| 81 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package restjsonservice
import (
"bytes"
"fmt"
"io"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi"
"github.com/aws/aws-sdk-go/private/protocol/rest"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
const opEmptyStream = "EmptyStream"
// EmptyStreamRequest generates a "aws/request.Request" representing the
// client's request for the EmptyStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See EmptyStream for more information on using the EmptyStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the EmptyStreamRequest method.
// req, resp := client.EmptyStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00/EmptyStream
func (c *RESTJSONService) EmptyStreamRequest(input *EmptyStreamInput) (req *request.Request, output *EmptyStreamOutput) {
op := &request.Operation{
Name: opEmptyStream,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &EmptyStreamInput{}
}
output = &EmptyStreamOutput{}
req = c.newRequest(op, input, output)
es := NewEmptyStreamEventStream()
output.eventStream = es
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
return
}
// EmptyStream API operation for REST JSON Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for REST JSON Service's
// API operation EmptyStream for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00/EmptyStream
func (c *RESTJSONService) EmptyStream(input *EmptyStreamInput) (*EmptyStreamOutput, error) {
req, out := c.EmptyStreamRequest(input)
return out, req.Send()
}
// EmptyStreamWithContext is the same as EmptyStream with the addition of
// the ability to pass a context and additional request options.
//
// See EmptyStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RESTJSONService) EmptyStreamWithContext(ctx aws.Context, input *EmptyStreamInput, opts ...request.Option) (*EmptyStreamOutput, error) {
req, out := c.EmptyStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
var _ awserr.Error
// EmptyStreamEventStream provides the event stream handling for the EmptyStream.
//
// For testing and mocking the event stream this type should be initialized via
// the NewEmptyStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type EmptyStreamEventStream struct {
// Reader is the EventStream reader for the EmptyEventStream
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader EmptyEventStreamReader
outputReader io.ReadCloser
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// NewEmptyStreamEventStream initializes an EmptyStreamEventStream.
// This function should only be used for testing and mocking the EmptyStreamEventStream
// stream within your application.
//
// The Reader member must be set before reading events from the stream.
//
// es := NewEmptyStreamEventStream(func(o *EmptyStreamEventStream{
// es.Reader = myMockStreamReader
// })
func NewEmptyStreamEventStream(opts ...func(*EmptyStreamEventStream)) *EmptyStreamEventStream {
es := &EmptyStreamEventStream{
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
func (es *EmptyStreamEventStream) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *EmptyStreamEventStream) waitStreamPartClose() {
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <-chan struct{}
if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
outputClosedCh = v.Closed()
}
select {
case <-es.done:
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
}
}
// Events returns a channel to read events from.
//
// These events are:
//
// * EmptyEventStreamUnknownEvent
func (es *EmptyStreamEventStream) Events() <-chan EmptyEventStreamEvent {
return es.Reader.Events()
}
func (es *EmptyStreamEventStream) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := unmarshalerForEmptyEventStreamEvent{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = newReadEmptyEventStream(eventReader)
}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
//
func (es *EmptyStreamEventStream) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *EmptyStreamEventStream) safeClose() {
if es.done != nil {
close(es.done)
}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *EmptyStreamEventStream) Err() error {
if err := es.err.Err(); err != nil {
return err
}
if err := es.Reader.Err(); err != nil {
return err
}
return nil
}
const opGetEventStream = "GetEventStream"
// GetEventStreamRequest generates a "aws/request.Request" representing the
// client's request for the GetEventStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetEventStream for more information on using the GetEventStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetEventStreamRequest method.
// req, resp := client.GetEventStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00/GetEventStream
func (c *RESTJSONService) GetEventStreamRequest(input *GetEventStreamInput) (req *request.Request, output *GetEventStreamOutput) {
op := &request.Operation{
Name: opGetEventStream,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &GetEventStreamInput{}
}
output = &GetEventStreamOutput{}
req = c.newRequest(op, input, output)
es := NewGetEventStreamEventStream()
output.eventStream = es
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
return
}
// GetEventStream API operation for REST JSON Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for REST JSON Service's
// API operation GetEventStream for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00/GetEventStream
func (c *RESTJSONService) GetEventStream(input *GetEventStreamInput) (*GetEventStreamOutput, error) {
req, out := c.GetEventStreamRequest(input)
return out, req.Send()
}
// GetEventStreamWithContext is the same as GetEventStream with the addition of
// the ability to pass a context and additional request options.
//
// See GetEventStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RESTJSONService) GetEventStreamWithContext(ctx aws.Context, input *GetEventStreamInput, opts ...request.Option) (*GetEventStreamOutput, error) {
req, out := c.GetEventStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
var _ awserr.Error
// GetEventStreamEventStream provides the event stream handling for the GetEventStream.
//
// For testing and mocking the event stream this type should be initialized via
// the NewGetEventStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type GetEventStreamEventStream struct {
// Reader is the EventStream reader for the EventStream
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader EventStreamReader
outputReader io.ReadCloser
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// NewGetEventStreamEventStream initializes an GetEventStreamEventStream.
// This function should only be used for testing and mocking the GetEventStreamEventStream
// stream within your application.
//
// The Reader member must be set before reading events from the stream.
//
// es := NewGetEventStreamEventStream(func(o *GetEventStreamEventStream{
// es.Reader = myMockStreamReader
// })
func NewGetEventStreamEventStream(opts ...func(*GetEventStreamEventStream)) *GetEventStreamEventStream {
es := &GetEventStreamEventStream{
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
func (es *GetEventStreamEventStream) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *GetEventStreamEventStream) waitStreamPartClose() {
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <-chan struct{}
if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
outputClosedCh = v.Closed()
}
select {
case <-es.done:
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
}
}
// Events returns a channel to read events from.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
// * EventStreamUnknownEvent
func (es *GetEventStreamEventStream) Events() <-chan EventStreamEvent {
return es.Reader.Events()
}
func (es *GetEventStreamEventStream) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := unmarshalerForEventStreamEvent{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = newReadEventStream(eventReader)
}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
//
func (es *GetEventStreamEventStream) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *GetEventStreamEventStream) safeClose() {
if es.done != nil {
close(es.done)
}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *GetEventStreamEventStream) Err() error {
if err := es.err.Err(); err != nil {
return err
}
if err := es.Reader.Err(); err != nil {
return err
}
return nil
}
const opOtherOperation = "OtherOperation"
// OtherOperationRequest generates a "aws/request.Request" representing the
// client's request for the OtherOperation operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OtherOperation for more information on using the OtherOperation
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OtherOperationRequest method.
// req, resp := client.OtherOperationRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00/OtherOperation
func (c *RESTJSONService) OtherOperationRequest(input *OtherOperationInput) (req *request.Request, output *OtherOperationOutput) {
op := &request.Operation{
Name: opOtherOperation,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &OtherOperationInput{}
}
output = &OtherOperationOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// OtherOperation API operation for REST JSON Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for REST JSON Service's
// API operation OtherOperation for usage and error information.
//
// Returned Error Types:
// * ExceptionEvent2
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00/OtherOperation
func (c *RESTJSONService) OtherOperation(input *OtherOperationInput) (*OtherOperationOutput, error) {
req, out := c.OtherOperationRequest(input)
return out, req.Send()
}
// OtherOperationWithContext is the same as OtherOperation with the addition of
// the ability to pass a context and additional request options.
//
// See OtherOperation for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RESTJSONService) OtherOperationWithContext(ctx aws.Context, input *OtherOperationInput, opts ...request.Option) (*OtherOperationOutput, error) {
req, out := c.OtherOperationRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type EmptyEvent struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s EmptyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyEvent) GoString() string {
return s.String()
}
// The EmptyEvent is and event in the EventStream group of events.
func (s *EmptyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *EmptyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *EmptyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
return msg, err
}
// EmptyEventStreamEvent groups together all EventStream
// events writes for EmptyEventStream.
//
// These events are:
//
type EmptyEventStreamEvent interface {
eventEmptyEventStream()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
// EmptyEventStreamReader provides the interface for reading to the stream. The
// default implementation for this interface will be EmptyEventStream.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
//
// * EmptyEventStreamUnknownEvent
type EmptyEventStreamReader interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan EmptyEventStreamEvent
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type readEmptyEventStream struct {
eventReader *eventstreamapi.EventReader
stream chan EmptyEventStreamEvent
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func newReadEmptyEventStream(eventReader *eventstreamapi.EventReader) *readEmptyEventStream {
r := &readEmptyEventStream{
eventReader: eventReader,
stream: make(chan EmptyEventStreamEvent),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *readEmptyEventStream) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *readEmptyEventStream) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *readEmptyEventStream) Closed() <-chan struct{} {
return r.done
}
func (r *readEmptyEventStream) safeClose() {
close(r.done)
}
func (r *readEmptyEventStream) Err() error {
return r.err.Err()
}
func (r *readEmptyEventStream) Events() <-chan EmptyEventStreamEvent {
return r.stream
}
func (r *readEmptyEventStream) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.(EmptyEventStreamEvent):
case <-r.done:
return
}
}
}
type unmarshalerForEmptyEventStreamEvent struct {
metadata protocol.ResponseMetadata
}
func (u unmarshalerForEmptyEventStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
default:
return &EmptyEventStreamUnknownEvent{Type: eventType}, nil
}
}
// EmptyEventStreamUnknownEvent provides a failsafe event for the
// EmptyEventStream group of events when an unknown event is received.
type EmptyEventStreamUnknownEvent struct {
Type string
Message eventstream.Message
}
// The EmptyEventStreamUnknownEvent is and event in the EmptyEventStream
// group of events.
func (s *EmptyEventStreamUnknownEvent) eventEmptyEventStream() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *EmptyEventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyEventStream value.
// This method is only used internally within the SDK's EventStream handling.
func (e *EmptyEventStreamUnknownEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
type EmptyStreamInput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s EmptyStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyStreamInput) GoString() string {
return s.String()
}
type EmptyStreamOutput struct {
_ struct{} `type:"structure"`
eventStream *EmptyStreamEventStream
}
// String returns the string representation
func (s EmptyStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyStreamOutput) GoString() string {
return s.String()
}
// GetStream returns the type to interact with the event stream.
func (s *EmptyStreamOutput) GetStream() *EmptyStreamEventStream {
return s.eventStream
}
// EventStreamEvent groups together all EventStream
// events writes for EventStream.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
type EventStreamEvent interface {
eventEventStream()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
// EventStreamReader provides the interface for reading to the stream. The
// default implementation for this interface will be EventStream.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
// * EventStreamUnknownEvent
type EventStreamReader interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan EventStreamEvent
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type readEventStream struct {
eventReader *eventstreamapi.EventReader
stream chan EventStreamEvent
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func newReadEventStream(eventReader *eventstreamapi.EventReader) *readEventStream {
r := &readEventStream{
eventReader: eventReader,
stream: make(chan EventStreamEvent),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *readEventStream) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *readEventStream) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *readEventStream) Closed() <-chan struct{} {
return r.done
}
func (r *readEventStream) safeClose() {
close(r.done)
}
func (r *readEventStream) Err() error {
return r.err.Err()
}
func (r *readEventStream) Events() <-chan EventStreamEvent {
return r.stream
}
func (r *readEventStream) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.(EventStreamEvent):
case <-r.done:
return
}
}
}
type unmarshalerForEventStreamEvent struct {
metadata protocol.ResponseMetadata
}
func (u unmarshalerForEventStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
case "Empty":
return &EmptyEvent{}, nil
case "ExplicitPayload":
return &ExplicitPayloadEvent{}, nil
case "Headers":
return &HeaderOnlyEvent{}, nil
case "ImplicitPayload":
return &ImplicitPayloadEvent{}, nil
case "PayloadOnly":
return &PayloadOnlyEvent{}, nil
case "PayloadOnlyBlob":
return &PayloadOnlyBlobEvent{}, nil
case "PayloadOnlyString":
return &PayloadOnlyStringEvent{}, nil
case "Exception":
return newErrorExceptionEvent(u.metadata).(eventstreamapi.Unmarshaler), nil
case "Exception2":
return newErrorExceptionEvent2(u.metadata).(eventstreamapi.Unmarshaler), nil
default:
return &EventStreamUnknownEvent{Type: eventType}, nil
}
}
// EventStreamUnknownEvent provides a failsafe event for the
// EventStream group of events when an unknown event is received.
type EventStreamUnknownEvent struct {
Type string
Message eventstream.Message
}
// The EventStreamUnknownEvent is and event in the EventStream
// group of events.
func (s *EventStreamUnknownEvent) eventEventStream() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *EventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the EventStream value.
// This method is only used internally within the SDK's EventStream handling.
func (e *EventStreamUnknownEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
type ExceptionEvent struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
IntVal *int64 `type:"integer"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation
func (s ExceptionEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExceptionEvent) GoString() string {
return s.String()
}
// The ExceptionEvent is and event in the EventStream group of events.
func (s *ExceptionEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExceptionEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
func newErrorExceptionEvent(v protocol.ResponseMetadata) error {
return &ExceptionEvent{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ExceptionEvent) Code() string {
return "ExceptionEvent"
}
// Message returns the exception's message.
func (s *ExceptionEvent) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ExceptionEvent) OrigErr() error {
return nil
}
func (s *ExceptionEvent) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ExceptionEvent) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ExceptionEvent) RequestID() string {
return s.RespMetadata.RequestID
}
type ExceptionEvent2 struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation
func (s ExceptionEvent2) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExceptionEvent2) GoString() string {
return s.String()
}
// The ExceptionEvent2 is and event in the EventStream group of events.
func (s *ExceptionEvent2) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExceptionEvent2 value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent2) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent2) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
func newErrorExceptionEvent2(v protocol.ResponseMetadata) error {
return &ExceptionEvent2{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ExceptionEvent2) Code() string {
return "ExceptionEvent2"
}
// Message returns the exception's message.
func (s *ExceptionEvent2) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ExceptionEvent2) OrigErr() error {
return nil
}
func (s *ExceptionEvent2) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ExceptionEvent2) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ExceptionEvent2) RequestID() string {
return s.RespMetadata.RequestID
}
type ExplicitPayloadEvent struct {
_ struct{} `type:"structure" payload:"NestedVal"`
LongVal *int64 `location:"header" type:"long"`
NestedVal *NestedShape `locationName:"NestedVal" type:"structure"`
StringVal *string `location:"header" type:"string"`
}
// String returns the string representation
func (s ExplicitPayloadEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExplicitPayloadEvent) GoString() string {
return s.String()
}
// SetLongVal sets the LongVal field's value.
func (s *ExplicitPayloadEvent) SetLongVal(v int64) *ExplicitPayloadEvent {
s.LongVal = &v
return s
}
// SetNestedVal sets the NestedVal field's value.
func (s *ExplicitPayloadEvent) SetNestedVal(v *NestedShape) *ExplicitPayloadEvent {
s.NestedVal = v
return s
}
// SetStringVal sets the StringVal field's value.
func (s *ExplicitPayloadEvent) SetStringVal(v string) *ExplicitPayloadEvent {
s.StringVal = &v
return s
}
// The ExplicitPayloadEvent is and event in the EventStream group of events.
func (s *ExplicitPayloadEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExplicitPayloadEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExplicitPayloadEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("LongVal"); hv != nil {
v := hv.Get().(int64)
s.LongVal = &v
}
if hv := msg.Headers.Get("StringVal"); hv != nil {
v := hv.Get().(string)
s.StringVal = &v
}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExplicitPayloadEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("LongVal", eventstream.Int64Value(*s.LongVal))
msg.Headers.Set("StringVal", eventstream.StringValue(*s.StringVal))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type GetEventStreamInput struct {
_ struct{} `type:"structure"`
InputVal *string `type:"string"`
}
// String returns the string representation
func (s GetEventStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetEventStreamInput) GoString() string {
return s.String()
}
// SetInputVal sets the InputVal field's value.
func (s *GetEventStreamInput) SetInputVal(v string) *GetEventStreamInput {
s.InputVal = &v
return s
}
type GetEventStreamOutput struct {
_ struct{} `type:"structure"`
eventStream *GetEventStreamEventStream
IntVal *int64 `type:"integer"`
StrVal *string `type:"string"`
}
// String returns the string representation
func (s GetEventStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetEventStreamOutput) GoString() string {
return s.String()
}
// SetIntVal sets the IntVal field's value.
func (s *GetEventStreamOutput) SetIntVal(v int64) *GetEventStreamOutput {
s.IntVal = &v
return s
}
// SetStrVal sets the StrVal field's value.
func (s *GetEventStreamOutput) SetStrVal(v string) *GetEventStreamOutput {
s.StrVal = &v
return s
}
// GetStream returns the type to interact with the event stream.
func (s *GetEventStreamOutput) GetStream() *GetEventStreamEventStream {
return s.eventStream
}
type HeaderOnlyEvent struct {
_ struct{} `type:"structure"`
// BlobVal is automatically base64 encoded/decoded by the SDK.
BlobVal []byte `location:"header" type:"blob"`
BoolVal *bool `location:"header" type:"boolean"`
ByteVal *int64 `location:"header" type:"byte"`
IntegerVal *int64 `location:"header" type:"integer"`
LongVal *int64 `location:"header" type:"long"`
ShortVal *int64 `location:"header" type:"short"`
StringVal *string `location:"header" type:"string"`
TimeVal *time.Time `location:"header" type:"timestamp"`
}
// String returns the string representation
func (s HeaderOnlyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s HeaderOnlyEvent) GoString() string {
return s.String()
}
// SetBlobVal sets the BlobVal field's value.
func (s *HeaderOnlyEvent) SetBlobVal(v []byte) *HeaderOnlyEvent {
s.BlobVal = v
return s
}
// SetBoolVal sets the BoolVal field's value.
func (s *HeaderOnlyEvent) SetBoolVal(v bool) *HeaderOnlyEvent {
s.BoolVal = &v
return s
}
// SetByteVal sets the ByteVal field's value.
func (s *HeaderOnlyEvent) SetByteVal(v int64) *HeaderOnlyEvent {
s.ByteVal = &v
return s
}
// SetIntegerVal sets the IntegerVal field's value.
func (s *HeaderOnlyEvent) SetIntegerVal(v int64) *HeaderOnlyEvent {
s.IntegerVal = &v
return s
}
// SetLongVal sets the LongVal field's value.
func (s *HeaderOnlyEvent) SetLongVal(v int64) *HeaderOnlyEvent {
s.LongVal = &v
return s
}
// SetShortVal sets the ShortVal field's value.
func (s *HeaderOnlyEvent) SetShortVal(v int64) *HeaderOnlyEvent {
s.ShortVal = &v
return s
}
// SetStringVal sets the StringVal field's value.
func (s *HeaderOnlyEvent) SetStringVal(v string) *HeaderOnlyEvent {
s.StringVal = &v
return s
}
// SetTimeVal sets the TimeVal field's value.
func (s *HeaderOnlyEvent) SetTimeVal(v time.Time) *HeaderOnlyEvent {
s.TimeVal = &v
return s
}
// The HeaderOnlyEvent is and event in the EventStream group of events.
func (s *HeaderOnlyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the HeaderOnlyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *HeaderOnlyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("BlobVal"); hv != nil {
v := hv.Get().([]byte)
s.BlobVal = v
}
if hv := msg.Headers.Get("BoolVal"); hv != nil {
v := hv.Get().(bool)
s.BoolVal = &v
}
if hv := msg.Headers.Get("ByteVal"); hv != nil {
v := hv.Get().(int8)
m := int64(v)
s.ByteVal = &m
}
if hv := msg.Headers.Get("IntegerVal"); hv != nil {
v := hv.Get().(int32)
m := int64(v)
s.IntegerVal = &m
}
if hv := msg.Headers.Get("LongVal"); hv != nil {
v := hv.Get().(int64)
s.LongVal = &v
}
if hv := msg.Headers.Get("ShortVal"); hv != nil {
v := hv.Get().(int16)
m := int64(v)
s.ShortVal = &m
}
if hv := msg.Headers.Get("StringVal"); hv != nil {
v := hv.Get().(string)
s.StringVal = &v
}
if hv := msg.Headers.Get("TimeVal"); hv != nil {
v := hv.Get().(time.Time)
s.TimeVal = &v
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *HeaderOnlyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("BlobVal", eventstream.BytesValue(s.BlobVal))
msg.Headers.Set("BoolVal", eventstream.BoolValue(*s.BoolVal))
msg.Headers.Set("ByteVal", eventstream.Int8Value(int8(*s.ByteVal)))
msg.Headers.Set("IntegerVal", eventstream.Int32Value(int32(*s.IntegerVal)))
msg.Headers.Set("LongVal", eventstream.Int64Value(*s.LongVal))
msg.Headers.Set("ShortVal", eventstream.Int16Value(int16(*s.ShortVal)))
msg.Headers.Set("StringVal", eventstream.StringValue(*s.StringVal))
msg.Headers.Set("TimeVal", eventstream.TimestampValue(*s.TimeVal))
return msg, err
}
type ImplicitPayloadEvent struct {
_ struct{} `type:"structure"`
ByteVal *int64 `location:"header" type:"byte"`
IntegerVal *int64 `type:"integer"`
ShortVal *int64 `type:"short"`
}
// String returns the string representation
func (s ImplicitPayloadEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ImplicitPayloadEvent) GoString() string {
return s.String()
}
// SetByteVal sets the ByteVal field's value.
func (s *ImplicitPayloadEvent) SetByteVal(v int64) *ImplicitPayloadEvent {
s.ByteVal = &v
return s
}
// SetIntegerVal sets the IntegerVal field's value.
func (s *ImplicitPayloadEvent) SetIntegerVal(v int64) *ImplicitPayloadEvent {
s.IntegerVal = &v
return s
}
// SetShortVal sets the ShortVal field's value.
func (s *ImplicitPayloadEvent) SetShortVal(v int64) *ImplicitPayloadEvent {
s.ShortVal = &v
return s
}
// The ImplicitPayloadEvent is and event in the EventStream group of events.
func (s *ImplicitPayloadEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ImplicitPayloadEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ImplicitPayloadEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("ByteVal"); hv != nil {
v := hv.Get().(int8)
m := int64(v)
s.ByteVal = &m
}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ImplicitPayloadEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("ByteVal", eventstream.Int8Value(int8(*s.ByteVal)))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type NestedShape struct {
_ struct{} `type:"structure"`
IntVal *int64 `type:"integer"`
StrVal *string `type:"string"`
}
// String returns the string representation
func (s NestedShape) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s NestedShape) GoString() string {
return s.String()
}
// SetIntVal sets the IntVal field's value.
func (s *NestedShape) SetIntVal(v int64) *NestedShape {
s.IntVal = &v
return s
}
// SetStrVal sets the StrVal field's value.
func (s *NestedShape) SetStrVal(v string) *NestedShape {
s.StrVal = &v
return s
}
type OtherOperationInput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s OtherOperationInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s OtherOperationInput) GoString() string {
return s.String()
}
type OtherOperationOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s OtherOperationOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s OtherOperationOutput) GoString() string {
return s.String()
}
type PayloadOnlyBlobEvent struct {
_ struct{} `type:"structure" payload:"BlobPayload"`
// BlobPayload is automatically base64 encoded/decoded by the SDK.
BlobPayload []byte `type:"blob"`
}
// String returns the string representation
func (s PayloadOnlyBlobEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyBlobEvent) GoString() string {
return s.String()
}
// SetBlobPayload sets the BlobPayload field's value.
func (s *PayloadOnlyBlobEvent) SetBlobPayload(v []byte) *PayloadOnlyBlobEvent {
s.BlobPayload = v
return s
}
// The PayloadOnlyBlobEvent is and event in the EventStream group of events.
func (s *PayloadOnlyBlobEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyBlobEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyBlobEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
s.BlobPayload = make([]byte, len(msg.Payload))
copy(s.BlobPayload, msg.Payload)
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyBlobEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set(":content-type", eventstream.StringValue("application/octet-stream"))
msg.Payload = s.BlobPayload
return msg, err
}
type PayloadOnlyEvent struct {
_ struct{} `type:"structure" payload:"NestedVal"`
NestedVal *NestedShape `locationName:"NestedVal" type:"structure"`
}
// String returns the string representation
func (s PayloadOnlyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyEvent) GoString() string {
return s.String()
}
// SetNestedVal sets the NestedVal field's value.
func (s *PayloadOnlyEvent) SetNestedVal(v *NestedShape) *PayloadOnlyEvent {
s.NestedVal = v
return s
}
// The PayloadOnlyEvent is and event in the EventStream group of events.
func (s *PayloadOnlyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type PayloadOnlyStringEvent struct {
_ struct{} `type:"structure" payload:"StringPayload"`
StringPayload *string `locationName:"StringPayload" type:"string"`
}
// String returns the string representation
func (s PayloadOnlyStringEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyStringEvent) GoString() string {
return s.String()
}
// SetStringPayload sets the StringPayload field's value.
func (s *PayloadOnlyStringEvent) SetStringPayload(v string) *PayloadOnlyStringEvent {
s.StringPayload = &v
return s
}
// The PayloadOnlyStringEvent is and event in the EventStream group of events.
func (s *PayloadOnlyStringEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyStringEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyStringEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
s.StringPayload = aws.String(string(msg.Payload))
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyStringEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Payload = []byte(aws.StringValue(s.StringPayload))
return msg, err
}
| 1,675 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package restjsonservice provides the client and types for making API
// requests to REST JSON Service.
//
// See https://docs.aws.amazon.com/goto/WebAPI/RESTJSONService-0000-00-00 for more information on this service.
//
// See restjsonservice package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/restjsonservice/
//
// Using the Client
//
// To contact REST JSON Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the REST JSON Service client RESTJSONService for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/restjsonservice/#New
package restjsonservice
| 27 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package restjsonservice
import (
"github.com/aws/aws-sdk-go/private/protocol"
)
const (
// ErrCodeExceptionEvent for service response error code
// "ExceptionEvent".
ErrCodeExceptionEvent = "ExceptionEvent"
// ErrCodeExceptionEvent2 for service response error code
// "ExceptionEvent2".
ErrCodeExceptionEvent2 = "ExceptionEvent2"
)
var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"ExceptionEvent": newErrorExceptionEvent,
"ExceptionEvent2": newErrorExceptionEvent2,
}
| 24 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// +build go1.15
package restjsonservice
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamtest"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
var _ time.Time
var _ awserr.Error
var _ context.Context
var _ sync.WaitGroup
var _ strings.Reader
func TestEmptyStream_Read(t *testing.T) {
expectEvents, eventMsgs := mockEmptyStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestEmptyStream_ReadClose(t *testing.T) {
_, eventMsgs := mockEmptyStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestEmptyStream_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mockEmptyStreamReadEvents()
var eventOffset int
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]EmptyEventStreamEvent{
&EmptyEventStreamUnknownEvent{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func BenchmarkEmptyStream_Read(b *testing.B) {
_, eventMsgs := mockEmptyStreamReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.EmptyStream(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mockEmptyStreamReadEvents() (
[]EmptyEventStreamEvent,
[]eventstream.Message,
) {
expectEvents := []EmptyEventStreamEvent{}
var marshalers request.HandlerList
marshalers.PushBackNamed(restjson.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{}
return expectEvents, eventMsgs
}
func TestGetEventStream_Read(t *testing.T) {
expectEvents, eventMsgs := mockGetEventStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestGetEventStream_ReadClose(t *testing.T) {
_, eventMsgs := mockGetEventStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
// Assert calling Err before close does not close the stream.
resp.GetStream().Err()
select {
case _, ok := <-resp.GetStream().Events():
if !ok {
t.Fatalf("expect stream not to be closed, but was")
}
default:
}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestGetEventStream_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mockGetEventStreamReadEvents()
var eventOffset int
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]EventStreamEvent{
&EventStreamUnknownEvent{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func BenchmarkGetEventStream_Read(b *testing.B) {
_, eventMsgs := mockGetEventStreamReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.GetEventStream(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mockGetEventStreamReadEvents() (
[]EventStreamEvent,
[]eventstream.Message,
) {
expectEvents := []EventStreamEvent{
&EmptyEvent{},
&ExplicitPayloadEvent{
LongVal: aws.Int64(1234),
NestedVal: &NestedShape{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
StringVal: aws.String("string value goes here"),
},
&HeaderOnlyEvent{
BlobVal: []byte("blob value goes here"),
BoolVal: aws.Bool(true),
ByteVal: aws.Int64(1),
IntegerVal: aws.Int64(123),
LongVal: aws.Int64(1234),
ShortVal: aws.Int64(12),
StringVal: aws.String("string value goes here"),
TimeVal: aws.Time(time.Unix(1396594860, 0).UTC()),
},
&ImplicitPayloadEvent{
ByteVal: aws.Int64(1),
IntegerVal: aws.Int64(123),
ShortVal: aws.Int64(12),
},
&PayloadOnlyEvent{
NestedVal: &NestedShape{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
},
&PayloadOnlyBlobEvent{
BlobPayload: []byte("blob value goes here"),
},
&PayloadOnlyStringEvent{
StringPayload: aws.String("string value goes here"),
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(restjson.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("Empty"),
},
},
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("ExplicitPayload"),
},
{
Name: "LongVal",
Value: eventstream.Int64Value(*expectEvents[1].(*ExplicitPayloadEvent).LongVal),
},
{
Name: "StringVal",
Value: eventstream.StringValue(*expectEvents[1].(*ExplicitPayloadEvent).StringVal),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[1]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("Headers"),
},
{
Name: "BlobVal",
Value: eventstream.BytesValue(expectEvents[2].(*HeaderOnlyEvent).BlobVal),
},
{
Name: "BoolVal",
Value: eventstream.BoolValue(*expectEvents[2].(*HeaderOnlyEvent).BoolVal),
},
{
Name: "ByteVal",
Value: eventstream.Int8Value(int8(*expectEvents[2].(*HeaderOnlyEvent).ByteVal)),
},
{
Name: "IntegerVal",
Value: eventstream.Int32Value(int32(*expectEvents[2].(*HeaderOnlyEvent).IntegerVal)),
},
{
Name: "LongVal",
Value: eventstream.Int64Value(*expectEvents[2].(*HeaderOnlyEvent).LongVal),
},
{
Name: "ShortVal",
Value: eventstream.Int16Value(int16(*expectEvents[2].(*HeaderOnlyEvent).ShortVal)),
},
{
Name: "StringVal",
Value: eventstream.StringValue(*expectEvents[2].(*HeaderOnlyEvent).StringVal),
},
{
Name: "TimeVal",
Value: eventstream.TimestampValue(*expectEvents[2].(*HeaderOnlyEvent).TimeVal),
},
},
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("ImplicitPayload"),
},
{
Name: "ByteVal",
Value: eventstream.Int8Value(int8(*expectEvents[3].(*ImplicitPayloadEvent).ByteVal)),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[3]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnly"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[4]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnlyBlob"),
},
},
Payload: expectEvents[5].(*PayloadOnlyBlobEvent).BlobPayload,
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnlyString"),
},
},
Payload: []byte(*expectEvents[6].(*PayloadOnlyStringEvent).StringPayload),
},
}
return expectEvents, eventMsgs
}
func TestGetEventStream_ReadException(t *testing.T) {
expectEvents := []EventStreamEvent{
&ExceptionEvent{
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
IntVal: aws.Int64(123),
Message_: aws.String("string value goes here"),
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(restjson.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventExceptionTypeHeader,
{
Name: eventstreamapi.ExceptionTypeHeader,
Value: eventstream.StringValue("Exception"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[0]),
},
}
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
<-resp.GetStream().Events()
err = resp.GetStream().Err()
if err == nil {
t.Fatalf("expect err, got none")
}
expectErr := &ExceptionEvent{
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
IntVal: aws.Int64(123),
Message_: aws.String("string value goes here"),
}
aerr, ok := err.(awserr.Error)
if !ok {
t.Errorf("expect exception, got %T, %#v", err, err)
}
if e, a := expectErr.Code(), aerr.Code(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr.Message(), aerr.Message(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr, aerr; !reflect.DeepEqual(e, a) {
t.Errorf("expect error %+#v, got %+#v", e, a)
}
}
var _ awserr.Error = (*ExceptionEvent)(nil)
var _ awserr.Error = (*ExceptionEvent2)(nil)
type loopReader struct {
source *bytes.Reader
}
func (c *loopReader) Read(p []byte) (int, error) {
if c.source.Len() == 0 {
c.source.Seek(0, 0)
}
return c.source.Read(p)
}
| 673 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package restjsonservice
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
// RESTJSONService provides the API operation methods for making requests to
// REST JSON Service. See this package's package overview docs
// for details on the service.
//
// RESTJSONService methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type RESTJSONService struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "RESTJSONService" // Name of service.
EndpointsID = "restjsonservice" // ID to lookup a service endpoint with.
ServiceID = "RESTJSONService" // ServiceID is a unique identifier of a specific service.
)
// New creates a new instance of the RESTJSONService client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a RESTJSONService client from just a session.
// svc := restjsonservice.New(mySession)
//
// // Create a RESTJSONService client with additional configuration
// svc := restjsonservice.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *RESTJSONService {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *RESTJSONService {
svc := &RESTJSONService{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "0000-00-00",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(restjson.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(
protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(),
)
svc.Handlers.BuildStream.PushBackNamed(restjson.BuildHandler)
svc.Handlers.UnmarshalStream.PushBackNamed(restjson.UnmarshalHandler)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a RESTJSONService operation and runs any
// custom request initialization.
func (c *RESTJSONService) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
| 105 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package restjsonserviceiface provides an interface to enable mocking the REST JSON Service service client
// for testing your code.
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters.
package restjsonserviceiface
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/model/api/codegentest/service/restjsonservice"
)
// RESTJSONServiceAPI provides an interface to enable mocking the
// restjsonservice.RESTJSONService service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
// // myFunc uses an SDK service client to make a request to
// // REST JSON Service.
// func myFunc(svc restjsonserviceiface.RESTJSONServiceAPI) bool {
// // Make svc.EmptyStream request
// }
//
// func main() {
// sess := session.New()
// svc := restjsonservice.New(sess)
//
// myFunc(svc)
// }
//
// In your _test.go file:
//
// // Define a mock struct to be used in your unit tests of myFunc.
// type mockRESTJSONServiceClient struct {
// restjsonserviceiface.RESTJSONServiceAPI
// }
// func (m *mockRESTJSONServiceClient) EmptyStream(input *restjsonservice.EmptyStreamInput) (*restjsonservice.EmptyStreamOutput, error) {
// // mock response/functionality
// }
//
// func TestMyFunc(t *testing.T) {
// // Setup Test
// mockSvc := &mockRESTJSONServiceClient{}
//
// myfunc(mockSvc)
//
// // Verify myFunc's functionality
// }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type RESTJSONServiceAPI interface {
EmptyStream(*restjsonservice.EmptyStreamInput) (*restjsonservice.EmptyStreamOutput, error)
EmptyStreamWithContext(aws.Context, *restjsonservice.EmptyStreamInput, ...request.Option) (*restjsonservice.EmptyStreamOutput, error)
EmptyStreamRequest(*restjsonservice.EmptyStreamInput) (*request.Request, *restjsonservice.EmptyStreamOutput)
GetEventStream(*restjsonservice.GetEventStreamInput) (*restjsonservice.GetEventStreamOutput, error)
GetEventStreamWithContext(aws.Context, *restjsonservice.GetEventStreamInput, ...request.Option) (*restjsonservice.GetEventStreamOutput, error)
GetEventStreamRequest(*restjsonservice.GetEventStreamInput) (*request.Request, *restjsonservice.GetEventStreamOutput)
OtherOperation(*restjsonservice.OtherOperationInput) (*restjsonservice.OtherOperationOutput, error)
OtherOperationWithContext(aws.Context, *restjsonservice.OtherOperationInput, ...request.Option) (*restjsonservice.OtherOperationOutput, error)
OtherOperationRequest(*restjsonservice.OtherOperationInput) (*request.Request, *restjsonservice.OtherOperationOutput)
}
var _ RESTJSONServiceAPI = (*restjsonservice.RESTJSONService)(nil)
| 77 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package restxmlservice
import (
"bytes"
"fmt"
"io"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi"
"github.com/aws/aws-sdk-go/private/protocol/rest"
"github.com/aws/aws-sdk-go/private/protocol/restxml"
)
const opEmptyStream = "EmptyStream"
// EmptyStreamRequest generates a "aws/request.Request" representing the
// client's request for the EmptyStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See EmptyStream for more information on using the EmptyStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the EmptyStreamRequest method.
// req, resp := client.EmptyStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00/EmptyStream
func (c *RESTXMLService) EmptyStreamRequest(input *EmptyStreamInput) (req *request.Request, output *EmptyStreamOutput) {
op := &request.Operation{
Name: opEmptyStream,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &EmptyStreamInput{}
}
output = &EmptyStreamOutput{}
req = c.newRequest(op, input, output)
es := NewEmptyStreamEventStream()
output.eventStream = es
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
return
}
// EmptyStream API operation for REST XML Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for REST XML Service's
// API operation EmptyStream for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00/EmptyStream
func (c *RESTXMLService) EmptyStream(input *EmptyStreamInput) (*EmptyStreamOutput, error) {
req, out := c.EmptyStreamRequest(input)
return out, req.Send()
}
// EmptyStreamWithContext is the same as EmptyStream with the addition of
// the ability to pass a context and additional request options.
//
// See EmptyStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RESTXMLService) EmptyStreamWithContext(ctx aws.Context, input *EmptyStreamInput, opts ...request.Option) (*EmptyStreamOutput, error) {
req, out := c.EmptyStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
var _ awserr.Error
// EmptyStreamEventStream provides the event stream handling for the EmptyStream.
//
// For testing and mocking the event stream this type should be initialized via
// the NewEmptyStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type EmptyStreamEventStream struct {
// Reader is the EventStream reader for the EmptyEventStream
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader EmptyEventStreamReader
outputReader io.ReadCloser
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// NewEmptyStreamEventStream initializes an EmptyStreamEventStream.
// This function should only be used for testing and mocking the EmptyStreamEventStream
// stream within your application.
//
// The Reader member must be set before reading events from the stream.
//
// es := NewEmptyStreamEventStream(func(o *EmptyStreamEventStream{
// es.Reader = myMockStreamReader
// })
func NewEmptyStreamEventStream(opts ...func(*EmptyStreamEventStream)) *EmptyStreamEventStream {
es := &EmptyStreamEventStream{
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
func (es *EmptyStreamEventStream) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *EmptyStreamEventStream) waitStreamPartClose() {
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <-chan struct{}
if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
outputClosedCh = v.Closed()
}
select {
case <-es.done:
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
}
}
// Events returns a channel to read events from.
//
// These events are:
//
// * EmptyEventStreamUnknownEvent
func (es *EmptyStreamEventStream) Events() <-chan EmptyEventStreamEvent {
return es.Reader.Events()
}
func (es *EmptyStreamEventStream) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := unmarshalerForEmptyEventStreamEvent{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = newReadEmptyEventStream(eventReader)
}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
//
func (es *EmptyStreamEventStream) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *EmptyStreamEventStream) safeClose() {
if es.done != nil {
close(es.done)
}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *EmptyStreamEventStream) Err() error {
if err := es.err.Err(); err != nil {
return err
}
if err := es.Reader.Err(); err != nil {
return err
}
return nil
}
const opGetEventStream = "GetEventStream"
// GetEventStreamRequest generates a "aws/request.Request" representing the
// client's request for the GetEventStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetEventStream for more information on using the GetEventStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetEventStreamRequest method.
// req, resp := client.GetEventStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00/GetEventStream
func (c *RESTXMLService) GetEventStreamRequest(input *GetEventStreamInput) (req *request.Request, output *GetEventStreamOutput) {
op := &request.Operation{
Name: opGetEventStream,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &GetEventStreamInput{}
}
output = &GetEventStreamOutput{}
req = c.newRequest(op, input, output)
es := NewGetEventStreamEventStream()
output.eventStream = es
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
return
}
// GetEventStream API operation for REST XML Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for REST XML Service's
// API operation GetEventStream for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00/GetEventStream
func (c *RESTXMLService) GetEventStream(input *GetEventStreamInput) (*GetEventStreamOutput, error) {
req, out := c.GetEventStreamRequest(input)
return out, req.Send()
}
// GetEventStreamWithContext is the same as GetEventStream with the addition of
// the ability to pass a context and additional request options.
//
// See GetEventStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RESTXMLService) GetEventStreamWithContext(ctx aws.Context, input *GetEventStreamInput, opts ...request.Option) (*GetEventStreamOutput, error) {
req, out := c.GetEventStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
var _ awserr.Error
// GetEventStreamEventStream provides the event stream handling for the GetEventStream.
//
// For testing and mocking the event stream this type should be initialized via
// the NewGetEventStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type GetEventStreamEventStream struct {
// Reader is the EventStream reader for the EventStream
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader EventStreamReader
outputReader io.ReadCloser
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// NewGetEventStreamEventStream initializes an GetEventStreamEventStream.
// This function should only be used for testing and mocking the GetEventStreamEventStream
// stream within your application.
//
// The Reader member must be set before reading events from the stream.
//
// es := NewGetEventStreamEventStream(func(o *GetEventStreamEventStream{
// es.Reader = myMockStreamReader
// })
func NewGetEventStreamEventStream(opts ...func(*GetEventStreamEventStream)) *GetEventStreamEventStream {
es := &GetEventStreamEventStream{
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
func (es *GetEventStreamEventStream) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *GetEventStreamEventStream) waitStreamPartClose() {
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <-chan struct{}
if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
outputClosedCh = v.Closed()
}
select {
case <-es.done:
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
}
}
// Events returns a channel to read events from.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
// * EventStreamUnknownEvent
func (es *GetEventStreamEventStream) Events() <-chan EventStreamEvent {
return es.Reader.Events()
}
func (es *GetEventStreamEventStream) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := unmarshalerForEventStreamEvent{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = newReadEventStream(eventReader)
}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
//
func (es *GetEventStreamEventStream) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *GetEventStreamEventStream) safeClose() {
if es.done != nil {
close(es.done)
}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *GetEventStreamEventStream) Err() error {
if err := es.err.Err(); err != nil {
return err
}
if err := es.Reader.Err(); err != nil {
return err
}
return nil
}
const opOtherOperation = "OtherOperation"
// OtherOperationRequest generates a "aws/request.Request" representing the
// client's request for the OtherOperation operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OtherOperation for more information on using the OtherOperation
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OtherOperationRequest method.
// req, resp := client.OtherOperationRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00/OtherOperation
func (c *RESTXMLService) OtherOperationRequest(input *OtherOperationInput) (req *request.Request, output *OtherOperationOutput) {
op := &request.Operation{
Name: opOtherOperation,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &OtherOperationInput{}
}
output = &OtherOperationOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// OtherOperation API operation for REST XML Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for REST XML Service's
// API operation OtherOperation for usage and error information.
//
// Returned Error Codes:
// * ErrCodeExceptionEvent2 "ExceptionEvent2"
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00/OtherOperation
func (c *RESTXMLService) OtherOperation(input *OtherOperationInput) (*OtherOperationOutput, error) {
req, out := c.OtherOperationRequest(input)
return out, req.Send()
}
// OtherOperationWithContext is the same as OtherOperation with the addition of
// the ability to pass a context and additional request options.
//
// See OtherOperation for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RESTXMLService) OtherOperationWithContext(ctx aws.Context, input *OtherOperationInput, opts ...request.Option) (*OtherOperationOutput, error) {
req, out := c.OtherOperationRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type EmptyEvent struct {
_ struct{} `locationName:"EmptyEvent" type:"structure"`
}
// String returns the string representation
func (s EmptyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyEvent) GoString() string {
return s.String()
}
// The EmptyEvent is and event in the EventStream group of events.
func (s *EmptyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *EmptyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *EmptyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
return msg, err
}
// EmptyEventStreamEvent groups together all EventStream
// events writes for EmptyEventStream.
//
// These events are:
//
type EmptyEventStreamEvent interface {
eventEmptyEventStream()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
// EmptyEventStreamReader provides the interface for reading to the stream. The
// default implementation for this interface will be EmptyEventStream.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
//
// * EmptyEventStreamUnknownEvent
type EmptyEventStreamReader interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan EmptyEventStreamEvent
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type readEmptyEventStream struct {
eventReader *eventstreamapi.EventReader
stream chan EmptyEventStreamEvent
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func newReadEmptyEventStream(eventReader *eventstreamapi.EventReader) *readEmptyEventStream {
r := &readEmptyEventStream{
eventReader: eventReader,
stream: make(chan EmptyEventStreamEvent),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *readEmptyEventStream) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *readEmptyEventStream) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *readEmptyEventStream) Closed() <-chan struct{} {
return r.done
}
func (r *readEmptyEventStream) safeClose() {
close(r.done)
}
func (r *readEmptyEventStream) Err() error {
return r.err.Err()
}
func (r *readEmptyEventStream) Events() <-chan EmptyEventStreamEvent {
return r.stream
}
func (r *readEmptyEventStream) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.(EmptyEventStreamEvent):
case <-r.done:
return
}
}
}
type unmarshalerForEmptyEventStreamEvent struct {
metadata protocol.ResponseMetadata
}
func (u unmarshalerForEmptyEventStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
default:
return &EmptyEventStreamUnknownEvent{Type: eventType}, nil
}
}
// EmptyEventStreamUnknownEvent provides a failsafe event for the
// EmptyEventStream group of events when an unknown event is received.
type EmptyEventStreamUnknownEvent struct {
Type string
Message eventstream.Message
}
// The EmptyEventStreamUnknownEvent is and event in the EmptyEventStream
// group of events.
func (s *EmptyEventStreamUnknownEvent) eventEmptyEventStream() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *EmptyEventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyEventStream value.
// This method is only used internally within the SDK's EventStream handling.
func (e *EmptyEventStreamUnknownEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
type EmptyStreamInput struct {
_ struct{} `locationName:"EmptyStreamRequest" type:"structure"`
}
// String returns the string representation
func (s EmptyStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyStreamInput) GoString() string {
return s.String()
}
type EmptyStreamOutput struct {
_ struct{} `type:"structure"`
eventStream *EmptyStreamEventStream
}
// String returns the string representation
func (s EmptyStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyStreamOutput) GoString() string {
return s.String()
}
// GetStream returns the type to interact with the event stream.
func (s *EmptyStreamOutput) GetStream() *EmptyStreamEventStream {
return s.eventStream
}
// EventStreamEvent groups together all EventStream
// events writes for EventStream.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
type EventStreamEvent interface {
eventEventStream()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
// EventStreamReader provides the interface for reading to the stream. The
// default implementation for this interface will be EventStream.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
// * EventStreamUnknownEvent
type EventStreamReader interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan EventStreamEvent
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type readEventStream struct {
eventReader *eventstreamapi.EventReader
stream chan EventStreamEvent
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func newReadEventStream(eventReader *eventstreamapi.EventReader) *readEventStream {
r := &readEventStream{
eventReader: eventReader,
stream: make(chan EventStreamEvent),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *readEventStream) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *readEventStream) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *readEventStream) Closed() <-chan struct{} {
return r.done
}
func (r *readEventStream) safeClose() {
close(r.done)
}
func (r *readEventStream) Err() error {
return r.err.Err()
}
func (r *readEventStream) Events() <-chan EventStreamEvent {
return r.stream
}
func (r *readEventStream) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.(EventStreamEvent):
case <-r.done:
return
}
}
}
type unmarshalerForEventStreamEvent struct {
metadata protocol.ResponseMetadata
}
func (u unmarshalerForEventStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
case "Empty":
return &EmptyEvent{}, nil
case "ExplicitPayload":
return &ExplicitPayloadEvent{}, nil
case "Headers":
return &HeaderOnlyEvent{}, nil
case "ImplicitPayload":
return &ImplicitPayloadEvent{}, nil
case "PayloadOnly":
return &PayloadOnlyEvent{}, nil
case "PayloadOnlyBlob":
return &PayloadOnlyBlobEvent{}, nil
case "PayloadOnlyString":
return &PayloadOnlyStringEvent{}, nil
case "Exception":
return newErrorExceptionEvent(u.metadata).(eventstreamapi.Unmarshaler), nil
case "Exception2":
return newErrorExceptionEvent2(u.metadata).(eventstreamapi.Unmarshaler), nil
default:
return &EventStreamUnknownEvent{Type: eventType}, nil
}
}
// EventStreamUnknownEvent provides a failsafe event for the
// EventStream group of events when an unknown event is received.
type EventStreamUnknownEvent struct {
Type string
Message eventstream.Message
}
// The EventStreamUnknownEvent is and event in the EventStream
// group of events.
func (s *EventStreamUnknownEvent) eventEventStream() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *EventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the EventStream value.
// This method is only used internally within the SDK's EventStream handling.
func (e *EventStreamUnknownEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
type ExceptionEvent struct {
_ struct{} `locationName:"ExceptionEvent" type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
IntVal *int64 `type:"integer"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation
func (s ExceptionEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExceptionEvent) GoString() string {
return s.String()
}
// The ExceptionEvent is and event in the EventStream group of events.
func (s *ExceptionEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExceptionEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
func newErrorExceptionEvent(v protocol.ResponseMetadata) error {
return &ExceptionEvent{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ExceptionEvent) Code() string {
return "ExceptionEvent"
}
// Message returns the exception's message.
func (s *ExceptionEvent) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ExceptionEvent) OrigErr() error {
return nil
}
func (s *ExceptionEvent) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ExceptionEvent) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ExceptionEvent) RequestID() string {
return s.RespMetadata.RequestID
}
type ExceptionEvent2 struct {
_ struct{} `locationName:"ExceptionEvent2" type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"Message" type:"string"`
}
// String returns the string representation
func (s ExceptionEvent2) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExceptionEvent2) GoString() string {
return s.String()
}
// The ExceptionEvent2 is and event in the EventStream group of events.
func (s *ExceptionEvent2) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExceptionEvent2 value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent2) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent2) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
func newErrorExceptionEvent2(v protocol.ResponseMetadata) error {
return &ExceptionEvent2{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ExceptionEvent2) Code() string {
return "ExceptionEvent2"
}
// Message returns the exception's message.
func (s *ExceptionEvent2) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ExceptionEvent2) OrigErr() error {
return nil
}
func (s *ExceptionEvent2) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ExceptionEvent2) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ExceptionEvent2) RequestID() string {
return s.RespMetadata.RequestID
}
type ExplicitPayloadEvent struct {
_ struct{} `locationName:"ExplicitPayloadEvent" type:"structure" payload:"NestedVal"`
LongVal *int64 `location:"header" type:"long"`
NestedVal *NestedShape `locationName:"NestedVal" type:"structure"`
StringVal *string `location:"header" type:"string"`
}
// String returns the string representation
func (s ExplicitPayloadEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExplicitPayloadEvent) GoString() string {
return s.String()
}
// SetLongVal sets the LongVal field's value.
func (s *ExplicitPayloadEvent) SetLongVal(v int64) *ExplicitPayloadEvent {
s.LongVal = &v
return s
}
// SetNestedVal sets the NestedVal field's value.
func (s *ExplicitPayloadEvent) SetNestedVal(v *NestedShape) *ExplicitPayloadEvent {
s.NestedVal = v
return s
}
// SetStringVal sets the StringVal field's value.
func (s *ExplicitPayloadEvent) SetStringVal(v string) *ExplicitPayloadEvent {
s.StringVal = &v
return s
}
// The ExplicitPayloadEvent is and event in the EventStream group of events.
func (s *ExplicitPayloadEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExplicitPayloadEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExplicitPayloadEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("LongVal"); hv != nil {
v := hv.Get().(int64)
s.LongVal = &v
}
if hv := msg.Headers.Get("StringVal"); hv != nil {
v := hv.Get().(string)
s.StringVal = &v
}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExplicitPayloadEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("LongVal", eventstream.Int64Value(*s.LongVal))
msg.Headers.Set("StringVal", eventstream.StringValue(*s.StringVal))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type GetEventStreamInput struct {
_ struct{} `locationName:"GetEventStreamRequest" type:"structure"`
InputVal *string `type:"string"`
}
// String returns the string representation
func (s GetEventStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetEventStreamInput) GoString() string {
return s.String()
}
// SetInputVal sets the InputVal field's value.
func (s *GetEventStreamInput) SetInputVal(v string) *GetEventStreamInput {
s.InputVal = &v
return s
}
type GetEventStreamOutput struct {
_ struct{} `type:"structure"`
eventStream *GetEventStreamEventStream
IntVal *int64 `type:"integer"`
StrVal *string `type:"string"`
}
// String returns the string representation
func (s GetEventStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetEventStreamOutput) GoString() string {
return s.String()
}
// SetIntVal sets the IntVal field's value.
func (s *GetEventStreamOutput) SetIntVal(v int64) *GetEventStreamOutput {
s.IntVal = &v
return s
}
// SetStrVal sets the StrVal field's value.
func (s *GetEventStreamOutput) SetStrVal(v string) *GetEventStreamOutput {
s.StrVal = &v
return s
}
// GetStream returns the type to interact with the event stream.
func (s *GetEventStreamOutput) GetStream() *GetEventStreamEventStream {
return s.eventStream
}
type HeaderOnlyEvent struct {
_ struct{} `locationName:"HeaderOnlyEvent" type:"structure"`
// BlobVal is automatically base64 encoded/decoded by the SDK.
BlobVal []byte `location:"header" type:"blob"`
BoolVal *bool `location:"header" type:"boolean"`
ByteVal *int64 `location:"header" type:"byte"`
IntegerVal *int64 `location:"header" type:"integer"`
LongVal *int64 `location:"header" type:"long"`
ShortVal *int64 `location:"header" type:"short"`
StringVal *string `location:"header" type:"string"`
TimeVal *time.Time `location:"header" type:"timestamp"`
}
// String returns the string representation
func (s HeaderOnlyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s HeaderOnlyEvent) GoString() string {
return s.String()
}
// SetBlobVal sets the BlobVal field's value.
func (s *HeaderOnlyEvent) SetBlobVal(v []byte) *HeaderOnlyEvent {
s.BlobVal = v
return s
}
// SetBoolVal sets the BoolVal field's value.
func (s *HeaderOnlyEvent) SetBoolVal(v bool) *HeaderOnlyEvent {
s.BoolVal = &v
return s
}
// SetByteVal sets the ByteVal field's value.
func (s *HeaderOnlyEvent) SetByteVal(v int64) *HeaderOnlyEvent {
s.ByteVal = &v
return s
}
// SetIntegerVal sets the IntegerVal field's value.
func (s *HeaderOnlyEvent) SetIntegerVal(v int64) *HeaderOnlyEvent {
s.IntegerVal = &v
return s
}
// SetLongVal sets the LongVal field's value.
func (s *HeaderOnlyEvent) SetLongVal(v int64) *HeaderOnlyEvent {
s.LongVal = &v
return s
}
// SetShortVal sets the ShortVal field's value.
func (s *HeaderOnlyEvent) SetShortVal(v int64) *HeaderOnlyEvent {
s.ShortVal = &v
return s
}
// SetStringVal sets the StringVal field's value.
func (s *HeaderOnlyEvent) SetStringVal(v string) *HeaderOnlyEvent {
s.StringVal = &v
return s
}
// SetTimeVal sets the TimeVal field's value.
func (s *HeaderOnlyEvent) SetTimeVal(v time.Time) *HeaderOnlyEvent {
s.TimeVal = &v
return s
}
// The HeaderOnlyEvent is and event in the EventStream group of events.
func (s *HeaderOnlyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the HeaderOnlyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *HeaderOnlyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("BlobVal"); hv != nil {
v := hv.Get().([]byte)
s.BlobVal = v
}
if hv := msg.Headers.Get("BoolVal"); hv != nil {
v := hv.Get().(bool)
s.BoolVal = &v
}
if hv := msg.Headers.Get("ByteVal"); hv != nil {
v := hv.Get().(int8)
m := int64(v)
s.ByteVal = &m
}
if hv := msg.Headers.Get("IntegerVal"); hv != nil {
v := hv.Get().(int32)
m := int64(v)
s.IntegerVal = &m
}
if hv := msg.Headers.Get("LongVal"); hv != nil {
v := hv.Get().(int64)
s.LongVal = &v
}
if hv := msg.Headers.Get("ShortVal"); hv != nil {
v := hv.Get().(int16)
m := int64(v)
s.ShortVal = &m
}
if hv := msg.Headers.Get("StringVal"); hv != nil {
v := hv.Get().(string)
s.StringVal = &v
}
if hv := msg.Headers.Get("TimeVal"); hv != nil {
v := hv.Get().(time.Time)
s.TimeVal = &v
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *HeaderOnlyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("BlobVal", eventstream.BytesValue(s.BlobVal))
msg.Headers.Set("BoolVal", eventstream.BoolValue(*s.BoolVal))
msg.Headers.Set("ByteVal", eventstream.Int8Value(int8(*s.ByteVal)))
msg.Headers.Set("IntegerVal", eventstream.Int32Value(int32(*s.IntegerVal)))
msg.Headers.Set("LongVal", eventstream.Int64Value(*s.LongVal))
msg.Headers.Set("ShortVal", eventstream.Int16Value(int16(*s.ShortVal)))
msg.Headers.Set("StringVal", eventstream.StringValue(*s.StringVal))
msg.Headers.Set("TimeVal", eventstream.TimestampValue(*s.TimeVal))
return msg, err
}
type ImplicitPayloadEvent struct {
_ struct{} `locationName:"ImplicitPayloadEvent" type:"structure"`
ByteVal *int64 `location:"header" type:"byte"`
IntegerVal *int64 `type:"integer"`
ShortVal *int64 `type:"short"`
}
// String returns the string representation
func (s ImplicitPayloadEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ImplicitPayloadEvent) GoString() string {
return s.String()
}
// SetByteVal sets the ByteVal field's value.
func (s *ImplicitPayloadEvent) SetByteVal(v int64) *ImplicitPayloadEvent {
s.ByteVal = &v
return s
}
// SetIntegerVal sets the IntegerVal field's value.
func (s *ImplicitPayloadEvent) SetIntegerVal(v int64) *ImplicitPayloadEvent {
s.IntegerVal = &v
return s
}
// SetShortVal sets the ShortVal field's value.
func (s *ImplicitPayloadEvent) SetShortVal(v int64) *ImplicitPayloadEvent {
s.ShortVal = &v
return s
}
// The ImplicitPayloadEvent is and event in the EventStream group of events.
func (s *ImplicitPayloadEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ImplicitPayloadEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ImplicitPayloadEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("ByteVal"); hv != nil {
v := hv.Get().(int8)
m := int64(v)
s.ByteVal = &m
}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ImplicitPayloadEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("ByteVal", eventstream.Int8Value(int8(*s.ByteVal)))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type NestedShape struct {
_ struct{} `type:"structure"`
IntVal *int64 `type:"integer"`
StrVal *string `type:"string"`
}
// String returns the string representation
func (s NestedShape) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s NestedShape) GoString() string {
return s.String()
}
// SetIntVal sets the IntVal field's value.
func (s *NestedShape) SetIntVal(v int64) *NestedShape {
s.IntVal = &v
return s
}
// SetStrVal sets the StrVal field's value.
func (s *NestedShape) SetStrVal(v string) *NestedShape {
s.StrVal = &v
return s
}
type OtherOperationInput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s OtherOperationInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s OtherOperationInput) GoString() string {
return s.String()
}
type OtherOperationOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s OtherOperationOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s OtherOperationOutput) GoString() string {
return s.String()
}
type PayloadOnlyBlobEvent struct {
_ struct{} `locationName:"PayloadOnlyBlobEvent" type:"structure" payload:"BlobPayload"`
// BlobPayload is automatically base64 encoded/decoded by the SDK.
BlobPayload []byte `type:"blob"`
}
// String returns the string representation
func (s PayloadOnlyBlobEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyBlobEvent) GoString() string {
return s.String()
}
// SetBlobPayload sets the BlobPayload field's value.
func (s *PayloadOnlyBlobEvent) SetBlobPayload(v []byte) *PayloadOnlyBlobEvent {
s.BlobPayload = v
return s
}
// The PayloadOnlyBlobEvent is and event in the EventStream group of events.
func (s *PayloadOnlyBlobEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyBlobEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyBlobEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
s.BlobPayload = make([]byte, len(msg.Payload))
copy(s.BlobPayload, msg.Payload)
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyBlobEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set(":content-type", eventstream.StringValue("application/octet-stream"))
msg.Payload = s.BlobPayload
return msg, err
}
type PayloadOnlyEvent struct {
_ struct{} `locationName:"PayloadOnlyEvent" type:"structure" payload:"NestedVal"`
NestedVal *NestedShape `locationName:"NestedVal" type:"structure"`
}
// String returns the string representation
func (s PayloadOnlyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyEvent) GoString() string {
return s.String()
}
// SetNestedVal sets the NestedVal field's value.
func (s *PayloadOnlyEvent) SetNestedVal(v *NestedShape) *PayloadOnlyEvent {
s.NestedVal = v
return s
}
// The PayloadOnlyEvent is and event in the EventStream group of events.
func (s *PayloadOnlyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type PayloadOnlyStringEvent struct {
_ struct{} `locationName:"PayloadOnlyStringEvent" type:"structure" payload:"StringPayload"`
StringPayload *string `locationName:"StringPayload" type:"string"`
}
// String returns the string representation
func (s PayloadOnlyStringEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyStringEvent) GoString() string {
return s.String()
}
// SetStringPayload sets the StringPayload field's value.
func (s *PayloadOnlyStringEvent) SetStringPayload(v string) *PayloadOnlyStringEvent {
s.StringPayload = &v
return s
}
// The PayloadOnlyStringEvent is and event in the EventStream group of events.
func (s *PayloadOnlyStringEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyStringEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyStringEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
s.StringPayload = aws.String(string(msg.Payload))
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyStringEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Payload = []byte(aws.StringValue(s.StringPayload))
return msg, err
}
| 1,675 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package restxmlservice provides the client and types for making API
// requests to REST XML Service.
//
// See https://docs.aws.amazon.com/goto/WebAPI/RESTXMLService-0000-00-00 for more information on this service.
//
// See restxmlservice package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/restxmlservice/
//
// Using the Client
//
// To contact REST XML Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the REST XML Service client RESTXMLService for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/restxmlservice/#New
package restxmlservice
| 27 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package restxmlservice
const (
// ErrCodeExceptionEvent for service response error code
// "ExceptionEvent".
ErrCodeExceptionEvent = "ExceptionEvent"
// ErrCodeExceptionEvent2 for service response error code
// "ExceptionEvent2".
ErrCodeExceptionEvent2 = "ExceptionEvent2"
)
| 15 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// +build go1.15
package restxmlservice
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamtest"
"github.com/aws/aws-sdk-go/private/protocol/restxml"
)
var _ time.Time
var _ awserr.Error
var _ context.Context
var _ sync.WaitGroup
var _ strings.Reader
func TestEmptyStream_Read(t *testing.T) {
expectEvents, eventMsgs := mockEmptyStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestEmptyStream_ReadClose(t *testing.T) {
_, eventMsgs := mockEmptyStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestEmptyStream_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mockEmptyStreamReadEvents()
var eventOffset int
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]EmptyEventStreamEvent{
&EmptyEventStreamUnknownEvent{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func BenchmarkEmptyStream_Read(b *testing.B) {
_, eventMsgs := mockEmptyStreamReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.EmptyStream(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mockEmptyStreamReadEvents() (
[]EmptyEventStreamEvent,
[]eventstream.Message,
) {
expectEvents := []EmptyEventStreamEvent{}
var marshalers request.HandlerList
marshalers.PushBackNamed(restxml.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{}
return expectEvents, eventMsgs
}
func TestGetEventStream_Read(t *testing.T) {
expectEvents, eventMsgs := mockGetEventStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestGetEventStream_ReadClose(t *testing.T) {
_, eventMsgs := mockGetEventStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
// Assert calling Err before close does not close the stream.
resp.GetStream().Err()
select {
case _, ok := <-resp.GetStream().Events():
if !ok {
t.Fatalf("expect stream not to be closed, but was")
}
default:
}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestGetEventStream_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mockGetEventStreamReadEvents()
var eventOffset int
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]EventStreamEvent{
&EventStreamUnknownEvent{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func BenchmarkGetEventStream_Read(b *testing.B) {
_, eventMsgs := mockGetEventStreamReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.GetEventStream(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mockGetEventStreamReadEvents() (
[]EventStreamEvent,
[]eventstream.Message,
) {
expectEvents := []EventStreamEvent{
&EmptyEvent{},
&ExplicitPayloadEvent{
LongVal: aws.Int64(1234),
NestedVal: &NestedShape{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
StringVal: aws.String("string value goes here"),
},
&HeaderOnlyEvent{
BlobVal: []byte("blob value goes here"),
BoolVal: aws.Bool(true),
ByteVal: aws.Int64(1),
IntegerVal: aws.Int64(123),
LongVal: aws.Int64(1234),
ShortVal: aws.Int64(12),
StringVal: aws.String("string value goes here"),
TimeVal: aws.Time(time.Unix(1396594860, 0).UTC()),
},
&ImplicitPayloadEvent{
ByteVal: aws.Int64(1),
IntegerVal: aws.Int64(123),
ShortVal: aws.Int64(12),
},
&PayloadOnlyEvent{
NestedVal: &NestedShape{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
},
&PayloadOnlyBlobEvent{
BlobPayload: []byte("blob value goes here"),
},
&PayloadOnlyStringEvent{
StringPayload: aws.String("string value goes here"),
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(restxml.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("Empty"),
},
},
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("ExplicitPayload"),
},
{
Name: "LongVal",
Value: eventstream.Int64Value(*expectEvents[1].(*ExplicitPayloadEvent).LongVal),
},
{
Name: "StringVal",
Value: eventstream.StringValue(*expectEvents[1].(*ExplicitPayloadEvent).StringVal),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[1]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("Headers"),
},
{
Name: "BlobVal",
Value: eventstream.BytesValue(expectEvents[2].(*HeaderOnlyEvent).BlobVal),
},
{
Name: "BoolVal",
Value: eventstream.BoolValue(*expectEvents[2].(*HeaderOnlyEvent).BoolVal),
},
{
Name: "ByteVal",
Value: eventstream.Int8Value(int8(*expectEvents[2].(*HeaderOnlyEvent).ByteVal)),
},
{
Name: "IntegerVal",
Value: eventstream.Int32Value(int32(*expectEvents[2].(*HeaderOnlyEvent).IntegerVal)),
},
{
Name: "LongVal",
Value: eventstream.Int64Value(*expectEvents[2].(*HeaderOnlyEvent).LongVal),
},
{
Name: "ShortVal",
Value: eventstream.Int16Value(int16(*expectEvents[2].(*HeaderOnlyEvent).ShortVal)),
},
{
Name: "StringVal",
Value: eventstream.StringValue(*expectEvents[2].(*HeaderOnlyEvent).StringVal),
},
{
Name: "TimeVal",
Value: eventstream.TimestampValue(*expectEvents[2].(*HeaderOnlyEvent).TimeVal),
},
},
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("ImplicitPayload"),
},
{
Name: "ByteVal",
Value: eventstream.Int8Value(int8(*expectEvents[3].(*ImplicitPayloadEvent).ByteVal)),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[3]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnly"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[4]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnlyBlob"),
},
},
Payload: expectEvents[5].(*PayloadOnlyBlobEvent).BlobPayload,
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnlyString"),
},
},
Payload: []byte(*expectEvents[6].(*PayloadOnlyStringEvent).StringPayload),
},
}
return expectEvents, eventMsgs
}
func TestGetEventStream_ReadException(t *testing.T) {
expectEvents := []EventStreamEvent{
&ExceptionEvent{
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
IntVal: aws.Int64(123),
Message_: aws.String("string value goes here"),
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(restxml.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventExceptionTypeHeader,
{
Name: eventstreamapi.ExceptionTypeHeader,
Value: eventstream.StringValue("Exception"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[0]),
},
}
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
<-resp.GetStream().Events()
err = resp.GetStream().Err()
if err == nil {
t.Fatalf("expect err, got none")
}
expectErr := &ExceptionEvent{
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
IntVal: aws.Int64(123),
Message_: aws.String("string value goes here"),
}
aerr, ok := err.(awserr.Error)
if !ok {
t.Errorf("expect exception, got %T, %#v", err, err)
}
if e, a := expectErr.Code(), aerr.Code(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr.Message(), aerr.Message(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr, aerr; !reflect.DeepEqual(e, a) {
t.Errorf("expect error %+#v, got %+#v", e, a)
}
}
var _ awserr.Error = (*ExceptionEvent)(nil)
var _ awserr.Error = (*ExceptionEvent2)(nil)
type loopReader struct {
source *bytes.Reader
}
func (c *loopReader) Read(p []byte) (int, error) {
if c.source.Len() == 0 {
c.source.Seek(0, 0)
}
return c.source.Read(p)
}
| 673 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package restxmlservice
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol/restxml"
)
// RESTXMLService provides the API operation methods for making requests to
// REST XML Service. See this package's package overview docs
// for details on the service.
//
// RESTXMLService methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type RESTXMLService struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "RESTXMLService" // Name of service.
EndpointsID = "restxmlservice" // ID to lookup a service endpoint with.
ServiceID = "RESTXMLService" // ServiceID is a unique identifier of a specific service.
)
// New creates a new instance of the RESTXMLService client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a RESTXMLService client from just a session.
// svc := restxmlservice.New(mySession)
//
// // Create a RESTXMLService client with additional configuration
// svc := restxmlservice.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *RESTXMLService {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *RESTXMLService {
svc := &RESTXMLService{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "0000-00-00",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(restxml.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler)
svc.Handlers.BuildStream.PushBackNamed(restxml.BuildHandler)
svc.Handlers.UnmarshalStream.PushBackNamed(restxml.UnmarshalHandler)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a RESTXMLService operation and runs any
// custom request initialization.
func (c *RESTXMLService) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
| 102 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package restxmlserviceiface provides an interface to enable mocking the REST XML Service service client
// for testing your code.
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters.
package restxmlserviceiface
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/model/api/codegentest/service/restxmlservice"
)
// RESTXMLServiceAPI provides an interface to enable mocking the
// restxmlservice.RESTXMLService service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
// // myFunc uses an SDK service client to make a request to
// // REST XML Service.
// func myFunc(svc restxmlserviceiface.RESTXMLServiceAPI) bool {
// // Make svc.EmptyStream request
// }
//
// func main() {
// sess := session.New()
// svc := restxmlservice.New(sess)
//
// myFunc(svc)
// }
//
// In your _test.go file:
//
// // Define a mock struct to be used in your unit tests of myFunc.
// type mockRESTXMLServiceClient struct {
// restxmlserviceiface.RESTXMLServiceAPI
// }
// func (m *mockRESTXMLServiceClient) EmptyStream(input *restxmlservice.EmptyStreamInput) (*restxmlservice.EmptyStreamOutput, error) {
// // mock response/functionality
// }
//
// func TestMyFunc(t *testing.T) {
// // Setup Test
// mockSvc := &mockRESTXMLServiceClient{}
//
// myfunc(mockSvc)
//
// // Verify myFunc's functionality
// }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type RESTXMLServiceAPI interface {
EmptyStream(*restxmlservice.EmptyStreamInput) (*restxmlservice.EmptyStreamOutput, error)
EmptyStreamWithContext(aws.Context, *restxmlservice.EmptyStreamInput, ...request.Option) (*restxmlservice.EmptyStreamOutput, error)
EmptyStreamRequest(*restxmlservice.EmptyStreamInput) (*request.Request, *restxmlservice.EmptyStreamOutput)
GetEventStream(*restxmlservice.GetEventStreamInput) (*restxmlservice.GetEventStreamOutput, error)
GetEventStreamWithContext(aws.Context, *restxmlservice.GetEventStreamInput, ...request.Option) (*restxmlservice.GetEventStreamOutput, error)
GetEventStreamRequest(*restxmlservice.GetEventStreamInput) (*request.Request, *restxmlservice.GetEventStreamOutput)
OtherOperation(*restxmlservice.OtherOperationInput) (*restxmlservice.OtherOperationOutput, error)
OtherOperationWithContext(aws.Context, *restxmlservice.OtherOperationInput, ...request.Option) (*restxmlservice.OtherOperationOutput, error)
OtherOperationRequest(*restxmlservice.OtherOperationInput) (*request.Request, *restxmlservice.OtherOperationOutput)
}
var _ RESTXMLServiceAPI = (*restxmlservice.RESTXMLService)(nil)
| 77 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rpcservice
import (
"bytes"
"fmt"
"io"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
"github.com/aws/aws-sdk-go/private/protocol/rest"
)
const opEmptyStream = "EmptyStream"
// EmptyStreamRequest generates a "aws/request.Request" representing the
// client's request for the EmptyStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See EmptyStream for more information on using the EmptyStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the EmptyStreamRequest method.
// req, resp := client.EmptyStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00/EmptyStream
func (c *RPCService) EmptyStreamRequest(input *EmptyStreamInput) (req *request.Request, output *EmptyStreamOutput) {
op := &request.Operation{
Name: opEmptyStream,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &EmptyStreamInput{}
}
output = &EmptyStreamOutput{}
req = c.newRequest(op, input, output)
es := NewEmptyStreamEventStream()
output.eventStream = es
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
es.output = output
req.Handlers.Unmarshal.PushBack(es.recvInitialEvent)
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
return
}
// EmptyStream API operation for RPC Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for RPC Service's
// API operation EmptyStream for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00/EmptyStream
func (c *RPCService) EmptyStream(input *EmptyStreamInput) (*EmptyStreamOutput, error) {
req, out := c.EmptyStreamRequest(input)
return out, req.Send()
}
// EmptyStreamWithContext is the same as EmptyStream with the addition of
// the ability to pass a context and additional request options.
//
// See EmptyStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RPCService) EmptyStreamWithContext(ctx aws.Context, input *EmptyStreamInput, opts ...request.Option) (*EmptyStreamOutput, error) {
req, out := c.EmptyStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
var _ awserr.Error
// EmptyStreamEventStream provides the event stream handling for the EmptyStream.
//
// For testing and mocking the event stream this type should be initialized via
// the NewEmptyStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type EmptyStreamEventStream struct {
// Reader is the EventStream reader for the EmptyEventStream
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader EmptyEventStreamReader
outputReader io.ReadCloser
output *EmptyStreamOutput
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// NewEmptyStreamEventStream initializes an EmptyStreamEventStream.
// This function should only be used for testing and mocking the EmptyStreamEventStream
// stream within your application.
//
// The Reader member must be set before reading events from the stream.
//
// es := NewEmptyStreamEventStream(func(o *EmptyStreamEventStream{
// es.Reader = myMockStreamReader
// })
func NewEmptyStreamEventStream(opts ...func(*EmptyStreamEventStream)) *EmptyStreamEventStream {
es := &EmptyStreamEventStream{
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
func (es *EmptyStreamEventStream) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *EmptyStreamEventStream) waitStreamPartClose() {
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <-chan struct{}
if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
outputClosedCh = v.Closed()
}
select {
case <-es.done:
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
}
}
type eventTypeForEmptyStreamEventStreamOutputEvent struct {
unmarshalerForEvent func(string) (eventstreamapi.Unmarshaler, error)
output *EmptyStreamOutput
}
func (e eventTypeForEmptyStreamEventStreamOutputEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
if eventType == "initial-response" {
return e.output, nil
}
return e.unmarshalerForEvent(eventType)
}
// Events returns a channel to read events from.
//
// These events are:
//
// * EmptyEventStreamUnknownEvent
func (es *EmptyStreamEventStream) Events() <-chan EmptyEventStreamEvent {
return es.Reader.Events()
}
func (es *EmptyStreamEventStream) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := unmarshalerForEmptyEventStreamEvent{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
unmarshalerForEvent = eventTypeForEmptyStreamEventStreamOutputEvent{
unmarshalerForEvent: unmarshalerForEvent,
output: es.output,
}.UnmarshalerForEventName
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = newReadEmptyEventStream(eventReader)
}
func (es *EmptyStreamEventStream) recvInitialEvent(r *request.Request) {
// Wait for the initial response event, which must be the first
// event to be received from the API.
select {
case event, ok := <-es.Events():
if !ok {
return
}
v, ok := event.(*EmptyStreamOutput)
if !ok || v == nil {
r.Error = awserr.New(
request.ErrCodeSerialization,
fmt.Sprintf("invalid event, %T, expect %T, %v",
event, (*EmptyStreamOutput)(nil), v),
nil,
)
return
}
*es.output = *v
es.output.eventStream = es
}
}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
//
func (es *EmptyStreamEventStream) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *EmptyStreamEventStream) safeClose() {
if es.done != nil {
close(es.done)
}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *EmptyStreamEventStream) Err() error {
if err := es.err.Err(); err != nil {
return err
}
if err := es.Reader.Err(); err != nil {
return err
}
return nil
}
const opGetEventStream = "GetEventStream"
// GetEventStreamRequest generates a "aws/request.Request" representing the
// client's request for the GetEventStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetEventStream for more information on using the GetEventStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetEventStreamRequest method.
// req, resp := client.GetEventStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00/GetEventStream
func (c *RPCService) GetEventStreamRequest(input *GetEventStreamInput) (req *request.Request, output *GetEventStreamOutput) {
op := &request.Operation{
Name: opGetEventStream,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &GetEventStreamInput{}
}
output = &GetEventStreamOutput{}
req = c.newRequest(op, input, output)
es := NewGetEventStreamEventStream()
output.eventStream = es
req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, rest.UnmarshalHandler)
req.Handlers.Unmarshal.PushBack(es.runOutputStream)
es.output = output
req.Handlers.Unmarshal.PushBack(es.recvInitialEvent)
req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose)
return
}
// GetEventStream API operation for RPC Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for RPC Service's
// API operation GetEventStream for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00/GetEventStream
func (c *RPCService) GetEventStream(input *GetEventStreamInput) (*GetEventStreamOutput, error) {
req, out := c.GetEventStreamRequest(input)
return out, req.Send()
}
// GetEventStreamWithContext is the same as GetEventStream with the addition of
// the ability to pass a context and additional request options.
//
// See GetEventStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RPCService) GetEventStreamWithContext(ctx aws.Context, input *GetEventStreamInput, opts ...request.Option) (*GetEventStreamOutput, error) {
req, out := c.GetEventStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
var _ awserr.Error
// GetEventStreamEventStream provides the event stream handling for the GetEventStream.
//
// For testing and mocking the event stream this type should be initialized via
// the NewGetEventStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type GetEventStreamEventStream struct {
// Reader is the EventStream reader for the EventStream
// events. This value is automatically set by the SDK when the API call is made
// Use this member when unit testing your code with the SDK to mock out the
// EventStream Reader.
//
// Must not be nil.
Reader EventStreamReader
outputReader io.ReadCloser
output *GetEventStreamOutput
done chan struct{}
closeOnce sync.Once
err *eventstreamapi.OnceError
}
// NewGetEventStreamEventStream initializes an GetEventStreamEventStream.
// This function should only be used for testing and mocking the GetEventStreamEventStream
// stream within your application.
//
// The Reader member must be set before reading events from the stream.
//
// es := NewGetEventStreamEventStream(func(o *GetEventStreamEventStream{
// es.Reader = myMockStreamReader
// })
func NewGetEventStreamEventStream(opts ...func(*GetEventStreamEventStream)) *GetEventStreamEventStream {
es := &GetEventStreamEventStream{
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
for _, fn := range opts {
fn(es)
}
return es
}
func (es *GetEventStreamEventStream) runOnStreamPartClose(r *request.Request) {
if es.done == nil {
return
}
go es.waitStreamPartClose()
}
func (es *GetEventStreamEventStream) waitStreamPartClose() {
var outputErrCh <-chan struct{}
if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok {
outputErrCh = v.ErrorSet()
}
var outputClosedCh <-chan struct{}
if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
outputClosedCh = v.Closed()
}
select {
case <-es.done:
case <-outputErrCh:
es.err.SetError(es.Reader.Err())
es.Close()
case <-outputClosedCh:
if err := es.Reader.Err(); err != nil {
es.err.SetError(es.Reader.Err())
}
es.Close()
}
}
type eventTypeForGetEventStreamEventStreamOutputEvent struct {
unmarshalerForEvent func(string) (eventstreamapi.Unmarshaler, error)
output *GetEventStreamOutput
}
func (e eventTypeForGetEventStreamEventStreamOutputEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
if eventType == "initial-response" {
return e.output, nil
}
return e.unmarshalerForEvent(eventType)
}
// Events returns a channel to read events from.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
// * EventStreamUnknownEvent
func (es *GetEventStreamEventStream) Events() <-chan EventStreamEvent {
return es.Reader.Events()
}
func (es *GetEventStreamEventStream) runOutputStream(r *request.Request) {
var opts []func(*eventstream.Decoder)
if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) {
opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger))
}
unmarshalerForEvent := unmarshalerForEventStreamEvent{
metadata: protocol.ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
},
}.UnmarshalerForEventName
unmarshalerForEvent = eventTypeForGetEventStreamEventStreamOutputEvent{
unmarshalerForEvent: unmarshalerForEvent,
output: es.output,
}.UnmarshalerForEventName
decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...)
eventReader := eventstreamapi.NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: r.Handlers.UnmarshalStream,
},
unmarshalerForEvent,
)
es.outputReader = r.HTTPResponse.Body
es.Reader = newReadEventStream(eventReader)
}
func (es *GetEventStreamEventStream) recvInitialEvent(r *request.Request) {
// Wait for the initial response event, which must be the first
// event to be received from the API.
select {
case event, ok := <-es.Events():
if !ok {
return
}
v, ok := event.(*GetEventStreamOutput)
if !ok || v == nil {
r.Error = awserr.New(
request.ErrCodeSerialization,
fmt.Sprintf("invalid event, %T, expect %T, %v",
event, (*GetEventStreamOutput)(nil), v),
nil,
)
return
}
*es.output = *v
es.output.eventStream = es
}
}
// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// You can use the closing of the Reader's Events channel to terminate your
// application's read from the API's stream.
//
func (es *GetEventStreamEventStream) Close() (err error) {
es.closeOnce.Do(es.safeClose)
return es.Err()
}
func (es *GetEventStreamEventStream) safeClose() {
if es.done != nil {
close(es.done)
}
es.Reader.Close()
if es.outputReader != nil {
es.outputReader.Close()
}
}
// Err returns any error that occurred while reading or writing EventStream
// Events from the service API's response. Returns nil if there were no errors.
func (es *GetEventStreamEventStream) Err() error {
if err := es.err.Err(); err != nil {
return err
}
if err := es.Reader.Err(); err != nil {
return err
}
return nil
}
const opOtherOperation = "OtherOperation"
// OtherOperationRequest generates a "aws/request.Request" representing the
// client's request for the OtherOperation operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OtherOperation for more information on using the OtherOperation
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OtherOperationRequest method.
// req, resp := client.OtherOperationRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00/OtherOperation
func (c *RPCService) OtherOperationRequest(input *OtherOperationInput) (req *request.Request, output *OtherOperationOutput) {
op := &request.Operation{
Name: opOtherOperation,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &OtherOperationInput{}
}
output = &OtherOperationOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// OtherOperation API operation for RPC Service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for RPC Service's
// API operation OtherOperation for usage and error information.
//
// Returned Error Types:
// * ExceptionEvent2
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00/OtherOperation
func (c *RPCService) OtherOperation(input *OtherOperationInput) (*OtherOperationOutput, error) {
req, out := c.OtherOperationRequest(input)
return out, req.Send()
}
// OtherOperationWithContext is the same as OtherOperation with the addition of
// the ability to pass a context and additional request options.
//
// See OtherOperation for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RPCService) OtherOperationWithContext(ctx aws.Context, input *OtherOperationInput, opts ...request.Option) (*OtherOperationOutput, error) {
req, out := c.OtherOperationRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type EmptyEvent struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s EmptyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyEvent) GoString() string {
return s.String()
}
// The EmptyEvent is and event in the EventStream group of events.
func (s *EmptyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *EmptyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *EmptyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
return msg, err
}
// EmptyEventStreamEvent groups together all EventStream
// events writes for EmptyEventStream.
//
// These events are:
//
type EmptyEventStreamEvent interface {
eventEmptyEventStream()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
// EmptyEventStreamReader provides the interface for reading to the stream. The
// default implementation for this interface will be EmptyEventStream.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
//
// * EmptyEventStreamUnknownEvent
type EmptyEventStreamReader interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan EmptyEventStreamEvent
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type readEmptyEventStream struct {
eventReader *eventstreamapi.EventReader
stream chan EmptyEventStreamEvent
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func newReadEmptyEventStream(eventReader *eventstreamapi.EventReader) *readEmptyEventStream {
r := &readEmptyEventStream{
eventReader: eventReader,
stream: make(chan EmptyEventStreamEvent),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *readEmptyEventStream) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *readEmptyEventStream) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *readEmptyEventStream) Closed() <-chan struct{} {
return r.done
}
func (r *readEmptyEventStream) safeClose() {
close(r.done)
}
func (r *readEmptyEventStream) Err() error {
return r.err.Err()
}
func (r *readEmptyEventStream) Events() <-chan EmptyEventStreamEvent {
return r.stream
}
func (r *readEmptyEventStream) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.(EmptyEventStreamEvent):
case <-r.done:
return
}
}
}
type unmarshalerForEmptyEventStreamEvent struct {
metadata protocol.ResponseMetadata
}
func (u unmarshalerForEmptyEventStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
default:
return &EmptyEventStreamUnknownEvent{Type: eventType}, nil
}
}
// EmptyEventStreamUnknownEvent provides a failsafe event for the
// EmptyEventStream group of events when an unknown event is received.
type EmptyEventStreamUnknownEvent struct {
Type string
Message eventstream.Message
}
// The EmptyEventStreamUnknownEvent is and event in the EmptyEventStream
// group of events.
func (s *EmptyEventStreamUnknownEvent) eventEmptyEventStream() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *EmptyEventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyEventStream value.
// This method is only used internally within the SDK's EventStream handling.
func (e *EmptyEventStreamUnknownEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
type EmptyStreamInput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s EmptyStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyStreamInput) GoString() string {
return s.String()
}
type EmptyStreamOutput struct {
_ struct{} `type:"structure"`
eventStream *EmptyStreamEventStream
}
// String returns the string representation
func (s EmptyStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s EmptyStreamOutput) GoString() string {
return s.String()
}
// GetStream returns the type to interact with the event stream.
func (s *EmptyStreamOutput) GetStream() *EmptyStreamEventStream {
return s.eventStream
}
// The EmptyStreamOutput is and event in the EmptyEventStream group of events.
func (s *EmptyStreamOutput) eventEmptyEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the EmptyStreamOutput value.
// This method is only used internally within the SDK's EventStream handling.
func (s *EmptyStreamOutput) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *EmptyStreamOutput) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
// EventStreamEvent groups together all EventStream
// events writes for EventStream.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
type EventStreamEvent interface {
eventEventStream()
eventstreamapi.Marshaler
eventstreamapi.Unmarshaler
}
// EventStreamReader provides the interface for reading to the stream. The
// default implementation for this interface will be EventStream.
//
// The reader's Close method must allow multiple concurrent calls.
//
// These events are:
//
// * EmptyEvent
// * ExplicitPayloadEvent
// * HeaderOnlyEvent
// * ImplicitPayloadEvent
// * PayloadOnlyEvent
// * PayloadOnlyBlobEvent
// * PayloadOnlyStringEvent
// * EventStreamUnknownEvent
type EventStreamReader interface {
// Returns a channel of events as they are read from the event stream.
Events() <-chan EventStreamEvent
// Close will stop the reader reading events from the stream.
Close() error
// Returns any error that has occurred while reading from the event stream.
Err() error
}
type readEventStream struct {
eventReader *eventstreamapi.EventReader
stream chan EventStreamEvent
err *eventstreamapi.OnceError
done chan struct{}
closeOnce sync.Once
}
func newReadEventStream(eventReader *eventstreamapi.EventReader) *readEventStream {
r := &readEventStream{
eventReader: eventReader,
stream: make(chan EventStreamEvent),
done: make(chan struct{}),
err: eventstreamapi.NewOnceError(),
}
go r.readEventStream()
return r
}
// Close will close the underlying event stream reader.
func (r *readEventStream) Close() error {
r.closeOnce.Do(r.safeClose)
return r.Err()
}
func (r *readEventStream) ErrorSet() <-chan struct{} {
return r.err.ErrorSet()
}
func (r *readEventStream) Closed() <-chan struct{} {
return r.done
}
func (r *readEventStream) safeClose() {
close(r.done)
}
func (r *readEventStream) Err() error {
return r.err.Err()
}
func (r *readEventStream) Events() <-chan EventStreamEvent {
return r.stream
}
func (r *readEventStream) readEventStream() {
defer r.Close()
defer close(r.stream)
for {
event, err := r.eventReader.ReadEvent()
if err != nil {
if err == io.EOF {
return
}
select {
case <-r.done:
// If closed already ignore the error
return
default:
}
if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok {
continue
}
r.err.SetError(err)
return
}
select {
case r.stream <- event.(EventStreamEvent):
case <-r.done:
return
}
}
}
type unmarshalerForEventStreamEvent struct {
metadata protocol.ResponseMetadata
}
func (u unmarshalerForEventStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) {
switch eventType {
case "Empty":
return &EmptyEvent{}, nil
case "ExplicitPayload":
return &ExplicitPayloadEvent{}, nil
case "Headers":
return &HeaderOnlyEvent{}, nil
case "ImplicitPayload":
return &ImplicitPayloadEvent{}, nil
case "PayloadOnly":
return &PayloadOnlyEvent{}, nil
case "PayloadOnlyBlob":
return &PayloadOnlyBlobEvent{}, nil
case "PayloadOnlyString":
return &PayloadOnlyStringEvent{}, nil
case "Exception":
return newErrorExceptionEvent(u.metadata).(eventstreamapi.Unmarshaler), nil
case "Exception2":
return newErrorExceptionEvent2(u.metadata).(eventstreamapi.Unmarshaler), nil
default:
return &EventStreamUnknownEvent{Type: eventType}, nil
}
}
// EventStreamUnknownEvent provides a failsafe event for the
// EventStream group of events when an unknown event is received.
type EventStreamUnknownEvent struct {
Type string
Message eventstream.Message
}
// The EventStreamUnknownEvent is and event in the EventStream
// group of events.
func (s *EventStreamUnknownEvent) eventEventStream() {}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (e *EventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) (
msg eventstream.Message, err error,
) {
return e.Message.Clone(), nil
}
// UnmarshalEvent unmarshals the EventStream Message into the EventStream value.
// This method is only used internally within the SDK's EventStream handling.
func (e *EventStreamUnknownEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Message = msg.Clone()
return nil
}
type ExceptionEvent struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
IntVal *int64 `type:"integer"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation
func (s ExceptionEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExceptionEvent) GoString() string {
return s.String()
}
// The ExceptionEvent is and event in the EventStream group of events.
func (s *ExceptionEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExceptionEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
func newErrorExceptionEvent(v protocol.ResponseMetadata) error {
return &ExceptionEvent{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ExceptionEvent) Code() string {
return "ExceptionEvent"
}
// Message returns the exception's message.
func (s *ExceptionEvent) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ExceptionEvent) OrigErr() error {
return nil
}
func (s *ExceptionEvent) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ExceptionEvent) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ExceptionEvent) RequestID() string {
return s.RespMetadata.RequestID
}
type ExceptionEvent2 struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation
func (s ExceptionEvent2) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExceptionEvent2) GoString() string {
return s.String()
}
// The ExceptionEvent2 is and event in the EventStream group of events.
func (s *ExceptionEvent2) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExceptionEvent2 value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent2) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExceptionEvent2) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
func newErrorExceptionEvent2(v protocol.ResponseMetadata) error {
return &ExceptionEvent2{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ExceptionEvent2) Code() string {
return "ExceptionEvent2"
}
// Message returns the exception's message.
func (s *ExceptionEvent2) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ExceptionEvent2) OrigErr() error {
return nil
}
func (s *ExceptionEvent2) Error() string {
return fmt.Sprintf("%s: %s", s.Code(), s.Message())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ExceptionEvent2) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ExceptionEvent2) RequestID() string {
return s.RespMetadata.RequestID
}
type ExplicitPayloadEvent struct {
_ struct{} `type:"structure" payload:"NestedVal"`
LongVal *int64 `location:"header" type:"long"`
NestedVal *NestedShape `locationName:"NestedVal" type:"structure"`
StringVal *string `location:"header" type:"string"`
}
// String returns the string representation
func (s ExplicitPayloadEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ExplicitPayloadEvent) GoString() string {
return s.String()
}
// SetLongVal sets the LongVal field's value.
func (s *ExplicitPayloadEvent) SetLongVal(v int64) *ExplicitPayloadEvent {
s.LongVal = &v
return s
}
// SetNestedVal sets the NestedVal field's value.
func (s *ExplicitPayloadEvent) SetNestedVal(v *NestedShape) *ExplicitPayloadEvent {
s.NestedVal = v
return s
}
// SetStringVal sets the StringVal field's value.
func (s *ExplicitPayloadEvent) SetStringVal(v string) *ExplicitPayloadEvent {
s.StringVal = &v
return s
}
// The ExplicitPayloadEvent is and event in the EventStream group of events.
func (s *ExplicitPayloadEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ExplicitPayloadEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ExplicitPayloadEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("LongVal"); hv != nil {
v := hv.Get().(int64)
s.LongVal = &v
}
if hv := msg.Headers.Get("StringVal"); hv != nil {
v := hv.Get().(string)
s.StringVal = &v
}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ExplicitPayloadEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("LongVal", eventstream.Int64Value(*s.LongVal))
msg.Headers.Set("StringVal", eventstream.StringValue(*s.StringVal))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type GetEventStreamInput struct {
_ struct{} `type:"structure"`
InputVal *string `type:"string"`
}
// String returns the string representation
func (s GetEventStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetEventStreamInput) GoString() string {
return s.String()
}
// SetInputVal sets the InputVal field's value.
func (s *GetEventStreamInput) SetInputVal(v string) *GetEventStreamInput {
s.InputVal = &v
return s
}
type GetEventStreamOutput struct {
_ struct{} `type:"structure"`
eventStream *GetEventStreamEventStream
IntVal *int64 `type:"integer"`
StrVal *string `type:"string"`
}
// String returns the string representation
func (s GetEventStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetEventStreamOutput) GoString() string {
return s.String()
}
// SetIntVal sets the IntVal field's value.
func (s *GetEventStreamOutput) SetIntVal(v int64) *GetEventStreamOutput {
s.IntVal = &v
return s
}
// SetStrVal sets the StrVal field's value.
func (s *GetEventStreamOutput) SetStrVal(v string) *GetEventStreamOutput {
s.StrVal = &v
return s
}
// GetStream returns the type to interact with the event stream.
func (s *GetEventStreamOutput) GetStream() *GetEventStreamEventStream {
return s.eventStream
}
// The GetEventStreamOutput is and event in the EventStream group of events.
func (s *GetEventStreamOutput) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the GetEventStreamOutput value.
// This method is only used internally within the SDK's EventStream handling.
func (s *GetEventStreamOutput) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *GetEventStreamOutput) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type HeaderOnlyEvent struct {
_ struct{} `type:"structure"`
// BlobVal is automatically base64 encoded/decoded by the SDK.
BlobVal []byte `location:"header" type:"blob"`
BoolVal *bool `location:"header" type:"boolean"`
ByteVal *int64 `location:"header" type:"byte"`
IntegerVal *int64 `location:"header" type:"integer"`
LongVal *int64 `location:"header" type:"long"`
ShortVal *int64 `location:"header" type:"short"`
StringVal *string `location:"header" type:"string"`
TimeVal *time.Time `location:"header" type:"timestamp"`
}
// String returns the string representation
func (s HeaderOnlyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s HeaderOnlyEvent) GoString() string {
return s.String()
}
// SetBlobVal sets the BlobVal field's value.
func (s *HeaderOnlyEvent) SetBlobVal(v []byte) *HeaderOnlyEvent {
s.BlobVal = v
return s
}
// SetBoolVal sets the BoolVal field's value.
func (s *HeaderOnlyEvent) SetBoolVal(v bool) *HeaderOnlyEvent {
s.BoolVal = &v
return s
}
// SetByteVal sets the ByteVal field's value.
func (s *HeaderOnlyEvent) SetByteVal(v int64) *HeaderOnlyEvent {
s.ByteVal = &v
return s
}
// SetIntegerVal sets the IntegerVal field's value.
func (s *HeaderOnlyEvent) SetIntegerVal(v int64) *HeaderOnlyEvent {
s.IntegerVal = &v
return s
}
// SetLongVal sets the LongVal field's value.
func (s *HeaderOnlyEvent) SetLongVal(v int64) *HeaderOnlyEvent {
s.LongVal = &v
return s
}
// SetShortVal sets the ShortVal field's value.
func (s *HeaderOnlyEvent) SetShortVal(v int64) *HeaderOnlyEvent {
s.ShortVal = &v
return s
}
// SetStringVal sets the StringVal field's value.
func (s *HeaderOnlyEvent) SetStringVal(v string) *HeaderOnlyEvent {
s.StringVal = &v
return s
}
// SetTimeVal sets the TimeVal field's value.
func (s *HeaderOnlyEvent) SetTimeVal(v time.Time) *HeaderOnlyEvent {
s.TimeVal = &v
return s
}
// The HeaderOnlyEvent is and event in the EventStream group of events.
func (s *HeaderOnlyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the HeaderOnlyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *HeaderOnlyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("BlobVal"); hv != nil {
v := hv.Get().([]byte)
s.BlobVal = v
}
if hv := msg.Headers.Get("BoolVal"); hv != nil {
v := hv.Get().(bool)
s.BoolVal = &v
}
if hv := msg.Headers.Get("ByteVal"); hv != nil {
v := hv.Get().(int8)
m := int64(v)
s.ByteVal = &m
}
if hv := msg.Headers.Get("IntegerVal"); hv != nil {
v := hv.Get().(int32)
m := int64(v)
s.IntegerVal = &m
}
if hv := msg.Headers.Get("LongVal"); hv != nil {
v := hv.Get().(int64)
s.LongVal = &v
}
if hv := msg.Headers.Get("ShortVal"); hv != nil {
v := hv.Get().(int16)
m := int64(v)
s.ShortVal = &m
}
if hv := msg.Headers.Get("StringVal"); hv != nil {
v := hv.Get().(string)
s.StringVal = &v
}
if hv := msg.Headers.Get("TimeVal"); hv != nil {
v := hv.Get().(time.Time)
s.TimeVal = &v
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *HeaderOnlyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("BlobVal", eventstream.BytesValue(s.BlobVal))
msg.Headers.Set("BoolVal", eventstream.BoolValue(*s.BoolVal))
msg.Headers.Set("ByteVal", eventstream.Int8Value(int8(*s.ByteVal)))
msg.Headers.Set("IntegerVal", eventstream.Int32Value(int32(*s.IntegerVal)))
msg.Headers.Set("LongVal", eventstream.Int64Value(*s.LongVal))
msg.Headers.Set("ShortVal", eventstream.Int16Value(int16(*s.ShortVal)))
msg.Headers.Set("StringVal", eventstream.StringValue(*s.StringVal))
msg.Headers.Set("TimeVal", eventstream.TimestampValue(*s.TimeVal))
return msg, err
}
type ImplicitPayloadEvent struct {
_ struct{} `type:"structure"`
ByteVal *int64 `location:"header" type:"byte"`
IntegerVal *int64 `type:"integer"`
ShortVal *int64 `type:"short"`
}
// String returns the string representation
func (s ImplicitPayloadEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ImplicitPayloadEvent) GoString() string {
return s.String()
}
// SetByteVal sets the ByteVal field's value.
func (s *ImplicitPayloadEvent) SetByteVal(v int64) *ImplicitPayloadEvent {
s.ByteVal = &v
return s
}
// SetIntegerVal sets the IntegerVal field's value.
func (s *ImplicitPayloadEvent) SetIntegerVal(v int64) *ImplicitPayloadEvent {
s.IntegerVal = &v
return s
}
// SetShortVal sets the ShortVal field's value.
func (s *ImplicitPayloadEvent) SetShortVal(v int64) *ImplicitPayloadEvent {
s.ShortVal = &v
return s
}
// The ImplicitPayloadEvent is and event in the EventStream group of events.
func (s *ImplicitPayloadEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the ImplicitPayloadEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *ImplicitPayloadEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if hv := msg.Headers.Get("ByteVal"); hv != nil {
v := hv.Get().(int8)
m := int64(v)
s.ByteVal = &m
}
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *ImplicitPayloadEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set("ByteVal", eventstream.Int8Value(int8(*s.ByteVal)))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type NestedShape struct {
_ struct{} `type:"structure"`
IntVal *int64 `type:"integer"`
StrVal *string `type:"string"`
}
// String returns the string representation
func (s NestedShape) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s NestedShape) GoString() string {
return s.String()
}
// SetIntVal sets the IntVal field's value.
func (s *NestedShape) SetIntVal(v int64) *NestedShape {
s.IntVal = &v
return s
}
// SetStrVal sets the StrVal field's value.
func (s *NestedShape) SetStrVal(v string) *NestedShape {
s.StrVal = &v
return s
}
type OtherOperationInput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s OtherOperationInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s OtherOperationInput) GoString() string {
return s.String()
}
type OtherOperationOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s OtherOperationOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s OtherOperationOutput) GoString() string {
return s.String()
}
type PayloadOnlyBlobEvent struct {
_ struct{} `type:"structure" payload:"BlobPayload"`
// BlobPayload is automatically base64 encoded/decoded by the SDK.
BlobPayload []byte `type:"blob"`
}
// String returns the string representation
func (s PayloadOnlyBlobEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyBlobEvent) GoString() string {
return s.String()
}
// SetBlobPayload sets the BlobPayload field's value.
func (s *PayloadOnlyBlobEvent) SetBlobPayload(v []byte) *PayloadOnlyBlobEvent {
s.BlobPayload = v
return s
}
// The PayloadOnlyBlobEvent is and event in the EventStream group of events.
func (s *PayloadOnlyBlobEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyBlobEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyBlobEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
s.BlobPayload = make([]byte, len(msg.Payload))
copy(s.BlobPayload, msg.Payload)
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyBlobEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Headers.Set(":content-type", eventstream.StringValue("application/octet-stream"))
msg.Payload = s.BlobPayload
return msg, err
}
type PayloadOnlyEvent struct {
_ struct{} `type:"structure" payload:"NestedVal"`
NestedVal *NestedShape `locationName:"NestedVal" type:"structure"`
}
// String returns the string representation
func (s PayloadOnlyEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyEvent) GoString() string {
return s.String()
}
// SetNestedVal sets the NestedVal field's value.
func (s *PayloadOnlyEvent) SetNestedVal(v *NestedShape) *PayloadOnlyEvent {
s.NestedVal = v
return s
}
// The PayloadOnlyEvent is and event in the EventStream group of events.
func (s *PayloadOnlyEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
if err := payloadUnmarshaler.UnmarshalPayload(
bytes.NewReader(msg.Payload), s,
); err != nil {
return err
}
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
var buf bytes.Buffer
if err = pm.MarshalPayload(&buf, s); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, err
}
type PayloadOnlyStringEvent struct {
_ struct{} `type:"structure" payload:"StringPayload"`
StringPayload *string `locationName:"StringPayload" type:"string"`
}
// String returns the string representation
func (s PayloadOnlyStringEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PayloadOnlyStringEvent) GoString() string {
return s.String()
}
// SetStringPayload sets the StringPayload field's value.
func (s *PayloadOnlyStringEvent) SetStringPayload(v string) *PayloadOnlyStringEvent {
s.StringPayload = &v
return s
}
// The PayloadOnlyStringEvent is and event in the EventStream group of events.
func (s *PayloadOnlyStringEvent) eventEventStream() {}
// UnmarshalEvent unmarshals the EventStream Message into the PayloadOnlyStringEvent value.
// This method is only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyStringEvent) UnmarshalEvent(
payloadUnmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
s.StringPayload = aws.String(string(msg.Payload))
return nil
}
// MarshalEvent marshals the type into an stream event value. This method
// should only used internally within the SDK's EventStream handling.
func (s *PayloadOnlyStringEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) {
msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType))
msg.Payload = []byte(aws.StringValue(s.StringPayload))
return msg, err
}
| 1,819 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package rpcservice provides the client and types for making API
// requests to RPC Service.
//
// See https://docs.aws.amazon.com/goto/WebAPI/RPCService-0000-00-00 for more information on this service.
//
// See rpcservice package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/rpcservice/
//
// Using the Client
//
// To contact RPC Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the RPC Service client RPCService for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/rpcservice/#New
package rpcservice
| 27 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rpcservice
import (
"github.com/aws/aws-sdk-go/private/protocol"
)
const (
// ErrCodeExceptionEvent for service response error code
// "ExceptionEvent".
ErrCodeExceptionEvent = "ExceptionEvent"
// ErrCodeExceptionEvent2 for service response error code
// "ExceptionEvent2".
ErrCodeExceptionEvent2 = "ExceptionEvent2"
)
var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"ExceptionEvent": newErrorExceptionEvent,
"ExceptionEvent2": newErrorExceptionEvent2,
}
| 24 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// +build go1.15
package rpcservice
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamtest"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)
var _ time.Time
var _ awserr.Error
var _ context.Context
var _ sync.WaitGroup
var _ strings.Reader
func TestEmptyStream_Read(t *testing.T) {
expectEvents, eventMsgs := mockEmptyStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
// Trim off response output type pseudo event so only event messages remain.
expectEvents = expectEvents[1:]
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestEmptyStream_ReadClose(t *testing.T) {
_, eventMsgs := mockEmptyStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestEmptyStream_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mockEmptyStreamReadEvents()
eventOffset := 1
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]EmptyEventStreamEvent{
&EmptyEventStreamUnknownEvent{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.EmptyStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
// Trim off response output type pseudo event so only event messages remain.
expectEvents = expectEvents[1:]
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func BenchmarkEmptyStream_Read(b *testing.B) {
_, eventMsgs := mockEmptyStreamReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.EmptyStream(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mockEmptyStreamReadEvents() (
[]EmptyEventStreamEvent,
[]eventstream.Message,
) {
expectEvents := []EmptyEventStreamEvent{
&EmptyStreamOutput{},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(jsonrpc.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("initial-response"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[0]),
},
}
return expectEvents, eventMsgs
}
func TestGetEventStream_Read(t *testing.T) {
expectEvents, eventMsgs := mockGetEventStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
expectResp := expectEvents[0].(*GetEventStreamOutput)
if e, a := expectResp.IntVal, resp.IntVal; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectResp.StrVal, resp.StrVal; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
// Trim off response output type pseudo event so only event messages remain.
expectEvents = expectEvents[1:]
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestGetEventStream_ReadClose(t *testing.T) {
_, eventMsgs := mockGetEventStreamReadEvents()
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
// Assert calling Err before close does not close the stream.
resp.GetStream().Err()
select {
case _, ok := <-resp.GetStream().Events():
if !ok {
t.Fatalf("expect stream not to be closed, but was")
}
default:
}
resp.GetStream().Close()
<-resp.GetStream().Events()
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func TestGetEventStream_ReadUnknownEvent(t *testing.T) {
expectEvents, eventMsgs := mockGetEventStreamReadEvents()
eventOffset := 1
unknownEvent := eventstream.Message{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("UnknownEventName"),
},
},
Payload: []byte("some unknown event"),
}
eventMsgs = append(eventMsgs[:eventOffset],
append([]eventstream.Message{unknownEvent}, eventMsgs[eventOffset:]...)...)
expectEvents = append(expectEvents[:eventOffset],
append([]EventStreamEvent{
&EventStreamUnknownEvent{
Type: "UnknownEventName",
Message: unknownEvent,
},
},
expectEvents[eventOffset:]...)...)
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
// Trim off response output type pseudo event so only event messages remain.
expectEvents = expectEvents[1:]
var i int
for event := range resp.GetStream().Events() {
if event == nil {
t.Errorf("%d, expect event, got nil", i)
}
if e, a := expectEvents[i], event; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %T %v, got %T %v", i, e, e, a, a)
}
i++
}
if err := resp.GetStream().Err(); err != nil {
t.Errorf("expect no error, %v", err)
}
}
func BenchmarkGetEventStream_Read(b *testing.B) {
_, eventMsgs := mockGetEventStreamReadEvents()
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
for _, msg := range eventMsgs {
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
}
stream := &loopReader{source: bytes.NewReader(buf.Bytes())}
sess := unit.Session
svc := New(sess, &aws.Config{
Endpoint: aws.String("https://example.com"),
DisableParamValidation: aws.Bool(true),
})
svc.Handlers.Send.Swap(corehandlers.SendHandler.Name,
request.NamedHandler{Name: "mockSend",
Fn: func(r *request.Request) {
r.HTTPResponse = &http.Response{
Status: "200 OK",
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(stream),
}
},
},
)
resp, err := svc.GetEventStream(nil)
if err != nil {
b.Fatalf("failed to create request, %v", err)
}
defer resp.GetStream().Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err = resp.GetStream().Err(); err != nil {
b.Fatalf("expect no error, got %v", err)
}
event := <-resp.GetStream().Events()
if event == nil {
b.Fatalf("expect event, got nil, %v, %d", resp.GetStream().Err(), i)
}
}
}
func mockGetEventStreamReadEvents() (
[]EventStreamEvent,
[]eventstream.Message,
) {
expectEvents := []EventStreamEvent{
&GetEventStreamOutput{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
&EmptyEvent{},
&ExplicitPayloadEvent{
LongVal: aws.Int64(1234),
NestedVal: &NestedShape{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
StringVal: aws.String("string value goes here"),
},
&HeaderOnlyEvent{
BlobVal: []byte("blob value goes here"),
BoolVal: aws.Bool(true),
ByteVal: aws.Int64(1),
IntegerVal: aws.Int64(123),
LongVal: aws.Int64(1234),
ShortVal: aws.Int64(12),
StringVal: aws.String("string value goes here"),
TimeVal: aws.Time(time.Unix(1396594860, 0).UTC()),
},
&ImplicitPayloadEvent{
ByteVal: aws.Int64(1),
IntegerVal: aws.Int64(123),
ShortVal: aws.Int64(12),
},
&PayloadOnlyEvent{
NestedVal: &NestedShape{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
},
&PayloadOnlyBlobEvent{
BlobPayload: []byte("blob value goes here"),
},
&PayloadOnlyStringEvent{
StringPayload: aws.String("string value goes here"),
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(jsonrpc.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
_ = payloadMarshaler
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("initial-response"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[0]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("Empty"),
},
},
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("ExplicitPayload"),
},
{
Name: "LongVal",
Value: eventstream.Int64Value(*expectEvents[2].(*ExplicitPayloadEvent).LongVal),
},
{
Name: "StringVal",
Value: eventstream.StringValue(*expectEvents[2].(*ExplicitPayloadEvent).StringVal),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[2]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("Headers"),
},
{
Name: "BlobVal",
Value: eventstream.BytesValue(expectEvents[3].(*HeaderOnlyEvent).BlobVal),
},
{
Name: "BoolVal",
Value: eventstream.BoolValue(*expectEvents[3].(*HeaderOnlyEvent).BoolVal),
},
{
Name: "ByteVal",
Value: eventstream.Int8Value(int8(*expectEvents[3].(*HeaderOnlyEvent).ByteVal)),
},
{
Name: "IntegerVal",
Value: eventstream.Int32Value(int32(*expectEvents[3].(*HeaderOnlyEvent).IntegerVal)),
},
{
Name: "LongVal",
Value: eventstream.Int64Value(*expectEvents[3].(*HeaderOnlyEvent).LongVal),
},
{
Name: "ShortVal",
Value: eventstream.Int16Value(int16(*expectEvents[3].(*HeaderOnlyEvent).ShortVal)),
},
{
Name: "StringVal",
Value: eventstream.StringValue(*expectEvents[3].(*HeaderOnlyEvent).StringVal),
},
{
Name: "TimeVal",
Value: eventstream.TimestampValue(*expectEvents[3].(*HeaderOnlyEvent).TimeVal),
},
},
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("ImplicitPayload"),
},
{
Name: "ByteVal",
Value: eventstream.Int8Value(int8(*expectEvents[4].(*ImplicitPayloadEvent).ByteVal)),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[4]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnly"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[5]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnlyBlob"),
},
},
Payload: expectEvents[6].(*PayloadOnlyBlobEvent).BlobPayload,
},
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("PayloadOnlyString"),
},
},
Payload: []byte(*expectEvents[7].(*PayloadOnlyStringEvent).StringPayload),
},
}
return expectEvents, eventMsgs
}
func TestGetEventStream_ReadException(t *testing.T) {
expectEvents := []EventStreamEvent{
&GetEventStreamOutput{
IntVal: aws.Int64(123),
StrVal: aws.String("string value goes here"),
},
&ExceptionEvent{
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
IntVal: aws.Int64(123),
Message_: aws.String("string value goes here"),
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(jsonrpc.BuildHandler)
payloadMarshaler := protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
}
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstreamtest.EventMessageTypeHeader,
{
Name: eventstreamapi.EventTypeHeader,
Value: eventstream.StringValue("initial-response"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[0]),
},
{
Headers: eventstream.Headers{
eventstreamtest.EventExceptionTypeHeader,
{
Name: eventstreamapi.ExceptionTypeHeader,
Value: eventstream.StringValue("Exception"),
},
},
Payload: eventstreamtest.MarshalEventPayload(payloadMarshaler, expectEvents[1]),
},
}
sess, cleanupFn, err := eventstreamtest.SetupEventStreamSession(t,
eventstreamtest.ServeEventStream{
T: t,
Events: eventMsgs,
},
true,
)
if err != nil {
t.Fatalf("expect no error, %v", err)
}
defer cleanupFn()
svc := New(sess)
resp, err := svc.GetEventStream(nil)
if err != nil {
t.Fatalf("expect no error got, %v", err)
}
defer resp.GetStream().Close()
<-resp.GetStream().Events()
err = resp.GetStream().Err()
if err == nil {
t.Fatalf("expect err, got none")
}
expectErr := &ExceptionEvent{
RespMetadata: protocol.ResponseMetadata{
StatusCode: 200,
},
IntVal: aws.Int64(123),
Message_: aws.String("string value goes here"),
}
aerr, ok := err.(awserr.Error)
if !ok {
t.Errorf("expect exception, got %T, %#v", err, err)
}
if e, a := expectErr.Code(), aerr.Code(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr.Message(), aerr.Message(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := expectErr, aerr; !reflect.DeepEqual(e, a) {
t.Errorf("expect error %+#v, got %+#v", e, a)
}
}
var _ awserr.Error = (*ExceptionEvent)(nil)
var _ awserr.Error = (*ExceptionEvent2)(nil)
type loopReader struct {
source *bytes.Reader
}
func (c *loopReader) Read(p []byte) (int, error) {
if c.source.Len() == 0 {
c.source.Seek(0, 0)
}
return c.source.Read(p)
}
| 729 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rpcservice
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)
// RPCService provides the API operation methods for making requests to
// RPC Service. See this package's package overview docs
// for details on the service.
//
// RPCService methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type RPCService struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "RPCService" // Name of service.
EndpointsID = "rpcservice" // ID to lookup a service endpoint with.
ServiceID = "RPCService" // ServiceID is a unique identifier of a specific service.
)
// New creates a new instance of the RPCService client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a RPCService client from just a session.
// svc := rpcservice.New(mySession)
//
// // Create a RPCService client with additional configuration
// svc := rpcservice.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *RPCService {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *RPCService {
svc := &RPCService{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "0000-00-00",
JSONVersion: "1.1",
TargetPrefix: "RPCService_00000000",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(
protocol.NewUnmarshalErrorHandler(jsonrpc.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(),
)
svc.Handlers.BuildStream.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.UnmarshalStream.PushBackNamed(jsonrpc.UnmarshalHandler)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a RPCService operation and runs any
// custom request initialization.
func (c *RPCService) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
| 107 |
session-manager-plugin | aws | Go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package rpcserviceiface provides an interface to enable mocking the RPC Service service client
// for testing your code.
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters.
package rpcserviceiface
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/model/api/codegentest/service/rpcservice"
)
// RPCServiceAPI provides an interface to enable mocking the
// rpcservice.RPCService service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
// // myFunc uses an SDK service client to make a request to
// // RPC Service.
// func myFunc(svc rpcserviceiface.RPCServiceAPI) bool {
// // Make svc.EmptyStream request
// }
//
// func main() {
// sess := session.New()
// svc := rpcservice.New(sess)
//
// myFunc(svc)
// }
//
// In your _test.go file:
//
// // Define a mock struct to be used in your unit tests of myFunc.
// type mockRPCServiceClient struct {
// rpcserviceiface.RPCServiceAPI
// }
// func (m *mockRPCServiceClient) EmptyStream(input *rpcservice.EmptyStreamInput) (*rpcservice.EmptyStreamOutput, error) {
// // mock response/functionality
// }
//
// func TestMyFunc(t *testing.T) {
// // Setup Test
// mockSvc := &mockRPCServiceClient{}
//
// myfunc(mockSvc)
//
// // Verify myFunc's functionality
// }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type RPCServiceAPI interface {
EmptyStream(*rpcservice.EmptyStreamInput) (*rpcservice.EmptyStreamOutput, error)
EmptyStreamWithContext(aws.Context, *rpcservice.EmptyStreamInput, ...request.Option) (*rpcservice.EmptyStreamOutput, error)
EmptyStreamRequest(*rpcservice.EmptyStreamInput) (*request.Request, *rpcservice.EmptyStreamOutput)
GetEventStream(*rpcservice.GetEventStreamInput) (*rpcservice.GetEventStreamOutput, error)
GetEventStreamWithContext(aws.Context, *rpcservice.GetEventStreamInput, ...request.Option) (*rpcservice.GetEventStreamOutput, error)
GetEventStreamRequest(*rpcservice.GetEventStreamInput) (*request.Request, *rpcservice.GetEventStreamOutput)
OtherOperation(*rpcservice.OtherOperationInput) (*rpcservice.OtherOperationOutput, error)
OtherOperationWithContext(aws.Context, *rpcservice.OtherOperationInput, ...request.Option) (*rpcservice.OtherOperationOutput, error)
OtherOperationRequest(*rpcservice.OtherOperationInput) (*request.Request, *rpcservice.OtherOperationOutput)
}
var _ RPCServiceAPI = (*rpcservice.RPCService)(nil)
| 77 |
session-manager-plugin | aws | Go | // +build codegen
package main
import (
"fmt"
"os"
"path/filepath"
"sort"
"github.com/aws/aws-sdk-go/private/model/api"
)
func main() {
dir, _ := os.Open(filepath.Join("models", "apis"))
names, _ := dir.Readdirnames(0)
for _, name := range names {
m, _ := filepath.Glob(filepath.Join("models", "apis", name, "*", "api-2.json"))
if len(m) == 0 {
continue
}
sort.Strings(m)
f := m[len(m)-1]
a := api.API{}
a.Attach(f)
fmt.Printf("%s\t%s\n", a.Metadata.ServiceFullName, a.Metadata.APIVersion)
}
}
| 30 |
session-manager-plugin | aws | Go | // +build codegen
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/private/model/api"
)
func main() {
glob := filepath.FromSlash(os.Args[1])
modelPaths, err := api.ExpandModelGlobPath(glob)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to expand glob, %v\n", err)
os.Exit(1)
}
_, excluded := api.TrimModelServiceVersions(modelPaths)
for _, exclude := range excluded {
modelPath := filepath.Dir(exclude)
fmt.Println("removing:", modelPath)
os.RemoveAll(modelPath)
}
}
| 29 |
session-manager-plugin | aws | Go | // +build codegen
// Command aws-gen-gocli parses a JSON description of an AWS API and generates a
// Go file containing a client for the API.
//
// aws-gen-gocli apis/s3/2006-03-03/api-2.json
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime/debug"
"strings"
"sync"
"github.com/aws/aws-sdk-go/private/model/api"
"github.com/aws/aws-sdk-go/private/util"
)
func usage() {
fmt.Fprintln(os.Stderr, `Usage: api-gen <options> [model path | file path]
Loads API models from file and generates SDK clients from the models.
The model path arguments can be globs, or paths to individual files. The
utiliity requires that the API model files follow the following pattern:
<root>/<servicename>/<api-version>/<model json files>
e.g:
./models/apis/s3/2006-03-01/*.json
Flags:`)
flag.PrintDefaults()
}
// Generates service api, examples, and interface from api json definition files.
//
// Flags:
// -path alternative service path to write generated files to for each service.
//
// Env:
// SERVICES comma separated list of services to generate.
func main() {
var svcPath, svcImportPath string
flag.StringVar(&svcPath, "path", "service",
"The `path` to generate service clients in to.",
)
flag.StringVar(&svcImportPath, "svc-import-path",
api.SDKImportRoot+"/service",
"The Go `import path` to generate client to be under.",
)
var ignoreUnsupportedAPIs bool
flag.BoolVar(&ignoreUnsupportedAPIs, "ignore-unsupported-apis",
true,
"Ignores API models that use unsupported features",
)
flag.Usage = usage
flag.Parse()
if len(os.Getenv("AWS_SDK_CODEGEN_DEBUG")) != 0 {
api.LogDebug(os.Stdout)
}
// Make sure all paths are based on platform's pathing not Unix
globs := flag.Args()
for i, g := range globs {
globs[i] = filepath.FromSlash(g)
}
svcPath = filepath.FromSlash(svcPath)
modelPaths, err := api.ExpandModelGlobPath(globs...)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to glob file pattern", err)
os.Exit(1)
}
modelPaths, _ = api.TrimModelServiceVersions(modelPaths)
loader := api.Loader{
BaseImport: svcImportPath,
IgnoreUnsupportedAPIs: ignoreUnsupportedAPIs,
}
apis, err := loader.Load(modelPaths)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to load API models", err)
os.Exit(1)
}
if len(apis) == 0 {
fmt.Fprintf(os.Stderr, "expected to load models, but found none")
os.Exit(1)
}
if v := os.Getenv("SERVICES"); len(v) != 0 {
svcs := strings.Split(v, ",")
for pkgName, a := range apis {
var found bool
for _, include := range svcs {
if a.PackageName() == include {
found = true
break
}
}
if !found {
delete(apis, pkgName)
}
}
}
var wg sync.WaitGroup
servicePaths := map[string]struct{}{}
for _, a := range apis {
if _, ok := excludeServices[a.PackageName()]; ok {
continue
}
// Create the output path for the model.
pkgDir := filepath.Join(svcPath, a.PackageName())
os.MkdirAll(filepath.Join(pkgDir, a.InterfacePackageName()), 0775)
if _, ok := servicePaths[pkgDir]; ok {
fmt.Fprintf(os.Stderr,
"attempted to generate a client into %s twice. Second model package, %v\n",
pkgDir, a.PackageName())
os.Exit(1)
}
servicePaths[pkgDir] = struct{}{}
g := &generateInfo{
API: a,
PackageDir: pkgDir,
}
wg.Add(1)
go func() {
defer wg.Done()
writeServiceFiles(g, pkgDir)
}()
}
wg.Wait()
}
type generateInfo struct {
*api.API
PackageDir string
}
var excludeServices = map[string]struct{}{
"importexport": {},
}
func writeServiceFiles(g *generateInfo, pkgDir string) {
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "Error generating %s\n%s\n%s\n",
pkgDir, r, debug.Stack())
os.Exit(1)
}
}()
fmt.Printf("Generating %s (%s)...\n",
g.API.PackageName(), g.API.Metadata.APIVersion)
// write files for service client and API
Must(writeServiceDocFile(g))
Must(writeAPIFile(g))
Must(writeServiceFile(g))
Must(writeInterfaceFile(g))
Must(writeWaitersFile(g))
Must(writeAPIErrorsFile(g))
Must(writeExamplesFile(g))
if g.API.HasEventStream {
Must(writeAPIEventStreamTestFile(g))
}
if g.API.PackageName() == "s3" {
Must(writeS3ManagerUploadInputFile(g))
}
if len(g.API.SmokeTests.TestCases) > 0 {
Must(writeAPISmokeTestsFile(g))
}
}
// Must will panic if the error passed in is not nil.
func Must(err error) {
if err != nil {
panic(err)
}
}
const codeLayout = `// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
%s
package %s
%s
`
func writeGoFile(file string, layout string, args ...interface{}) error {
return ioutil.WriteFile(file, []byte(util.GoFmt(fmt.Sprintf(layout, args...))), 0664)
}
// writeServiceDocFile generates the documentation for service package.
func writeServiceDocFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "doc.go"),
codeLayout,
strings.TrimSpace(g.API.ServicePackageDoc()),
g.API.PackageName(),
"",
)
}
// writeExamplesFile writes out the service example file.
func writeExamplesFile(g *generateInfo) error {
code := g.API.ExamplesGoCode()
if len(code) > 0 {
return writeGoFile(filepath.Join(g.PackageDir, "examples_test.go"),
codeLayout,
"",
g.API.PackageName()+"_test",
code,
)
}
return nil
}
// writeServiceFile writes out the service initialization file.
func writeServiceFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "service.go"),
codeLayout,
"",
g.API.PackageName(),
g.API.ServiceGoCode(),
)
}
// writeInterfaceFile writes out the service interface file.
func writeInterfaceFile(g *generateInfo) error {
const pkgDoc = `
// Package %s provides an interface to enable mocking the %s service client
// for testing your code.
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters.`
return writeGoFile(filepath.Join(g.PackageDir, g.API.InterfacePackageName(), "interface.go"),
codeLayout,
fmt.Sprintf(pkgDoc, g.API.InterfacePackageName(), g.API.Metadata.ServiceFullName),
g.API.InterfacePackageName(),
g.API.InterfaceGoCode(),
)
}
func writeWaitersFile(g *generateInfo) error {
if len(g.API.Waiters) == 0 {
return nil
}
return writeGoFile(filepath.Join(g.PackageDir, "waiters.go"),
codeLayout,
"",
g.API.PackageName(),
g.API.WaitersGoCode(),
)
}
// writeAPIFile writes out the service API file.
func writeAPIFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "api.go"),
codeLayout,
"",
g.API.PackageName(),
g.API.APIGoCode(),
)
}
// writeAPIErrorsFile writes out the service API errors file.
func writeAPIErrorsFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "errors.go"),
codeLayout,
"",
g.API.PackageName(),
g.API.APIErrorsGoCode(),
)
}
func writeAPIEventStreamTestFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "eventstream_test.go"),
codeLayout,
"// +build go1.15\n",
g.API.PackageName(),
g.API.APIEventStreamTestGoCode(),
)
}
func writeS3ManagerUploadInputFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "s3manager", "upload_input.go"),
codeLayout,
"",
"s3manager",
api.S3ManagerUploadInputGoCode(g.API),
)
}
func writeAPISmokeTestsFile(g *generateInfo) error {
return writeGoFile(filepath.Join(g.PackageDir, "integ_test.go"),
codeLayout,
"// +build go1.15,integration\n",
g.API.PackageName()+"_test",
g.API.APISmokeTestsGoCode(),
)
}
| 319 |
session-manager-plugin | aws | Go | // +build codegen
// Command gen-endpoints parses a JSON description of the AWS endpoint
// discovery logic and generates a Go file which returns an endpoint.
//
// aws-gen-goendpoints apis/_endpoints.json aws/endpoints_map.go
package main
import (
"flag"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws/endpoints"
)
// Generates the endpoints from json description
//
// Args:
// -model The definition file to use
// -out The output file to generate
func main() {
var modelName, outName string
flag.StringVar(&modelName, "model", "", "Endpoints definition model")
flag.StringVar(&outName, "out", "", "File to write generated endpoints to.")
flag.Parse()
if len(modelName) == 0 || len(outName) == 0 {
exitErrorf("model and out both required.")
}
modelFile, err := os.Open(modelName)
if err != nil {
exitErrorf("failed to open model definition, %v.", err)
}
defer modelFile.Close()
outFile, err := os.Create(outName)
if err != nil {
exitErrorf("failed to open out file, %v.", err)
}
defer func() {
if err := outFile.Close(); err != nil {
exitErrorf("failed to successfully write %q file, %v", outName, err)
}
}()
if err := endpoints.CodeGenModel(modelFile, outFile, func(o *endpoints.CodeGenOptions) {
o.DisableGenerateServiceIDs = true
}); err != nil {
exitErrorf("failed to codegen model, %v", err)
}
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
| 59 |
session-manager-plugin | aws | Go | // +build codegen
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"os/exec"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
"github.com/aws/aws-sdk-go/private/model/api"
"github.com/aws/aws-sdk-go/private/util"
)
// TestSuiteTypeInput input test
// TestSuiteTypeInput output test
const (
TestSuiteTypeInput = iota
TestSuiteTypeOutput
)
type testSuite struct {
*api.API
Description string
ClientEndpoint string
Cases []testCase
Type uint
title string
}
func (s *testSuite) UnmarshalJSON(p []byte) error {
type stub testSuite
var v stub
if err := json.Unmarshal(p, &v); err != nil {
return err
}
if len(v.ClientEndpoint) == 0 {
v.ClientEndpoint = "https://test"
}
for i := 0; i < len(v.Cases); i++ {
if len(v.Cases[i].InputTest.Host) == 0 {
v.Cases[i].InputTest.Host = "test"
}
if len(v.Cases[i].InputTest.URI) == 0 {
v.Cases[i].InputTest.URI = "/"
}
}
*s = testSuite(v)
return nil
}
type testCase struct {
TestSuite *testSuite
Given *api.Operation
Params interface{} `json:",omitempty"`
Data interface{} `json:"result,omitempty"`
InputTest testExpectation `json:"serialized"`
OutputTest testExpectation `json:"response"`
}
type testExpectation struct {
Body string
Host string
URI string
Headers map[string]string
JSONValues map[string]string
StatusCode uint `json:"status_code"`
}
const preamble = `
var _ bytes.Buffer // always import bytes
var _ http.Request
var _ json.Marshaler
var _ time.Time
var _ xmlutil.XMLNode
var _ xml.Attr
var _ = ioutil.Discard
var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
var _ = aws.String
var _ = fmt.Println
var _ = reflect.Value{}
func init() {
protocol.RandReader = &awstesting.ZeroReader{}
}
`
var reStripSpace = regexp.MustCompile(`\s(\w)`)
var reImportRemoval = regexp.MustCompile(`(?s:import \((.+?)\))`)
func removeImports(code string) string {
return reImportRemoval.ReplaceAllString(code, "")
}
var extraImports = []string{
"bytes",
"encoding/json",
"encoding/xml",
"fmt",
"io",
"io/ioutil",
"net/http",
"testing",
"time",
"reflect",
"net/url",
"",
"github.com/aws/aws-sdk-go/awstesting",
"github.com/aws/aws-sdk-go/awstesting/unit",
"github.com/aws/aws-sdk-go/private/protocol",
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil",
"github.com/aws/aws-sdk-go/private/util",
}
func addImports(code string) string {
importNames := make([]string, len(extraImports))
for i, n := range extraImports {
if n != "" {
importNames[i] = fmt.Sprintf("%q", n)
}
}
str := reImportRemoval.ReplaceAllString(code, "import (\n"+strings.Join(importNames, "\n")+"$1\n)")
return str
}
func (t *testSuite) TestSuite() string {
var buf bytes.Buffer
t.title = reStripSpace.ReplaceAllStringFunc(t.Description, func(x string) string {
return strings.ToUpper(x[1:])
})
t.title = regexp.MustCompile(`\W`).ReplaceAllString(t.title, "")
for idx, c := range t.Cases {
c.TestSuite = t
buf.WriteString(c.TestCase(idx) + "\n")
}
return buf.String()
}
var tplInputTestCase = template.Must(template.New("inputcase").Parse(`
func Test{{ .OpName }}(t *testing.T) {
svc := New{{ .TestCase.TestSuite.API.StructName }}(unit.Session, &aws.Config{Endpoint: aws.String("{{ .TestCase.TestSuite.ClientEndpoint }}")})
{{ if ne .ParamsString "" }}input := {{ .ParamsString }}
{{ range $k, $v := .JSONValues -}}
input.{{ $k }} = {{ $v }}
{{ end -}}
req, _ := svc.{{ .TestCase.Given.ExportedName }}Request(input){{ else }}req, _ := svc.{{ .TestCase.Given.ExportedName }}Request(nil){{ end }}
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
{{ if ne .TestCase.InputTest.Body "" }}// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
{{ .BodyAssertions }}{{ end }}
// assert URL
awstesting.AssertURL(t, "https://{{ .TestCase.InputTest.Host }}{{ .TestCase.InputTest.URI }}", r.URL.String())
// assert headers
{{ range $k, $v := .TestCase.InputTest.Headers -}}
if e, a := "{{ $v }}", r.Header.Get("{{ $k }}"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
{{ end }}
}
`))
type tplInputTestCaseData struct {
TestCase *testCase
JSONValues map[string]string
OpName, ParamsString string
}
func (t tplInputTestCaseData) BodyAssertions() string {
code := &bytes.Buffer{}
protocol := t.TestCase.TestSuite.API.Metadata.Protocol
// Extract the body bytes
fmt.Fprintln(code, "body, _ := ioutil.ReadAll(r.Body)")
// Generate the body verification code
expectedBody := util.Trim(t.TestCase.InputTest.Body)
switch protocol {
case "ec2", "query":
fmt.Fprintf(code, "awstesting.AssertQuery(t, `%s`, util.Trim(string(body)))",
expectedBody)
case "rest-xml":
if strings.HasPrefix(expectedBody, "<") {
fmt.Fprintf(code, "awstesting.AssertXML(t, `%s`, util.Trim(string(body)))",
expectedBody)
} else {
code.WriteString(fmtAssertEqual(fmt.Sprintf("%q", expectedBody), "util.Trim(string(body))"))
}
case "json", "jsonrpc", "rest-json":
if strings.HasPrefix(expectedBody, "{") {
fmt.Fprintf(code, "awstesting.AssertJSON(t, `%s`, util.Trim(string(body)))",
expectedBody)
} else {
code.WriteString(fmtAssertEqual(fmt.Sprintf("%q", expectedBody), "util.Trim(string(body))"))
}
default:
code.WriteString(fmtAssertEqual(expectedBody, "util.Trim(string(body))"))
}
return code.String()
}
func fmtAssertEqual(e, a string) string {
const format = `if e, a := %s, %s; e != a {
t.Errorf("expect %%v, got %%v", e, a)
}
`
return fmt.Sprintf(format, e, a)
}
func fmtAssertNil(v string) string {
const format = `if e := %s; e != nil {
t.Errorf("expect nil, got %%v", e)
}
`
return fmt.Sprintf(format, v)
}
var tplOutputTestCase = template.Must(template.New("outputcase").Parse(`
func Test{{ .OpName }}(t *testing.T) {
svc := New{{ .TestCase.TestSuite.API.StructName }}(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte({{ .Body }}))
req, out := svc.{{ .TestCase.Given.ExportedName }}Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
{{ range $k, $v := .TestCase.OutputTest.Headers }}req.HTTPResponse.Header.Set("{{ $k }}", "{{ $v }}")
{{ end }}
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
{{ .Assertions }}
}
`))
type tplOutputTestCaseData struct {
TestCase *testCase
Body, OpName, Assertions string
}
func (i *testCase) TestCase(idx int) string {
var buf bytes.Buffer
opName := i.TestSuite.API.StructName() + i.TestSuite.title + "Case" + strconv.Itoa(idx+1)
if i.TestSuite.Type == TestSuiteTypeInput { // input test
// query test should sort body as form encoded values
switch i.TestSuite.API.Metadata.Protocol {
case "query", "ec2":
m, _ := url.ParseQuery(i.InputTest.Body)
i.InputTest.Body = m.Encode()
case "rest-xml":
// Nothing to do
case "json", "rest-json":
// Nothing to do
}
jsonValues := buildJSONValues(i.Given.InputRef.Shape)
var params interface{}
if m, ok := i.Params.(map[string]interface{}); ok {
paramsMap := map[string]interface{}{}
for k, v := range m {
if _, ok := jsonValues[k]; !ok {
paramsMap[k] = v
} else {
if i.InputTest.JSONValues == nil {
i.InputTest.JSONValues = map[string]string{}
}
i.InputTest.JSONValues[k] = serializeJSONValue(v.(map[string]interface{}))
}
}
params = paramsMap
} else {
params = i.Params
}
input := tplInputTestCaseData{
TestCase: i,
OpName: strings.ToUpper(opName[0:1]) + opName[1:],
ParamsString: api.ParamsStructFromJSON(params, i.Given.InputRef.Shape, false),
JSONValues: i.InputTest.JSONValues,
}
if err := tplInputTestCase.Execute(&buf, input); err != nil {
panic(err)
}
} else if i.TestSuite.Type == TestSuiteTypeOutput {
output := tplOutputTestCaseData{
TestCase: i,
Body: fmt.Sprintf("%q", i.OutputTest.Body),
OpName: strings.ToUpper(opName[0:1]) + opName[1:],
Assertions: GenerateAssertions(i.Data, i.Given.OutputRef.Shape, "out"),
}
if err := tplOutputTestCase.Execute(&buf, output); err != nil {
panic(err)
}
}
return buf.String()
}
func serializeJSONValue(m map[string]interface{}) string {
str := "aws.JSONValue"
str += walkMap(m)
return str
}
func walkMap(m map[string]interface{}) string {
str := "{"
for k, v := range m {
str += fmt.Sprintf("%q:", k)
switch v.(type) {
case bool:
str += fmt.Sprintf("%t,\n", v.(bool))
case string:
str += fmt.Sprintf("%q,\n", v.(string))
case int:
str += fmt.Sprintf("%d,\n", v.(int))
case float64:
str += fmt.Sprintf("%f,\n", v.(float64))
case map[string]interface{}:
str += walkMap(v.(map[string]interface{}))
}
}
str += "}"
return str
}
func buildJSONValues(shape *api.Shape) map[string]struct{} {
keys := map[string]struct{}{}
for key, field := range shape.MemberRefs {
if field.JSONValue {
keys[key] = struct{}{}
}
}
return keys
}
// generateTestSuite generates a protocol test suite for a given configuration
// JSON protocol test file.
func generateTestSuite(filename string) string {
inout := "Input"
if strings.Contains(filename, "output/") {
inout = "Output"
}
var suites []testSuite
f, err := os.Open(filename)
if err != nil {
panic(err)
}
err = json.NewDecoder(f).Decode(&suites)
if err != nil {
panic(err)
}
var buf bytes.Buffer
buf.WriteString("// Code generated by models/protocol_tests/generate.go. DO NOT EDIT.\n\n")
buf.WriteString("package " + suites[0].ProtocolPackage() + "_test\n\n")
var innerBuf bytes.Buffer
innerBuf.WriteString("//\n// Tests begin here\n//\n\n\n")
for i, suite := range suites {
svcPrefix := inout + "Service" + strconv.Itoa(i+1)
suite.API.Metadata.ServiceAbbreviation = svcPrefix + "ProtocolTest"
suite.API.Operations = map[string]*api.Operation{}
for idx, c := range suite.Cases {
c.Given.ExportedName = svcPrefix + "TestCaseOperation" + strconv.Itoa(idx+1)
suite.API.Operations[c.Given.ExportedName] = c.Given
}
suite.Type = getType(inout)
suite.API.NoInitMethods = true // don't generate init methods
suite.API.NoStringerMethods = true // don't generate stringer methods
suite.API.NoConstServiceNames = true // don't generate service names
suite.API.Setup()
suite.API.Metadata.EndpointPrefix = suite.API.PackageName()
suite.API.Metadata.EndpointsID = suite.API.Metadata.EndpointPrefix
// Sort in order for deterministic test generation
names := make([]string, 0, len(suite.API.Shapes))
for n := range suite.API.Shapes {
names = append(names, n)
}
sort.Strings(names)
for _, name := range names {
s := suite.API.Shapes[name]
s.Rename(svcPrefix + "TestShape" + name)
}
svcCode := addImports(suite.API.ServiceGoCode())
if i == 0 {
importMatch := reImportRemoval.FindStringSubmatch(svcCode)
buf.WriteString(importMatch[0] + "\n\n")
buf.WriteString(preamble + "\n\n")
}
svcCode = removeImports(svcCode)
svcCode = strings.Replace(svcCode, "func New(", "func New"+suite.API.StructName()+"(", -1)
svcCode = strings.Replace(svcCode, "func newClient(", "func new"+suite.API.StructName()+"Client(", -1)
svcCode = strings.Replace(svcCode, "return newClient(", "return new"+suite.API.StructName()+"Client(", -1)
buf.WriteString(svcCode + "\n\n")
apiCode := removeImports(suite.API.APIGoCode())
apiCode = strings.Replace(apiCode, "var oprw sync.Mutex", "", -1)
apiCode = strings.Replace(apiCode, "oprw.Lock()", "", -1)
apiCode = strings.Replace(apiCode, "defer oprw.Unlock()", "", -1)
buf.WriteString(apiCode + "\n\n")
innerBuf.WriteString(suite.TestSuite() + "\n")
}
return buf.String() + innerBuf.String()
}
// findMember searches the shape for the member with the matching key name.
func findMember(shape *api.Shape, key string) string {
for actualKey := range shape.MemberRefs {
if strings.EqualFold(key, actualKey) {
return actualKey
}
}
return ""
}
// GenerateAssertions builds assertions for a shape based on its type.
//
// The shape's recursive values also will have assertions generated for them.
func GenerateAssertions(out interface{}, shape *api.Shape, prefix string) string {
if shape == nil {
return ""
}
switch t := out.(type) {
case map[string]interface{}:
keys := util.SortedKeys(t)
code := ""
if shape.Type == "map" {
for _, k := range keys {
v := t[k]
s := shape.ValueRef.Shape
code += GenerateAssertions(v, s, prefix+"[\""+k+"\"]")
}
} else if shape.Type == "jsonvalue" {
code += fmt.Sprintf("reflect.DeepEqual(%s, map[string]interface{}%s)\n", prefix, walkMap(out.(map[string]interface{})))
} else {
for _, k := range keys {
v := t[k]
m := findMember(shape, k)
s := shape.MemberRefs[m].Shape
code += GenerateAssertions(v, s, prefix+"."+m+"")
}
}
return code
case []interface{}:
code := ""
for i, v := range t {
s := shape.MemberRef.Shape
code += GenerateAssertions(v, s, prefix+"["+strconv.Itoa(i)+"]")
}
return code
default:
switch shape.Type {
case "timestamp":
return fmtAssertEqual(
fmt.Sprintf("time.Unix(%#v, 0).UTC().String()", out),
fmt.Sprintf("%s.UTC().String()", prefix),
)
case "blob":
return fmtAssertEqual(
fmt.Sprintf("%#v", out),
fmt.Sprintf("string(%s)", prefix),
)
case "integer", "long":
return fmtAssertEqual(
fmt.Sprintf("int64(%#v)", out),
fmt.Sprintf("*%s", prefix),
)
default:
if !reflect.ValueOf(out).IsValid() {
return fmtAssertNil(prefix)
}
return fmtAssertEqual(
fmt.Sprintf("%#v", out),
fmt.Sprintf("*%s", prefix),
)
}
}
}
func getType(t string) uint {
switch t {
case "Input":
return TestSuiteTypeInput
case "Output":
return TestSuiteTypeOutput
default:
panic("Invalid type for test suite")
}
}
func main() {
if len(os.Getenv("AWS_SDK_CODEGEN_DEBUG")) != 0 {
api.LogDebug(os.Stdout)
}
fmt.Println("Generating test suite", os.Args[1:])
out := generateTestSuite(os.Args[1])
if len(os.Args) == 3 {
f, err := os.Create(os.Args[2])
defer f.Close()
if err != nil {
panic(err)
}
f.WriteString(util.GoFmt(out))
f.Close()
c := exec.Command("gofmt", "-s", "-w", os.Args[2])
if err := c.Run(); err != nil {
panic(err)
}
} else {
fmt.Println(out)
}
}
| 566 |
session-manager-plugin | aws | Go | package protocol
import (
"github.com/aws/aws-sdk-go/aws/request"
"net"
"strconv"
"strings"
)
// ValidateEndpointHostHandler is a request handler that will validate the
// request endpoint's hosts is a valid RFC 3986 host.
var ValidateEndpointHostHandler = request.NamedHandler{
Name: "awssdk.protocol.ValidateEndpointHostHandler",
Fn: func(r *request.Request) {
err := ValidateEndpointHost(r.Operation.Name, r.HTTPRequest.URL.Host)
if err != nil {
r.Error = err
}
},
}
// ValidateEndpointHost validates that the host string passed in is a valid RFC
// 3986 host. Returns error if the host is not valid.
func ValidateEndpointHost(opName, host string) error {
paramErrs := request.ErrInvalidParams{Context: opName}
var hostname string
var port string
var err error
if strings.Contains(host, ":") {
hostname, port, err = net.SplitHostPort(host)
if err != nil {
paramErrs.Add(request.NewErrParamFormat("endpoint", err.Error(), host))
}
if !ValidPortNumber(port) {
paramErrs.Add(request.NewErrParamFormat("endpoint port number", "[0-65535]", port))
}
} else {
hostname = host
}
labels := strings.Split(hostname, ".")
for i, label := range labels {
if i == len(labels)-1 && len(label) == 0 {
// Allow trailing dot for FQDN hosts.
continue
}
if !ValidHostLabel(label) {
paramErrs.Add(request.NewErrParamFormat(
"endpoint host label", "[a-zA-Z0-9-]{1,63}", label))
}
}
if len(hostname) == 0 {
paramErrs.Add(request.NewErrParamMinLen("endpoint host", 1))
}
if len(hostname) > 255 {
paramErrs.Add(request.NewErrParamMaxLen(
"endpoint host", 255, host,
))
}
if paramErrs.Len() > 0 {
return paramErrs
}
return nil
}
// ValidHostLabel returns if the label is a valid RFC 3986 host label.
func ValidHostLabel(label string) bool {
if l := len(label); l == 0 || l > 63 {
return false
}
for _, r := range label {
switch {
case r >= '0' && r <= '9':
case r >= 'A' && r <= 'Z':
case r >= 'a' && r <= 'z':
case r == '-':
default:
return false
}
}
return true
}
// ValidPortNumber return if the port is valid RFC 3986 port
func ValidPortNumber(port string) bool {
i, err := strconv.Atoi(port)
if err != nil {
return false
}
if i < 0 || i > 65535 {
return false
}
return true
}
| 105 |
session-manager-plugin | aws | Go | package protocol
import (
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
)
// HostPrefixHandlerName is the handler name for the host prefix request
// handler.
const HostPrefixHandlerName = "awssdk.endpoint.HostPrefixHandler"
// NewHostPrefixHandler constructs a build handler
func NewHostPrefixHandler(prefix string, labelsFn func() map[string]string) request.NamedHandler {
builder := HostPrefixBuilder{
Prefix: prefix,
LabelsFn: labelsFn,
}
return request.NamedHandler{
Name: HostPrefixHandlerName,
Fn: builder.Build,
}
}
// HostPrefixBuilder provides the request handler to expand and prepend
// the host prefix into the operation's request endpoint host.
type HostPrefixBuilder struct {
Prefix string
LabelsFn func() map[string]string
}
// Build updates the passed in Request with the HostPrefix template expanded.
func (h HostPrefixBuilder) Build(r *request.Request) {
if aws.BoolValue(r.Config.DisableEndpointHostPrefix) {
return
}
var labels map[string]string
if h.LabelsFn != nil {
labels = h.LabelsFn()
}
prefix := h.Prefix
for name, value := range labels {
prefix = strings.Replace(prefix, "{"+name+"}", value, -1)
}
r.HTTPRequest.URL.Host = prefix + r.HTTPRequest.URL.Host
if len(r.HTTPRequest.Host) > 0 {
r.HTTPRequest.Host = prefix + r.HTTPRequest.Host
}
}
| 55 |
session-manager-plugin | aws | Go | // +build go1.7
package protocol
import (
"net/http"
"net/url"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
)
func TestHostPrefixBuilder(t *testing.T) {
cases := map[string]struct {
URLHost string
ReqHost string
Prefix string
LabelsFn func() map[string]string
Disabled bool
ExpectURLHost string
ExpectReqHost string
}{
"no labels": {
URLHost: "service.region.amazonaws.com",
Prefix: "data-",
ExpectURLHost: "data-service.region.amazonaws.com",
},
"with labels": {
URLHost: "service.region.amazonaws.com",
Prefix: "{first}-{second}.",
LabelsFn: func() map[string]string {
return map[string]string{
"first": "abc",
"second": "123",
}
},
ExpectURLHost: "abc-123.service.region.amazonaws.com",
},
"with host prefix disabled": {
Disabled: true,
URLHost: "service.region.amazonaws.com",
Prefix: "{first}-{second}.",
LabelsFn: func() map[string]string {
return map[string]string{
"first": "abc",
"second": "123",
}
},
ExpectURLHost: "service.region.amazonaws.com",
},
"with duplicate labels": {
URLHost: "service.region.amazonaws.com",
Prefix: "{first}-{second}-{first}.",
LabelsFn: func() map[string]string {
return map[string]string{
"first": "abc",
"second": "123",
}
},
ExpectURLHost: "abc-123-abc.service.region.amazonaws.com",
},
"with unbracketed labels": {
URLHost: "service.region.amazonaws.com",
Prefix: "first-{second}.",
LabelsFn: func() map[string]string {
return map[string]string{
"first": "abc",
"second": "123",
}
},
ExpectURLHost: "first-123.service.region.amazonaws.com",
},
"with req host": {
URLHost: "service.region.amazonaws.com:1234",
ReqHost: "service.region.amazonaws.com",
Prefix: "data-",
ExpectURLHost: "data-service.region.amazonaws.com:1234",
ExpectReqHost: "data-service.region.amazonaws.com",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
builder := HostPrefixBuilder{
Prefix: c.Prefix, LabelsFn: c.LabelsFn,
}
req := &request.Request{
Config: aws.Config{
DisableEndpointHostPrefix: aws.Bool(c.Disabled),
},
HTTPRequest: &http.Request{
Host: c.ReqHost,
URL: &url.URL{
Host: c.URLHost,
},
},
}
builder.Build(req)
if e, a := c.ExpectURLHost, req.HTTPRequest.URL.Host; e != a {
t.Errorf("expect URL host %v, got %v", e, a)
}
if e, a := c.ExpectReqHost, req.HTTPRequest.Host; e != a {
t.Errorf("expect request host %v, got %v", e, a)
}
})
}
}
| 111 |
session-manager-plugin | aws | Go | // +build go1.7
package protocol
import (
"strconv"
"testing"
)
func TestValidPortNumber(t *testing.T) {
cases := []struct {
Input string
Valid bool
}{
{Input: "123", Valid: true},
{Input: "123.0", Valid: false},
{Input: "-123", Valid: false},
{Input: "65536", Valid: false},
{Input: "0", Valid: true},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
valid := ValidPortNumber(c.Input)
if e, a := c.Valid, valid; e != a {
t.Errorf("expect valid %v, got %v", e, a)
}
})
}
}
func TestValidHostLabel(t *testing.T) {
cases := []struct {
Input string
Valid bool
}{
{Input: "abc123", Valid: true},
{Input: "123", Valid: true},
{Input: "abc", Valid: true},
{Input: "123-abc", Valid: true},
{Input: "{thing}-abc", Valid: false},
{Input: "abc.123", Valid: false},
{Input: "abc/123", Valid: false},
{Input: "012345678901234567890123456789012345678901234567890123456789123", Valid: true},
{Input: "0123456789012345678901234567890123456789012345678901234567891234", Valid: false},
{Input: "", Valid: false},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
valid := ValidHostLabel(c.Input)
if e, a := c.Valid, valid; e != a {
t.Errorf("expect valid %v, got %v", e, a)
}
})
}
}
func TestValidateEndpointHostHandler(t *testing.T) {
cases := map[string]struct {
Input string
Valid bool
}{
"valid host": {Input: "abc.123", Valid: true},
"fqdn host": {Input: "abc.123.", Valid: true},
"empty label": {Input: "abc..", Valid: false},
"max host len": {
Input: "123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.12345",
Valid: true,
},
"too long host": {
Input: "123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456",
Valid: false,
},
"valid host with port number": {Input: "abd.123:1234", Valid: true},
"valid host with invalid port number": {Input: "abc.123:99999", Valid: false},
"empty host with port number": {Input: ":1234", Valid: false},
"valid host with empty port number": {Input: "abc.123:", Valid: false},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
err := ValidateEndpointHost("OpName", c.Input)
if e, a := c.Valid, err == nil; e != a {
t.Errorf("expect valid %v, got %v, %v", e, a, err)
}
})
}
}
| 90 |
session-manager-plugin | aws | Go | package protocol
import (
"crypto/rand"
"fmt"
"reflect"
)
// RandReader is the random reader the protocol package will use to read
// random bytes from. This is exported for testing, and should not be used.
var RandReader = rand.Reader
const idempotencyTokenFillTag = `idempotencyToken`
// CanSetIdempotencyToken returns true if the struct field should be
// automatically populated with a Idempotency token.
//
// Only *string and string type fields that are tagged with idempotencyToken
// which are not already set can be auto filled.
func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool {
switch u := v.Interface().(type) {
// To auto fill an Idempotency token the field must be a string,
// tagged for auto fill, and have a zero value.
case *string:
return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0
case string:
return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0
}
return false
}
// GetIdempotencyToken returns a randomly generated idempotency token.
func GetIdempotencyToken() string {
b := make([]byte, 16)
RandReader.Read(b)
return UUIDVersion4(b)
}
// SetIdempotencyToken will set the value provided with a Idempotency Token.
// Given that the value can be set. Will panic if value is not setable.
func SetIdempotencyToken(v reflect.Value) {
if v.Kind() == reflect.Ptr {
if v.IsNil() && v.CanSet() {
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
v = reflect.Indirect(v)
if !v.CanSet() {
panic(fmt.Sprintf("unable to set idempotnecy token %v", v))
}
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
// TODO handle error
return
}
v.Set(reflect.ValueOf(UUIDVersion4(b)))
}
// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided
func UUIDVersion4(u []byte) string {
// https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
// 13th character is "4"
u[6] = (u[6] | 0x40) & 0x4F
// 17th character is "8", "9", "a", or "b"
u[8] = (u[8] | 0x80) & 0xBF
return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
}
| 76 |
session-manager-plugin | aws | Go | package protocol_test
import (
"reflect"
"testing"
"github.com/aws/aws-sdk-go/private/protocol"
)
func TestCanSetIdempotencyToken(t *testing.T) {
cases := []struct {
CanSet bool
Case interface{}
}{
{
true,
struct {
Field *string `idempotencyToken:"true"`
}{},
},
{
true,
struct {
Field string `idempotencyToken:"true"`
}{},
},
{
false,
struct {
Field *string `idempotencyToken:"true"`
}{Field: new(string)},
},
{
false,
struct {
Field string `idempotencyToken:"true"`
}{Field: "value"},
},
{
false,
struct {
Field *int `idempotencyToken:"true"`
}{},
},
{
false,
struct {
Field *string
}{},
},
}
for i, c := range cases {
v := reflect.Indirect(reflect.ValueOf(c.Case))
ty := v.Type()
canSet := protocol.CanSetIdempotencyToken(v.Field(0), ty.Field(0))
if e, a := c.CanSet, canSet; e != a {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
}
}
func TestSetIdempotencyToken(t *testing.T) {
cases := []struct {
Case interface{}
}{
{
&struct {
Field *string `idempotencyToken:"true"`
}{},
},
{
&struct {
Field string `idempotencyToken:"true"`
}{},
},
{
&struct {
Field *string `idempotencyToken:"true"`
}{Field: new(string)},
},
{
&struct {
Field string `idempotencyToken:"true"`
}{Field: ""},
},
}
for i, c := range cases {
v := reflect.Indirect(reflect.ValueOf(c.Case))
protocol.SetIdempotencyToken(v.Field(0))
if v.Field(0).Interface() == nil {
t.Errorf("%d, expect not nil", i)
}
}
}
func TestUUIDVersion4(t *testing.T) {
uuid := protocol.UUIDVersion4(make([]byte, 16))
if e, a := `00000000-0000-4000-8000-000000000000`, uuid; e != a {
t.Errorf("expect %v, got %v", e, a)
}
b := make([]byte, 16)
for i := 0; i < len(b); i++ {
b[i] = 1
}
uuid = protocol.UUIDVersion4(b)
if e, a := `01010101-0101-4101-8101-010101010101`, uuid; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
| 114 |
session-manager-plugin | aws | Go | package protocol
import (
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
"github.com/aws/aws-sdk-go/aws"
)
// EscapeMode is the mode that should be use for escaping a value
type EscapeMode uint
// The modes for escaping a value before it is marshaled, and unmarshaled.
const (
NoEscape EscapeMode = iota
Base64Escape
QuotedEscape
)
// EncodeJSONValue marshals the value into a JSON string, and optionally base64
// encodes the string before returning it.
//
// Will panic if the escape mode is unknown.
func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err
}
switch escape {
case NoEscape:
return string(b), nil
case Base64Escape:
return base64.StdEncoding.EncodeToString(b), nil
case QuotedEscape:
return strconv.Quote(string(b)), nil
}
panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape))
}
// DecodeJSONValue will attempt to decode the string input as a JSONValue.
// Optionally decoding base64 the value first before JSON unmarshaling.
//
// Will panic if the escape mode is unknown.
func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) {
var b []byte
var err error
switch escape {
case NoEscape:
b = []byte(v)
case Base64Escape:
b, err = base64.StdEncoding.DecodeString(v)
case QuotedEscape:
var u string
u, err = strconv.Unquote(v)
b = []byte(u)
default:
panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape))
}
if err != nil {
return nil, err
}
m := aws.JSONValue{}
err = json.Unmarshal(b, &m)
if err != nil {
return nil, err
}
return m, nil
}
| 77 |
session-manager-plugin | aws | Go | package protocol
import (
"fmt"
"reflect"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws"
)
var testJSONValueCases = []struct {
Value aws.JSONValue
Mode EscapeMode
String string
}{
{
Value: aws.JSONValue{
"abc": 123.,
},
Mode: NoEscape,
String: `{"abc":123}`,
},
{
Value: aws.JSONValue{
"abc": 123.,
},
Mode: Base64Escape,
String: `eyJhYmMiOjEyM30=`,
},
{
Value: aws.JSONValue{
"abc": 123.,
},
Mode: QuotedEscape,
String: `"{\"abc\":123}"`,
},
}
func TestEncodeJSONValue(t *testing.T) {
for i, c := range testJSONValueCases {
str, err := EncodeJSONValue(c.Value, c.Mode)
if err != nil {
t.Fatalf("%d, expect no error, got %v", i, err)
}
if e, a := c.String, str; e != a {
t.Errorf("%d, expect %v encoded value, got %v", i, e, a)
}
}
}
func TestDecodeJSONValue(t *testing.T) {
for i, c := range testJSONValueCases {
val, err := DecodeJSONValue(c.String, c.Mode)
if err != nil {
t.Fatalf("%d, expect no error, got %v", i, err)
}
if e, a := c.Value, val; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %v encoded value, got %v", i, e, a)
}
}
}
func TestEncodeJSONValue_PanicUnkownMode(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("expect panic, got none")
} else {
reason := fmt.Sprintf("%v", r)
if e, a := "unknown EscapeMode", reason; !strings.Contains(a, e) {
t.Errorf("expect %q to be in %v", e, a)
}
}
}()
val := aws.JSONValue{}
EncodeJSONValue(val, 123456)
}
func TestDecodeJSONValue_PanicUnkownMode(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("expect panic, got none")
} else {
reason := fmt.Sprintf("%v", r)
if e, a := "unknown EscapeMode", reason; !strings.Contains(a, e) {
t.Errorf("expect %q to be in %v", e, a)
}
}
}()
DecodeJSONValue(`{"abc":123}`, 123456)
}
| 94 |
session-manager-plugin | aws | Go | package protocol
import (
"io"
"io/ioutil"
"net/http"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
)
// PayloadUnmarshaler provides the interface for unmarshaling a payload's
// reader into a SDK shape.
type PayloadUnmarshaler interface {
UnmarshalPayload(io.Reader, interface{}) error
}
// HandlerPayloadUnmarshal implements the PayloadUnmarshaler from a
// HandlerList. This provides the support for unmarshaling a payload reader to
// a shape without needing a SDK request first.
type HandlerPayloadUnmarshal struct {
Unmarshalers request.HandlerList
}
// UnmarshalPayload unmarshals the io.Reader payload into the SDK shape using
// the Unmarshalers HandlerList provided. Returns an error if unable
// unmarshaling fails.
func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error {
req := &request.Request{
HTTPRequest: &http.Request{},
HTTPResponse: &http.Response{
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(r),
},
Data: v,
}
h.Unmarshalers.Run(req)
return req.Error
}
// PayloadMarshaler provides the interface for marshaling a SDK shape into and
// io.Writer.
type PayloadMarshaler interface {
MarshalPayload(io.Writer, interface{}) error
}
// HandlerPayloadMarshal implements the PayloadMarshaler from a HandlerList.
// This provides support for marshaling a SDK shape into an io.Writer without
// needing a SDK request first.
type HandlerPayloadMarshal struct {
Marshalers request.HandlerList
}
// MarshalPayload marshals the SDK shape into the io.Writer using the
// Marshalers HandlerList provided. Returns an error if unable if marshal
// fails.
func (h HandlerPayloadMarshal) MarshalPayload(w io.Writer, v interface{}) error {
req := request.New(
aws.Config{},
metadata.ClientInfo{},
request.Handlers{},
nil,
&request.Operation{HTTPMethod: "PUT"},
v,
nil,
)
h.Marshalers.Run(req)
if req.Error != nil {
return req.Error
}
io.Copy(w, req.GetBody())
return nil
}
| 82 |
session-manager-plugin | aws | Go | package protocol
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
// RequireHTTPMinProtocol request handler is used to enforce that
// the target endpoint supports the given major and minor HTTP protocol version.
type RequireHTTPMinProtocol struct {
Major, Minor int
}
// Handler will mark the request.Request with an error if the
// target endpoint did not connect with the required HTTP protocol
// major and minor version.
func (p RequireHTTPMinProtocol) Handler(r *request.Request) {
if r.Error != nil || r.HTTPResponse == nil {
return
}
if !strings.HasPrefix(r.HTTPResponse.Proto, "HTTP") {
r.Error = newMinHTTPProtoError(p.Major, p.Minor, r)
}
if r.HTTPResponse.ProtoMajor < p.Major || r.HTTPResponse.ProtoMinor < p.Minor {
r.Error = newMinHTTPProtoError(p.Major, p.Minor, r)
}
}
// ErrCodeMinimumHTTPProtocolError error code is returned when the target endpoint
// did not match the required HTTP major and minor protocol version.
const ErrCodeMinimumHTTPProtocolError = "MinimumHTTPProtocolError"
func newMinHTTPProtoError(major, minor int, r *request.Request) error {
return awserr.NewRequestFailure(
awserr.New("MinimumHTTPProtocolError",
fmt.Sprintf(
"operation requires minimum HTTP protocol of HTTP/%d.%d, but was %s",
major, minor, r.HTTPResponse.Proto,
),
nil,
),
r.HTTPResponse.StatusCode, r.RequestID,
)
}
| 50 |
session-manager-plugin | aws | Go | // +build go1.7
package protocol
import (
"net/http"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
func TestRequireHTTPMinProtocol(t *testing.T) {
cases := map[string]struct {
Major, Minor int
Response *http.Response
Err string
}{
"HTTP/2.0": {
Major: 2,
Response: &http.Response{
StatusCode: 200,
Proto: "HTTP/2.0",
ProtoMajor: 2, ProtoMinor: 0,
},
},
"HTTP/1.1": {
Major: 2,
Response: &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
ProtoMajor: 1, ProtoMinor: 1,
},
Err: "operation requires minimum HTTP protocol",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
req := &request.Request{
HTTPResponse: c.Response,
}
RequireHTTPMinProtocol{Major: c.Major, Minor: c.Minor}.Handler(req)
if len(c.Err) != 0 {
if req.Error == nil {
t.Fatalf("expect error")
}
if e, a := c.Err, req.Error.Error(); !strings.Contains(a, e) {
t.Errorf("expect %q error, got %q", e, a)
}
aerr, ok := req.Error.(awserr.RequestFailure)
if !ok {
t.Fatalf("expect RequestFailure, got %T", req.Error)
}
if e, a := ErrCodeMinimumHTTPProtocolError, aerr.Code(); e != a {
t.Errorf("expect %v code, got %v", e, a)
}
if e, a := c.Response.StatusCode, aerr.StatusCode(); e != a {
t.Errorf("expect %v status code, got %v", e, a)
}
} else {
if err := req.Error; err != nil {
t.Fatalf("expect no failure, got %v", err)
}
}
})
}
}
| 73 |
session-manager-plugin | aws | Go | package protocol_test
import (
"net/http"
"net/url"
"testing"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/ec2query"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
"github.com/aws/aws-sdk-go/private/protocol/query"
"github.com/aws/aws-sdk-go/private/protocol/rest"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
"github.com/aws/aws-sdk-go/private/protocol/restxml"
)
func xmlData(set bool, b []byte, size, delta int) {
const openingTags = "<B><A>"
const closingTags = "</A></B>"
if !set {
copy(b, []byte(openingTags))
}
if size == 0 {
copy(b[delta-len(closingTags):], []byte(closingTags))
}
}
func jsonData(set bool, b []byte, size, delta int) {
if !set {
copy(b, []byte("{\"A\": \""))
}
if size == 0 {
copy(b[delta-len("\"}"):], []byte("\"}"))
}
}
func buildNewRequest(data interface{}) *request.Request {
v := url.Values{}
v.Set("test", "TEST")
v.Add("test1", "TEST1")
req := &request.Request{
HTTPRequest: &http.Request{
Header: make(http.Header),
Body: &awstesting.ReadCloser{Size: 2048},
URL: &url.URL{
RawQuery: v.Encode(),
},
},
Params: &struct {
LocationName string `locationName:"test"`
}{
"Test",
},
ClientInfo: metadata.ClientInfo{
ServiceName: "test",
TargetPrefix: "test",
JSONVersion: "test",
APIVersion: "test",
Endpoint: "test",
SigningName: "test",
SigningRegion: "test",
},
Operation: &request.Operation{
Name: "test",
},
}
req.HTTPResponse = &http.Response{
Body: &awstesting.ReadCloser{Size: 2048},
Header: http.Header{
"X-Amzn-Requestid": []string{"1"},
},
StatusCode: http.StatusOK,
}
if data == nil {
data = &struct {
_ struct{} `type:"structure"`
LocationName *string `locationName:"testName"`
Location *string `location:"statusCode"`
A *string `type:"string"`
}{}
}
req.Data = data
return req
}
type expected struct {
dataType int
closed bool
size int
errExists bool
}
const (
jsonType = iota
xmlType
)
func checkForLeak(data interface{}, build, fn func(*request.Request), t *testing.T, result expected) {
req := buildNewRequest(data)
reader := req.HTTPResponse.Body.(*awstesting.ReadCloser)
switch result.dataType {
case jsonType:
reader.FillData = jsonData
case xmlType:
reader.FillData = xmlData
}
build(req)
fn(req)
if result.errExists {
if err := req.Error; err == nil {
t.Errorf("expect error")
}
} else {
if err := req.Error; err != nil {
t.Errorf("expect nil, %v", err)
}
}
if e, a := reader.Closed, result.closed; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := reader.Size, result.size; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestJSONRpc(t *testing.T) {
checkForLeak(nil, jsonrpc.Build, jsonrpc.Unmarshal, t, expected{jsonType, true, 0, false})
checkForLeak(nil, jsonrpc.Build, jsonrpc.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
checkForLeak(nil, jsonrpc.Build, jsonrpc.UnmarshalError, t, expected{jsonType, true, 0, true})
}
func TestQuery(t *testing.T) {
checkForLeak(nil, query.Build, query.Unmarshal, t, expected{jsonType, true, 0, false})
checkForLeak(nil, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
checkForLeak(nil, query.Build, query.UnmarshalError, t, expected{jsonType, true, 0, true})
}
func TestRest(t *testing.T) {
// case 1: Payload io.ReadSeeker
checkForLeak(nil, rest.Build, rest.Unmarshal, t, expected{jsonType, false, 2048, false})
checkForLeak(nil, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
// case 2: Payload *string
// should close the body
dataStr := struct {
_ struct{} `type:"structure" payload:"Payload"`
LocationName *string `locationName:"testName"`
Location *string `location:"statusCode"`
A *string `type:"string"`
Payload *string `locationName:"payload" type:"blob" required:"true"`
}{}
checkForLeak(&dataStr, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, false})
checkForLeak(&dataStr, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
// case 3: Payload []byte
// should close the body
dataBytes := struct {
_ struct{} `type:"structure" payload:"Payload"`
LocationName *string `locationName:"testName"`
Location *string `location:"statusCode"`
A *string `type:"string"`
Payload []byte `locationName:"payload" type:"blob" required:"true"`
}{}
checkForLeak(&dataBytes, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, false})
checkForLeak(&dataBytes, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
// case 4: Payload unsupported type
// should close the body
dataUnsupported := struct {
_ struct{} `type:"structure" payload:"Payload"`
LocationName *string `locationName:"testName"`
Location *string `location:"statusCode"`
A *string `type:"string"`
Payload string `locationName:"payload" type:"blob" required:"true"`
}{}
checkForLeak(&dataUnsupported, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, true})
checkForLeak(&dataUnsupported, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
}
func TestRestJSON(t *testing.T) {
checkForLeak(nil, restjson.Build, restjson.Unmarshal, t, expected{jsonType, true, 0, false})
checkForLeak(nil, restjson.Build, restjson.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
checkForLeak(nil, restjson.Build, restjson.UnmarshalError, t, expected{jsonType, true, 0, true})
}
func TestRestXML(t *testing.T) {
checkForLeak(nil, restxml.Build, restxml.Unmarshal, t, expected{xmlType, true, 0, false})
checkForLeak(nil, restxml.Build, restxml.UnmarshalMeta, t, expected{xmlType, false, 2048, false})
checkForLeak(nil, restxml.Build, restxml.UnmarshalError, t, expected{xmlType, true, 0, true})
}
func TestXML(t *testing.T) {
checkForLeak(nil, ec2query.Build, ec2query.Unmarshal, t, expected{jsonType, true, 0, false})
checkForLeak(nil, ec2query.Build, ec2query.UnmarshalMeta, t, expected{jsonType, false, 2048, false})
checkForLeak(nil, ec2query.Build, ec2query.UnmarshalError, t, expected{jsonType, true, 0, true})
}
func TestProtocol(t *testing.T) {
checkForLeak(nil, restxml.Build, protocol.UnmarshalDiscardBody, t, expected{xmlType, true, 0, false})
}
| 210 |
session-manager-plugin | aws | Go | package protocol
import (
"bytes"
"fmt"
"math"
"strconv"
"time"
"github.com/aws/aws-sdk-go/internal/sdkmath"
)
// Names of time formats supported by the SDK
const (
RFC822TimeFormatName = "rfc822"
ISO8601TimeFormatName = "iso8601"
UnixTimeFormatName = "unixTimestamp"
)
// Time formats supported by the SDK
// Output time is intended to not contain decimals
const (
// RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT
RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT"
rfc822TimeFormatSingleDigitDay = "Mon, _2 Jan 2006 15:04:05 GMT"
rfc822TimeFormatSingleDigitDayTwoDigitYear = "Mon, _2 Jan 06 15:04:05 GMT"
// This format is used for output time without seconds precision
RFC822OutputTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
// RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z
ISO8601TimeFormat = "2006-01-02T15:04:05.999999999Z"
// This format is used for output time with fractional second precision up to milliseconds
ISO8601OutputTimeFormat = "2006-01-02T15:04:05.999999999Z"
)
// IsKnownTimestampFormat returns if the timestamp format name
// is know to the SDK's protocols.
func IsKnownTimestampFormat(name string) bool {
switch name {
case RFC822TimeFormatName:
fallthrough
case ISO8601TimeFormatName:
fallthrough
case UnixTimeFormatName:
return true
default:
return false
}
}
// FormatTime returns a string value of the time.
func FormatTime(name string, t time.Time) string {
t = t.UTC().Truncate(time.Millisecond)
switch name {
case RFC822TimeFormatName:
return t.Format(RFC822OutputTimeFormat)
case ISO8601TimeFormatName:
return t.Format(ISO8601OutputTimeFormat)
case UnixTimeFormatName:
ms := t.UnixNano() / int64(time.Millisecond)
return strconv.FormatFloat(float64(ms)/1e3, 'f', -1, 64)
default:
panic("unknown timestamp format name, " + name)
}
}
// ParseTime attempts to parse the time given the format. Returns
// the time if it was able to be parsed, and fails otherwise.
func ParseTime(formatName, value string) (time.Time, error) {
switch formatName {
case RFC822TimeFormatName: // Smithy HTTPDate format
return tryParse(value,
RFC822TimeFormat,
rfc822TimeFormatSingleDigitDay,
rfc822TimeFormatSingleDigitDayTwoDigitYear,
time.RFC850,
time.ANSIC,
)
case ISO8601TimeFormatName: // Smithy DateTime format
return tryParse(value,
ISO8601TimeFormat,
time.RFC3339Nano,
time.RFC3339,
)
case UnixTimeFormatName:
v, err := strconv.ParseFloat(value, 64)
_, dec := math.Modf(v)
dec = sdkmath.Round(dec*1e3) / 1e3 //Rounds 0.1229999 to 0.123
if err != nil {
return time.Time{}, err
}
return time.Unix(int64(v), int64(dec*(1e9))), nil
default:
panic("unknown timestamp format name, " + formatName)
}
}
func tryParse(v string, formats ...string) (time.Time, error) {
var errs parseErrors
for _, f := range formats {
t, err := time.Parse(f, v)
if err != nil {
errs = append(errs, parseError{
Format: f,
Err: err,
})
continue
}
return t, nil
}
return time.Time{}, fmt.Errorf("unable to parse time string, %v", errs)
}
type parseErrors []parseError
func (es parseErrors) Error() string {
var s bytes.Buffer
for _, e := range es {
fmt.Fprintf(&s, "\n * %q: %v", e.Format, e.Err)
}
return "parse errors:" + s.String()
}
type parseError struct {
Format string
Err error
}
| 133 |
session-manager-plugin | aws | Go | // +build go1.7
package protocol
import (
"testing"
"time"
)
func TestFormatTime(t *testing.T) {
cases := map[string]struct {
formatName string
expectedOutput string
input time.Time
}{
"UnixTest1": {
formatName: UnixTimeFormatName,
expectedOutput: "946845296",
input: time.Date(2000, time.January, 2, 20, 34, 56, 0, time.UTC),
},
"UnixTest2": {
formatName: UnixTimeFormatName,
expectedOutput: "946845296.123",
input: time.Date(2000, time.January, 2, 20, 34, 56, .123e9, time.UTC),
},
"ISO8601Test1": {
formatName: ISO8601TimeFormatName,
expectedOutput: "2000-01-02T20:34:56Z",
input: time.Date(2000, time.January, 2, 20, 34, 56, 0, time.UTC),
},
"RFC822Test1": {
formatName: RFC822TimeFormatName,
expectedOutput: "Sun, 02 Jan 2000 20:34:56 GMT",
input: time.Date(2000, time.January, 2, 20, 34, 56, 0, time.UTC),
},
"ISO8601Test2": {
formatName: ISO8601TimeFormatName,
expectedOutput: "2000-01-02T20:34:56.123Z",
input: time.Date(2000, time.January, 2, 20, 34, 56, .123e9, time.UTC),
},
"ISO8601Test3": {
formatName: ISO8601TimeFormatName,
expectedOutput: "2000-01-02T20:34:56.123Z",
input: time.Date(2000, time.January, 2, 20, 34, 56, .123456e9, time.UTC),
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
if e, a := c.expectedOutput, FormatTime(c.formatName, c.input); e != a {
t.Errorf("expected %s, got %s for %s format ", e, a, c.formatName)
}
})
}
}
func TestParseTime(t *testing.T) {
//input and output times are considered equal if they are equal until three decimal places
cases := map[string]struct {
formatName, input string
expectedOutput time.Time
}{
"UnixTestExponent": {
formatName: UnixTimeFormatName,
input: "1.583858715232899e9",
expectedOutput: time.Date(2020, time.March, 10, 16, 45, 15, .233e9, time.UTC),
},
"UnixTest1": {
formatName: UnixTimeFormatName,
input: "946845296.123",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, .123e9, time.UTC),
},
"UnixTest2": {
formatName: UnixTimeFormatName,
input: "946845296.12344",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, .123e9, time.UTC),
},
"UnixTest3": {
formatName: UnixTimeFormatName,
input: "946845296.1229999",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, .123e9, time.UTC),
},
"ISO8601Test milliseconds": {
formatName: ISO8601TimeFormatName,
input: "2000-01-02T20:34:56.123Z",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, .123e9, time.UTC),
},
"ISO8601Test nanoseconds": {
formatName: ISO8601TimeFormatName,
input: "2000-01-02T20:34:56.123456789Z",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, .123456789e9, time.UTC),
},
"ISO8601Test millisecond utc offset": {
formatName: ISO8601TimeFormatName,
input: "2000-01-02T20:34:56.123-07:00",
expectedOutput: time.Date(2000, time.January, 3, 3, 34, 56, .123e9, time.UTC),
},
"ISO8601Test millisecond positive utc offset": {
formatName: ISO8601TimeFormatName,
input: "2000-01-02T20:34:56.123+07:00",
expectedOutput: time.Date(2000, time.January, 2, 13, 34, 56, .123e9, time.UTC),
},
"ISO8601Test nanosecond utc offset": {
formatName: ISO8601TimeFormatName,
input: "2000-01-02T20:34:56.123456789-07:00",
expectedOutput: time.Date(2000, time.January, 3, 3, 34, 56, .123456789e9, time.UTC),
},
"RFC822Test single digit day": {
formatName: RFC822TimeFormatName,
input: "Sun, 2 Jan 2000 20:34:56 GMT",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, 0, time.UTC),
},
"RFC822Test two digit day": {
formatName: RFC822TimeFormatName,
input: "Sun, 02 Jan 2000 20:34:56 GMT",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, 0, time.UTC),
},
"RFC822Test two digit day year": {
formatName: RFC822TimeFormatName,
input: "Sun, 2 Jan 00 20:34:56 GMT",
expectedOutput: time.Date(2000, time.January, 2, 20, 34, 56, 0, time.UTC),
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
timeVal, err := ParseTime(c.formatName, c.input)
if err != nil {
t.Errorf("expect no error, got %v", err)
}
if e, a := c.expectedOutput, timeVal.UTC(); !e.Equal(a) {
t.Errorf("expect %v time, got %v", e, a)
}
})
}
}
| 137 |
session-manager-plugin | aws | Go | package protocol
import (
"io"
"io/ioutil"
"github.com/aws/aws-sdk-go/aws/request"
)
// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body
var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody}
// UnmarshalDiscardBody is a request handler to empty a response's body and closing it.
func UnmarshalDiscardBody(r *request.Request) {
if r.HTTPResponse == nil || r.HTTPResponse.Body == nil {
return
}
io.Copy(ioutil.Discard, r.HTTPResponse.Body)
r.HTTPResponse.Body.Close()
}
// ResponseMetadata provides the SDK response metadata attributes.
type ResponseMetadata struct {
StatusCode int
RequestID string
}
| 28 |
session-manager-plugin | aws | Go | package protocol
import (
"net/http"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
// UnmarshalErrorHandler provides unmarshaling errors API response errors for
// both typed and untyped errors.
type UnmarshalErrorHandler struct {
unmarshaler ErrorUnmarshaler
}
// ErrorUnmarshaler is an abstract interface for concrete implementations to
// unmarshal protocol specific response errors.
type ErrorUnmarshaler interface {
UnmarshalError(*http.Response, ResponseMetadata) (error, error)
}
// NewUnmarshalErrorHandler returns an UnmarshalErrorHandler
// initialized for the set of exception names to the error unmarshalers
func NewUnmarshalErrorHandler(unmarshaler ErrorUnmarshaler) *UnmarshalErrorHandler {
return &UnmarshalErrorHandler{
unmarshaler: unmarshaler,
}
}
// UnmarshalErrorHandlerName is the name of the named handler.
const UnmarshalErrorHandlerName = "awssdk.protocol.UnmarshalError"
// NamedHandler returns a NamedHandler for the unmarshaler using the set of
// errors the unmarshaler was initialized for.
func (u *UnmarshalErrorHandler) NamedHandler() request.NamedHandler {
return request.NamedHandler{
Name: UnmarshalErrorHandlerName,
Fn: u.UnmarshalError,
}
}
// UnmarshalError will attempt to unmarshal the API response's error message
// into either a generic SDK error type, or a typed error corresponding to the
// errors exception name.
func (u *UnmarshalErrorHandler) UnmarshalError(r *request.Request) {
defer r.HTTPResponse.Body.Close()
respMeta := ResponseMetadata{
StatusCode: r.HTTPResponse.StatusCode,
RequestID: r.RequestID,
}
v, err := u.unmarshaler.UnmarshalError(r.HTTPResponse, respMeta)
if err != nil {
r.Error = awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization,
"failed to unmarshal response error", err),
respMeta.StatusCode,
respMeta.RequestID,
)
return
}
r.Error = v
}
| 66 |
session-manager-plugin | aws | Go | package protocol_test
import (
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/ec2query"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
"github.com/aws/aws-sdk-go/private/protocol/query"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
"github.com/aws/aws-sdk-go/private/protocol/restxml"
)
type mockCloser struct {
*strings.Reader
Closed bool
}
func (m *mockCloser) Close() error {
m.Closed = true
return nil
}
func TestUnmarshalDrainBody(t *testing.T) {
b := &mockCloser{Reader: strings.NewReader("example body")}
r := &request.Request{HTTPResponse: &http.Response{
Body: b,
}}
protocol.UnmarshalDiscardBody(r)
if err := r.Error; err != nil {
t.Errorf("expect nil, %v", err)
}
if e, a := 0, b.Len(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if !b.Closed {
t.Errorf("expect true")
}
}
func TestUnmarshalDrainBodyNoBody(t *testing.T) {
r := &request.Request{HTTPResponse: &http.Response{}}
protocol.UnmarshalDiscardBody(r)
if err := r.Error; err != nil {
t.Errorf("expect nil, %v", err)
}
}
func TestUnmarshalSeriaizationError(t *testing.T) {
type testOutput struct {
_ struct{}
}
cases := []struct {
name string
r request.Request
unmarshalFn func(*request.Request)
expectedError awserr.RequestFailure
}{
{
name: "jsonrpc",
r: request.Request{
Data: &testOutput{},
HTTPResponse: &http.Response{
StatusCode: 502,
Body: ioutil.NopCloser(strings.NewReader("invalid json")),
},
},
unmarshalFn: jsonrpc.Unmarshal,
expectedError: awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization, "", nil),
502,
"",
),
},
{
name: "ec2query",
r: request.Request{
Data: &testOutput{},
HTTPResponse: &http.Response{
StatusCode: 111,
Body: ioutil.NopCloser(strings.NewReader("<<>>>>>>")),
},
},
unmarshalFn: ec2query.Unmarshal,
expectedError: awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization, "", nil),
111,
"",
),
},
{
name: "query",
r: request.Request{
Operation: &request.Operation{
Name: "Foo",
},
Data: &testOutput{},
HTTPResponse: &http.Response{
StatusCode: 1,
Body: ioutil.NopCloser(strings.NewReader("<<>>>>>>")),
},
},
unmarshalFn: query.Unmarshal,
expectedError: awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization, "", nil),
1,
"",
),
},
{
name: "restjson",
r: request.Request{
Data: &testOutput{},
HTTPResponse: &http.Response{
StatusCode: 123,
Body: ioutil.NopCloser(strings.NewReader("invalid json")),
},
},
unmarshalFn: restjson.Unmarshal,
expectedError: awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization, "", nil),
123,
"",
),
},
{
name: "restxml",
r: request.Request{
Data: &testOutput{},
HTTPResponse: &http.Response{
StatusCode: 456,
Body: ioutil.NopCloser(strings.NewReader("<<>>>>>>")),
},
},
unmarshalFn: restxml.Unmarshal,
expectedError: awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization, "", nil),
456,
"",
),
},
}
for _, c := range cases {
c.unmarshalFn(&c.r)
rfErr, ok := c.r.Error.(awserr.RequestFailure)
if !ok {
t.Errorf("%s: expected awserr.RequestFailure, but received %T", c.name, c.r.Error)
}
if e, a := c.expectedError.StatusCode(), rfErr.StatusCode(); e != a {
t.Errorf("%s: expected %v, but received %v", c.name, e, a)
}
}
}
| 166 |
session-manager-plugin | aws | Go | // Package ec2query provides serialization of AWS EC2 requests and responses.
package ec2query
//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/input/ec2.json build_test.go
import (
"net/url"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol/query/queryutil"
)
// BuildHandler is a named request handler for building ec2query protocol requests
var BuildHandler = request.NamedHandler{Name: "awssdk.ec2query.Build", Fn: Build}
// Build builds a request for the EC2 protocol.
func Build(r *request.Request) {
body := url.Values{
"Action": {r.Operation.Name},
"Version": {r.ClientInfo.APIVersion},
}
if err := queryutil.Parse(body, r.Params, true); err != nil {
r.Error = awserr.New(request.ErrCodeSerialization,
"failed encoding EC2 Query request", err)
}
if !r.IsPresigned() {
r.HTTPRequest.Method = "POST"
r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
r.SetBufferBody([]byte(body.Encode()))
} else { // This is a pre-signed request
r.HTTPRequest.Method = "GET"
r.HTTPRequest.URL.RawQuery = body.Encode()
}
}
| 37 |
session-manager-plugin | aws | Go | // +build bench
package ec2query_test
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/private/protocol/ec2query"
"github.com/aws/aws-sdk-go/service/ec2"
)
func BenchmarkEC2QueryBuild_Complex_ec2AuthorizeSecurityGroupEgress(b *testing.B) {
params := &ec2.AuthorizeSecurityGroupEgressInput{
GroupId: aws.String("String"), // Required
CidrIp: aws.String("String"),
DryRun: aws.Bool(true),
FromPort: aws.Int64(1),
IpPermissions: []*ec2.IpPermission{
{ // Required
FromPort: aws.Int64(1),
IpProtocol: aws.String("String"),
IpRanges: []*ec2.IpRange{
{ // Required
CidrIp: aws.String("String"),
},
// More values...
},
PrefixListIds: []*ec2.PrefixListId{
{ // Required
PrefixListId: aws.String("String"),
},
// More values...
},
ToPort: aws.Int64(1),
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{ // Required
GroupId: aws.String("String"),
GroupName: aws.String("String"),
UserId: aws.String("String"),
},
// More values...
},
},
// More values...
},
IpProtocol: aws.String("String"),
SourceSecurityGroupName: aws.String("String"),
SourceSecurityGroupOwnerId: aws.String("String"),
ToPort: aws.Int64(1),
}
benchEC2QueryBuild(b, "AuthorizeSecurityGroupEgress", params)
}
func BenchmarkEC2QueryBuild_Simple_ec2AttachNetworkInterface(b *testing.B) {
params := &ec2.AttachNetworkInterfaceInput{
DeviceIndex: aws.Int64(1), // Required
InstanceId: aws.String("String"), // Required
NetworkInterfaceId: aws.String("String"), // Required
DryRun: aws.Bool(true),
}
benchEC2QueryBuild(b, "AttachNetworkInterface", params)
}
func benchEC2QueryBuild(b *testing.B, opName string, params interface{}) {
svc := awstesting.NewClient()
svc.ServiceName = "ec2"
svc.APIVersion = "2015-04-15"
for i := 0; i < b.N; i++ {
r := svc.NewRequest(&request.Operation{
Name: opName,
HTTPMethod: "POST",
HTTPPath: "/",
}, params, nil)
ec2query.Build(r)
if r.Error != nil {
b.Fatal("Unexpected error", r.Error)
}
}
}
| 86 |
session-manager-plugin | aws | Go | // Code generated by models/protocol_tests/generate.go. DO NOT EDIT.
package ec2query_test
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/ec2query"
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
"github.com/aws/aws-sdk-go/private/util"
)
var _ bytes.Buffer // always import bytes
var _ http.Request
var _ json.Marshaler
var _ time.Time
var _ xmlutil.XMLNode
var _ xml.Attr
var _ = ioutil.Discard
var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
var _ = aws.String
var _ = fmt.Println
var _ = reflect.Value{}
func init() {
protocol.RandReader = &awstesting.ZeroReader{}
}
// InputService1ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService1ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService1ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService1ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService1ProtocolTest client from just a session.
// svc := inputservice1protocoltest.New(mySession)
//
// // Create a InputService1ProtocolTest client with additional configuration
// svc := inputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService1ProtocolTest {
c := p.ClientConfig("inputservice1protocoltest", cfgs...)
return newInputService1ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService1ProtocolTest {
svc := &InputService1ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService1ProtocolTest",
ServiceID: "InputService1ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService1ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService1TestCaseOperation1 = "OperationName"
// InputService1TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService1TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService1TestCaseOperation1 for more information on using the InputService1TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService1TestCaseOperation1Request method.
// req, resp := client.InputService1TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService1TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService1TestShapeInputService1TestCaseOperation1Input{}
}
output = &InputService1TestShapeInputService1TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService1TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService1TestCaseOperation1 for usage and error information.
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) {
req, out := c.InputService1TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService1TestCaseOperation1WithContext is the same as InputService1TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService1TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation1Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) {
req, out := c.InputService1TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService1TestShapeInputService1TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Bar *string `type:"string"`
Foo *string `type:"string"`
}
// SetBar sets the Bar field's value.
func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetBar(v string) *InputService1TestShapeInputService1TestCaseOperation1Input {
s.Bar = &v
return s
}
// SetFoo sets the Foo field's value.
func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetFoo(v string) *InputService1TestShapeInputService1TestCaseOperation1Input {
s.Foo = &v
return s
}
type InputService1TestShapeInputService1TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService2ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService2ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService2ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService2ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService2ProtocolTest client from just a session.
// svc := inputservice2protocoltest.New(mySession)
//
// // Create a InputService2ProtocolTest client with additional configuration
// svc := inputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService2ProtocolTest {
c := p.ClientConfig("inputservice2protocoltest", cfgs...)
return newInputService2ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService2ProtocolTest {
svc := &InputService2ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService2ProtocolTest",
ServiceID: "InputService2ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService2ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService2TestCaseOperation1 = "OperationName"
// InputService2TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService2TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService2TestCaseOperation1 for more information on using the InputService2TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService2TestCaseOperation1Request method.
// req, resp := client.InputService2TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService2TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService2TestShapeInputService2TestCaseOperation1Input{}
}
output = &InputService2TestShapeInputService2TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService2TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService2TestCaseOperation1 for usage and error information.
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) {
req, out := c.InputService2TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService2TestCaseOperation1WithContext is the same as InputService2TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService2TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1WithContext(ctx aws.Context, input *InputService2TestShapeInputService2TestCaseOperation1Input, opts ...request.Option) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) {
req, out := c.InputService2TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService2TestShapeInputService2TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Bar *string `locationName:"barLocationName" type:"string"`
Foo *string `type:"string"`
Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"`
}
// SetBar sets the Bar field's value.
func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetBar(v string) *InputService2TestShapeInputService2TestCaseOperation1Input {
s.Bar = &v
return s
}
// SetFoo sets the Foo field's value.
func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetFoo(v string) *InputService2TestShapeInputService2TestCaseOperation1Input {
s.Foo = &v
return s
}
// SetYuck sets the Yuck field's value.
func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetYuck(v string) *InputService2TestShapeInputService2TestCaseOperation1Input {
s.Yuck = &v
return s
}
type InputService2TestShapeInputService2TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService3ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService3ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService3ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService3ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService3ProtocolTest client from just a session.
// svc := inputservice3protocoltest.New(mySession)
//
// // Create a InputService3ProtocolTest client with additional configuration
// svc := inputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService3ProtocolTest {
c := p.ClientConfig("inputservice3protocoltest", cfgs...)
return newInputService3ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService3ProtocolTest {
svc := &InputService3ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService3ProtocolTest",
ServiceID: "InputService3ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService3ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService3TestCaseOperation1 = "OperationName"
// InputService3TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService3TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService3TestCaseOperation1 for more information on using the InputService3TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService3TestCaseOperation1Request method.
// req, resp := client.InputService3TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService3TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService3TestShapeInputService3TestCaseOperation1Input{}
}
output = &InputService3TestShapeInputService3TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService3TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService3TestCaseOperation1 for usage and error information.
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) {
req, out := c.InputService3TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService3TestCaseOperation1WithContext is the same as InputService3TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService3TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation1Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) {
req, out := c.InputService3TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService3TestShapeInputService3TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"`
}
// SetStructArg sets the StructArg field's value.
func (s *InputService3TestShapeInputService3TestCaseOperation1Input) SetStructArg(v *InputService3TestShapeStructType) *InputService3TestShapeInputService3TestCaseOperation1Input {
s.StructArg = v
return s
}
type InputService3TestShapeInputService3TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService3TestShapeStructType struct {
_ struct{} `type:"structure"`
ScalarArg *string `locationName:"Scalar" type:"string"`
}
// SetScalarArg sets the ScalarArg field's value.
func (s *InputService3TestShapeStructType) SetScalarArg(v string) *InputService3TestShapeStructType {
s.ScalarArg = &v
return s
}
// InputService4ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService4ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService4ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService4ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService4ProtocolTest client from just a session.
// svc := inputservice4protocoltest.New(mySession)
//
// // Create a InputService4ProtocolTest client with additional configuration
// svc := inputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService4ProtocolTest {
c := p.ClientConfig("inputservice4protocoltest", cfgs...)
return newInputService4ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService4ProtocolTest {
svc := &InputService4ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService4ProtocolTest",
ServiceID: "InputService4ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService4ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService4TestCaseOperation1 = "OperationName"
// InputService4TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService4TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService4TestCaseOperation1 for more information on using the InputService4TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService4TestCaseOperation1Request method.
// req, resp := client.InputService4TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService4TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService4TestShapeInputService4TestCaseOperation1Input{}
}
output = &InputService4TestShapeInputService4TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService4TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService4TestCaseOperation1 for usage and error information.
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) {
req, out := c.InputService4TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService4TestCaseOperation1WithContext is the same as InputService4TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService4TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation1Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) {
req, out := c.InputService4TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService4TestShapeInputService4TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
ListBools []*bool `type:"list"`
ListFloats []*float64 `type:"list"`
ListIntegers []*int64 `type:"list"`
ListStrings []*string `type:"list"`
}
// SetListBools sets the ListBools field's value.
func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListBools(v []*bool) *InputService4TestShapeInputService4TestCaseOperation1Input {
s.ListBools = v
return s
}
// SetListFloats sets the ListFloats field's value.
func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListFloats(v []*float64) *InputService4TestShapeInputService4TestCaseOperation1Input {
s.ListFloats = v
return s
}
// SetListIntegers sets the ListIntegers field's value.
func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListIntegers(v []*int64) *InputService4TestShapeInputService4TestCaseOperation1Input {
s.ListIntegers = v
return s
}
// SetListStrings sets the ListStrings field's value.
func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListStrings(v []*string) *InputService4TestShapeInputService4TestCaseOperation1Input {
s.ListStrings = v
return s
}
type InputService4TestShapeInputService4TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService5ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService5ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService5ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService5ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService5ProtocolTest client from just a session.
// svc := inputservice5protocoltest.New(mySession)
//
// // Create a InputService5ProtocolTest client with additional configuration
// svc := inputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService5ProtocolTest {
c := p.ClientConfig("inputservice5protocoltest", cfgs...)
return newInputService5ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService5ProtocolTest {
svc := &InputService5ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService5ProtocolTest",
ServiceID: "InputService5ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService5ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService5TestCaseOperation1 = "OperationName"
// InputService5TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation1 for more information on using the InputService5TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation1Request method.
// req, resp := client.InputService5TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation1Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation1 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) {
req, out := c.InputService5TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation1WithContext is the same as InputService5TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation1Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) {
req, out := c.InputService5TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService5TestShapeInputService5TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"`
}
// SetListArg sets the ListArg field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation1Input) SetListArg(v []*string) *InputService5TestShapeInputService5TestCaseOperation1Input {
s.ListArg = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService6ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService6ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService6ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService6ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService6ProtocolTest client from just a session.
// svc := inputservice6protocoltest.New(mySession)
//
// // Create a InputService6ProtocolTest client with additional configuration
// svc := inputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService6ProtocolTest {
c := p.ClientConfig("inputservice6protocoltest", cfgs...)
return newInputService6ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService6ProtocolTest {
svc := &InputService6ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService6ProtocolTest",
ServiceID: "InputService6ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService6ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService6TestCaseOperation1 = "OperationName"
// InputService6TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService6TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService6TestCaseOperation1 for more information on using the InputService6TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService6TestCaseOperation1Request method.
// req, resp := client.InputService6TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService6TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService6TestShapeInputService6TestCaseOperation1Input{}
}
output = &InputService6TestShapeInputService6TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService6TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService6TestCaseOperation1 for usage and error information.
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) {
req, out := c.InputService6TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService6TestCaseOperation1WithContext is the same as InputService6TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService6TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1WithContext(ctx aws.Context, input *InputService6TestShapeInputService6TestCaseOperation1Input, opts ...request.Option) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) {
req, out := c.InputService6TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService6TestShapeInputService6TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"`
}
// SetListArg sets the ListArg field's value.
func (s *InputService6TestShapeInputService6TestCaseOperation1Input) SetListArg(v []*string) *InputService6TestShapeInputService6TestCaseOperation1Input {
s.ListArg = v
return s
}
type InputService6TestShapeInputService6TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService7ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService7ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService7ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService7ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService7ProtocolTest client from just a session.
// svc := inputservice7protocoltest.New(mySession)
//
// // Create a InputService7ProtocolTest client with additional configuration
// svc := inputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService7ProtocolTest {
c := p.ClientConfig("inputservice7protocoltest", cfgs...)
return newInputService7ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService7ProtocolTest {
svc := &InputService7ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService7ProtocolTest",
ServiceID: "InputService7ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService7ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService7TestCaseOperation1 = "OperationName"
// InputService7TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService7TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService7TestCaseOperation1 for more information on using the InputService7TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService7TestCaseOperation1Request method.
// req, resp := client.InputService7TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService7TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService7TestShapeInputService7TestCaseOperation1Input{}
}
output = &InputService7TestShapeInputService7TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService7TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService7TestCaseOperation1 for usage and error information.
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) {
req, out := c.InputService7TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService7TestCaseOperation1WithContext is the same as InputService7TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService7TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation1Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) {
req, out := c.InputService7TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService7TestShapeInputService7TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
// BlobArg is automatically base64 encoded/decoded by the SDK.
BlobArg []byte `type:"blob"`
}
// SetBlobArg sets the BlobArg field's value.
func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetBlobArg(v []byte) *InputService7TestShapeInputService7TestCaseOperation1Input {
s.BlobArg = v
return s
}
type InputService7TestShapeInputService7TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService8ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService8ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService8ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService8ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService8ProtocolTest client from just a session.
// svc := inputservice8protocoltest.New(mySession)
//
// // Create a InputService8ProtocolTest client with additional configuration
// svc := inputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService8ProtocolTest {
c := p.ClientConfig("inputservice8protocoltest", cfgs...)
return newInputService8ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService8ProtocolTest {
svc := &InputService8ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService8ProtocolTest",
ServiceID: "InputService8ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService8ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService8TestCaseOperation1 = "OperationName"
// InputService8TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService8TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService8TestCaseOperation1 for more information on using the InputService8TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService8TestCaseOperation1Request method.
// req, resp := client.InputService8TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService8TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService8TestShapeInputService8TestCaseOperation1Input{}
}
output = &InputService8TestShapeInputService8TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService8TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService8TestCaseOperation1 for usage and error information.
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) {
req, out := c.InputService8TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService8TestCaseOperation1WithContext is the same as InputService8TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService8TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation1Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) {
req, out := c.InputService8TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService8TestShapeInputService8TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
TimeArg *time.Time `type:"timestamp"`
TimeCustom *time.Time `type:"timestamp" timestampFormat:"unixTimestamp"`
TimeFormat *time.Time `type:"timestamp" timestampFormat:"unixTimestamp"`
}
// SetTimeArg sets the TimeArg field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetTimeArg(v time.Time) *InputService8TestShapeInputService8TestCaseOperation1Input {
s.TimeArg = &v
return s
}
// SetTimeCustom sets the TimeCustom field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetTimeCustom(v time.Time) *InputService8TestShapeInputService8TestCaseOperation1Input {
s.TimeCustom = &v
return s
}
// SetTimeFormat sets the TimeFormat field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetTimeFormat(v time.Time) *InputService8TestShapeInputService8TestCaseOperation1Input {
s.TimeFormat = &v
return s
}
type InputService8TestShapeInputService8TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService9ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService9ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService9ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService9ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService9ProtocolTest client from just a session.
// svc := inputservice9protocoltest.New(mySession)
//
// // Create a InputService9ProtocolTest client with additional configuration
// svc := inputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService9ProtocolTest {
c := p.ClientConfig("inputservice9protocoltest", cfgs...)
return newInputService9ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService9ProtocolTest {
svc := &InputService9ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService9ProtocolTest",
ServiceID: "InputService9ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService9ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService9TestCaseOperation1 = "OperationName"
// InputService9TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService9TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService9TestCaseOperation1 for more information on using the InputService9TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService9TestCaseOperation1Request method.
// req, resp := client.InputService9TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputService9TestCaseOperation1Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService9TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService9TestShapeInputService9TestCaseOperation1Input{}
}
output = &InputService9TestShapeInputService9TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService9TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService9TestCaseOperation1 for usage and error information.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputService9TestCaseOperation1Input) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) {
req, out := c.InputService9TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService9TestCaseOperation1WithContext is the same as InputService9TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService9TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation1WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation1Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) {
req, out := c.InputService9TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService9TestCaseOperation2 = "OperationName"
// InputService9TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService9TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService9TestCaseOperation2 for more information on using the InputService9TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService9TestCaseOperation2Request method.
// req, resp := client.InputService9TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputService9TestCaseOperation2Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService9TestCaseOperation2,
HTTPPath: "/",
}
if input == nil {
input = &InputService9TestShapeInputService9TestCaseOperation2Input{}
}
output = &InputService9TestShapeInputService9TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService9TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService9TestCaseOperation2 for usage and error information.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *InputService9TestShapeInputService9TestCaseOperation2Input) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) {
req, out := c.InputService9TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService9TestCaseOperation2WithContext is the same as InputService9TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService9TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation2WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation2Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) {
req, out := c.InputService9TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService9TestShapeInputService9TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Token *string `type:"string" idempotencyToken:"true"`
}
// SetToken sets the Token field's value.
func (s *InputService9TestShapeInputService9TestCaseOperation1Input) SetToken(v string) *InputService9TestShapeInputService9TestCaseOperation1Input {
s.Token = &v
return s
}
type InputService9TestShapeInputService9TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService9TestShapeInputService9TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
Token *string `type:"string" idempotencyToken:"true"`
}
// SetToken sets the Token field's value.
func (s *InputService9TestShapeInputService9TestCaseOperation2Input) SetToken(v string) *InputService9TestShapeInputService9TestCaseOperation2Input {
s.Token = &v
return s
}
type InputService9TestShapeInputService9TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
// InputService10ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService10ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService10ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService10ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService10ProtocolTest client from just a session.
// svc := inputservice10protocoltest.New(mySession)
//
// // Create a InputService10ProtocolTest client with additional configuration
// svc := inputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService10ProtocolTest {
c := p.ClientConfig("inputservice10protocoltest", cfgs...)
return newInputService10ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService10ProtocolTest {
svc := &InputService10ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService10ProtocolTest",
ServiceID: "InputService10ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService10ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService10TestCaseOperation1 = "OperationName"
// InputService10TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService10TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService10TestCaseOperation1 for more information on using the InputService10TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService10TestCaseOperation1Request method.
// req, resp := client.InputService10TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputService10TestCaseOperation1Input) (req *request.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService10TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService10TestShapeInputService10TestCaseOperation1Input{}
}
output = &InputService10TestShapeInputService10TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService10TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService10TestCaseOperation1 for usage and error information.
func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *InputService10TestShapeInputService10TestCaseOperation1Input) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) {
req, out := c.InputService10TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService10TestCaseOperation1WithContext is the same as InputService10TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService10TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService10ProtocolTest) InputService10TestCaseOperation1WithContext(ctx aws.Context, input *InputService10TestShapeInputService10TestCaseOperation1Input, opts ...request.Option) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) {
req, out := c.InputService10TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService10TestCaseOperation2 = "OperationName"
// InputService10TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService10TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService10TestCaseOperation2 for more information on using the InputService10TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService10TestCaseOperation2Request method.
// req, resp := client.InputService10TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService10ProtocolTest) InputService10TestCaseOperation2Request(input *InputService10TestShapeInputService10TestCaseOperation2Input) (req *request.Request, output *InputService10TestShapeInputService10TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService10TestCaseOperation2,
HTTPPath: "/",
}
if input == nil {
input = &InputService10TestShapeInputService10TestCaseOperation2Input{}
}
output = &InputService10TestShapeInputService10TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService10TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService10TestCaseOperation2 for usage and error information.
func (c *InputService10ProtocolTest) InputService10TestCaseOperation2(input *InputService10TestShapeInputService10TestCaseOperation2Input) (*InputService10TestShapeInputService10TestCaseOperation2Output, error) {
req, out := c.InputService10TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService10TestCaseOperation2WithContext is the same as InputService10TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService10TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService10ProtocolTest) InputService10TestCaseOperation2WithContext(ctx aws.Context, input *InputService10TestShapeInputService10TestCaseOperation2Input, opts ...request.Option) (*InputService10TestShapeInputService10TestCaseOperation2Output, error) {
req, out := c.InputService10TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService10TestShapeInputService10TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
FooEnum *string `type:"string" enum:"InputService10TestShapeEnumType"`
ListEnums []*string `type:"list"`
}
// SetFooEnum sets the FooEnum field's value.
func (s *InputService10TestShapeInputService10TestCaseOperation1Input) SetFooEnum(v string) *InputService10TestShapeInputService10TestCaseOperation1Input {
s.FooEnum = &v
return s
}
// SetListEnums sets the ListEnums field's value.
func (s *InputService10TestShapeInputService10TestCaseOperation1Input) SetListEnums(v []*string) *InputService10TestShapeInputService10TestCaseOperation1Input {
s.ListEnums = v
return s
}
type InputService10TestShapeInputService10TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService10TestShapeInputService10TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
FooEnum *string `type:"string" enum:"InputService10TestShapeEnumType"`
ListEnums []*string `type:"list"`
}
// SetFooEnum sets the FooEnum field's value.
func (s *InputService10TestShapeInputService10TestCaseOperation2Input) SetFooEnum(v string) *InputService10TestShapeInputService10TestCaseOperation2Input {
s.FooEnum = &v
return s
}
// SetListEnums sets the ListEnums field's value.
func (s *InputService10TestShapeInputService10TestCaseOperation2Input) SetListEnums(v []*string) *InputService10TestShapeInputService10TestCaseOperation2Input {
s.ListEnums = v
return s
}
type InputService10TestShapeInputService10TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
const (
// EnumTypeFoo is a InputService10TestShapeEnumType enum value
EnumTypeFoo = "foo"
// EnumTypeBar is a InputService10TestShapeEnumType enum value
EnumTypeBar = "bar"
)
// InputService10TestShapeEnumType_Values returns all elements of the InputService10TestShapeEnumType enum
func InputService10TestShapeEnumType_Values() []string {
return []string{
EnumTypeFoo,
EnumTypeBar,
}
}
// InputService11ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService11ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService11ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService11ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService11ProtocolTest client from just a session.
// svc := inputservice11protocoltest.New(mySession)
//
// // Create a InputService11ProtocolTest client with additional configuration
// svc := inputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService11ProtocolTest {
c := p.ClientConfig("inputservice11protocoltest", cfgs...)
return newInputService11ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService11ProtocolTest {
svc := &InputService11ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService11ProtocolTest",
ServiceID: "InputService11ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService11ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService11TestCaseOperation1 = "StaticOp"
// InputService11TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService11TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService11TestCaseOperation1 for more information on using the InputService11TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService11TestCaseOperation1Request method.
// req, resp := client.InputService11TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService11ProtocolTest) InputService11TestCaseOperation1Request(input *InputService11TestShapeInputService11TestCaseOperation1Input) (req *request.Request, output *InputService11TestShapeInputService11TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService11TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService11TestShapeInputService11TestCaseOperation1Input{}
}
output = &InputService11TestShapeInputService11TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
req.Handlers.Build.PushBackNamed(protocol.NewHostPrefixHandler("data-", nil))
req.Handlers.Build.PushBackNamed(protocol.ValidateEndpointHostHandler)
return
}
// InputService11TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService11TestCaseOperation1 for usage and error information.
func (c *InputService11ProtocolTest) InputService11TestCaseOperation1(input *InputService11TestShapeInputService11TestCaseOperation1Input) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) {
req, out := c.InputService11TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService11TestCaseOperation1WithContext is the same as InputService11TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService11TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService11ProtocolTest) InputService11TestCaseOperation1WithContext(ctx aws.Context, input *InputService11TestShapeInputService11TestCaseOperation1Input, opts ...request.Option) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) {
req, out := c.InputService11TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService11TestCaseOperation2 = "MemberRefOp"
// InputService11TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService11TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService11TestCaseOperation2 for more information on using the InputService11TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService11TestCaseOperation2Request method.
// req, resp := client.InputService11TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService11ProtocolTest) InputService11TestCaseOperation2Request(input *InputService11TestShapeInputService11TestCaseOperation2Input) (req *request.Request, output *InputService11TestShapeInputService11TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService11TestCaseOperation2,
HTTPPath: "/",
}
if input == nil {
input = &InputService11TestShapeInputService11TestCaseOperation2Input{}
}
output = &InputService11TestShapeInputService11TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
req.Handlers.Build.PushBackNamed(protocol.NewHostPrefixHandler("foo-{Name}.", input.hostLabels))
req.Handlers.Build.PushBackNamed(protocol.ValidateEndpointHostHandler)
return
}
// InputService11TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService11TestCaseOperation2 for usage and error information.
func (c *InputService11ProtocolTest) InputService11TestCaseOperation2(input *InputService11TestShapeInputService11TestCaseOperation2Input) (*InputService11TestShapeInputService11TestCaseOperation2Output, error) {
req, out := c.InputService11TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService11TestCaseOperation2WithContext is the same as InputService11TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService11TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService11ProtocolTest) InputService11TestCaseOperation2WithContext(ctx aws.Context, input *InputService11TestShapeInputService11TestCaseOperation2Input, opts ...request.Option) (*InputService11TestShapeInputService11TestCaseOperation2Output, error) {
req, out := c.InputService11TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService11TestShapeInputService11TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Name *string `type:"string"`
}
// SetName sets the Name field's value.
func (s *InputService11TestShapeInputService11TestCaseOperation1Input) SetName(v string) *InputService11TestShapeInputService11TestCaseOperation1Input {
s.Name = &v
return s
}
type InputService11TestShapeInputService11TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService11TestShapeInputService11TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
// Name is a required field
Name *string `type:"string" required:"true"`
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *InputService11TestShapeInputService11TestCaseOperation2Input) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "InputService11TestShapeInputService11TestCaseOperation2Input"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if s.Name != nil && len(*s.Name) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Name", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetName sets the Name field's value.
func (s *InputService11TestShapeInputService11TestCaseOperation2Input) SetName(v string) *InputService11TestShapeInputService11TestCaseOperation2Input {
s.Name = &v
return s
}
func (s *InputService11TestShapeInputService11TestCaseOperation2Input) hostLabels() map[string]string {
return map[string]string{
"Name": aws.StringValue(s.Name),
}
}
type InputService11TestShapeInputService11TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
//
// Tests begin here
//
func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) {
svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService1TestShapeInputService1TestCaseOperation1Input{
Bar: aws.String("val2"),
Foo: aws.String("val1"),
}
req, _ := svc.InputService1TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService2ProtocolTestStructureWithLocationNameAndQueryNameAppliedToMembersCase1(t *testing.T) {
svc := NewInputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService2TestShapeInputService2TestCaseOperation1Input{
Bar: aws.String("val2"),
Foo: aws.String("val1"),
Yuck: aws.String("val3"),
}
req, _ := svc.InputService2TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&BarLocationName=val2&Foo=val1&Version=2014-01-01&yuckQueryName=val3`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService3ProtocolTestNestedStructureMembersCase1(t *testing.T) {
svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService3TestShapeInputService3TestCaseOperation1Input{
StructArg: &InputService3TestShapeStructType{
ScalarArg: aws.String("foo"),
},
}
req, _ := svc.InputService3TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&Struct.Scalar=foo&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService4ProtocolTestListTypesCase1(t *testing.T) {
svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService4TestShapeInputService4TestCaseOperation1Input{
ListBools: []*bool{
aws.Bool(true),
aws.Bool(false),
aws.Bool(false),
},
ListFloats: []*float64{
aws.Float64(1.1),
aws.Float64(2.718),
aws.Float64(3.14),
},
ListIntegers: []*int64{
aws.Int64(0),
aws.Int64(1),
aws.Int64(2),
},
ListStrings: []*string{
aws.String("foo"),
aws.String("bar"),
aws.String("baz"),
},
}
req, _ := svc.InputService4TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&ListBools.1=true&ListBools.2=false&ListBools.3=false&ListFloats.1=1.1&ListFloats.2=2.718&ListFloats.3=3.14&ListIntegers.1=0&ListIntegers.2=1&ListIntegers.3=2&ListStrings.1=foo&ListStrings.2=bar&ListStrings.3=baz&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService5ProtocolTestListWithLocationNameAppliedToMemberCase1(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation1Input{
ListArg: []*string{
aws.String("a"),
aws.String("b"),
aws.String("c"),
},
}
req, _ := svc.InputService5TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&ListMemberName.1=a&ListMemberName.2=b&ListMemberName.3=c&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService6ProtocolTestListWithLocationNameAndQueryNameCase1(t *testing.T) {
svc := NewInputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService6TestShapeInputService6TestCaseOperation1Input{
ListArg: []*string{
aws.String("a"),
aws.String("b"),
aws.String("c"),
},
}
req, _ := svc.InputService6TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&ListQueryName.1=a&ListQueryName.2=b&ListQueryName.3=c&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) {
svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService7TestShapeInputService7TestCaseOperation1Input{
BlobArg: []byte("foo"),
}
req, _ := svc.InputService7TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) {
svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService8TestShapeInputService8TestCaseOperation1Input{
TimeArg: aws.Time(time.Unix(1422172800, 0)),
TimeCustom: aws.Time(time.Unix(1422172800, 0)),
TimeFormat: aws.Time(time.Unix(1422172800, 0)),
}
req, _ := svc.InputService8TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&TimeCustom=1422172800&TimeFormat=1422172800&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService9ProtocolTestIdempotencyTokenAutoFillCase1(t *testing.T) {
svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService9TestShapeInputService9TestCaseOperation1Input{
Token: aws.String("abc123"),
}
req, _ := svc.InputService9TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&Token=abc123&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService9ProtocolTestIdempotencyTokenAutoFillCase2(t *testing.T) {
svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService9TestShapeInputService9TestCaseOperation2Input{}
req, _ := svc.InputService9TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&Token=00000000-0000-4000-8000-000000000000&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService10ProtocolTestEnumCase1(t *testing.T) {
svc := NewInputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService10TestShapeInputService10TestCaseOperation1Input{
ListEnums: []*string{
aws.String("foo"),
aws.String(""),
aws.String("bar"),
},
}
req, _ := svc.InputService10TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&ListEnums.1=foo&ListEnums.2=&ListEnums.3=bar&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService10ProtocolTestEnumCase2(t *testing.T) {
svc := NewInputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService10TestShapeInputService10TestCaseOperation2Input{}
req, _ := svc.InputService10TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=OperationName&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService11ProtocolTestEndpointHostTraitCase1(t *testing.T) {
svc := NewInputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://service.region.amazonaws.com")})
input := &InputService11TestShapeInputService11TestCaseOperation1Input{
Name: aws.String("myname"),
}
req, _ := svc.InputService11TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=StaticOp&Name=myname&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://data-service.region.amazonaws.com/", r.URL.String())
// assert headers
}
func TestInputService11ProtocolTestEndpointHostTraitCase2(t *testing.T) {
svc := NewInputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://service.region.amazonaws.com")})
input := &InputService11TestShapeInputService11TestCaseOperation2Input{
Name: aws.String("myname"),
}
req, _ := svc.InputService11TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertQuery(t, `Action=MemberRefOp&Name=myname&Version=2014-01-01`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://foo-myname.service.region.amazonaws.com/", r.URL.String())
// assert headers
}
| 2,497 |
session-manager-plugin | aws | Go | package ec2query
//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/output/ec2.json unmarshal_test.go
import (
"encoding/xml"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
)
// UnmarshalHandler is a named request handler for unmarshaling ec2query protocol requests
var UnmarshalHandler = request.NamedHandler{Name: "awssdk.ec2query.Unmarshal", Fn: Unmarshal}
// UnmarshalMetaHandler is a named request handler for unmarshaling ec2query protocol request metadata
var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.ec2query.UnmarshalMeta", Fn: UnmarshalMeta}
// UnmarshalErrorHandler is a named request handler for unmarshaling ec2query protocol request errors
var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.ec2query.UnmarshalError", Fn: UnmarshalError}
// Unmarshal unmarshals a response body for the EC2 protocol.
func Unmarshal(r *request.Request) {
defer r.HTTPResponse.Body.Close()
if r.DataFilled() {
decoder := xml.NewDecoder(r.HTTPResponse.Body)
err := xmlutil.UnmarshalXML(r.Data, decoder, "")
if err != nil {
r.Error = awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization,
"failed decoding EC2 Query response", err),
r.HTTPResponse.StatusCode,
r.RequestID,
)
return
}
}
}
// UnmarshalMeta unmarshals response headers for the EC2 protocol.
func UnmarshalMeta(r *request.Request) {
r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid")
if r.RequestID == "" {
// Alternative version of request id in the header
r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id")
}
}
type xmlErrorResponse struct {
XMLName xml.Name `xml:"Response"`
Code string `xml:"Errors>Error>Code"`
Message string `xml:"Errors>Error>Message"`
RequestID string `xml:"RequestID"`
}
// UnmarshalError unmarshals a response error for the EC2 protocol.
func UnmarshalError(r *request.Request) {
defer r.HTTPResponse.Body.Close()
var respErr xmlErrorResponse
err := xmlutil.UnmarshalXMLError(&respErr, r.HTTPResponse.Body)
if err != nil {
r.Error = awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization,
"failed to unmarshal error message", err),
r.HTTPResponse.StatusCode,
r.RequestID,
)
return
}
r.Error = awserr.NewRequestFailure(
awserr.New(respErr.Code, respErr.Message, nil),
r.HTTPResponse.StatusCode,
respErr.RequestID,
)
}
| 78 |
session-manager-plugin | aws | Go | // +build go1.8
package ec2query
import (
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
func TestUnmarshalError(t *testing.T) {
cases := map[string]struct {
Request *request.Request
Code, Msg string
ReqID string
Status int
}{
"ErrorResponse": {
Request: &request.Request{
HTTPResponse: &http.Response{
StatusCode: 400,
Header: http.Header{},
Body: ioutil.NopCloser(strings.NewReader(
`<Response>
<Errors>
<Error>
<Code>codeAbc</Code>
<Message>msg123</Message>
</Error>
</Errors>
<RequestID>reqID123</RequestID>
</Response>`)),
},
},
Code: "codeAbc", Msg: "msg123",
Status: 400, ReqID: "reqID123",
},
"unknown tag": {
Request: &request.Request{
HTTPResponse: &http.Response{
StatusCode: 400,
Header: http.Header{},
Body: ioutil.NopCloser(strings.NewReader(
`<Hello>
<World>.</World>
</Hello>`)),
},
},
Code: request.ErrCodeSerialization,
Msg: "failed to unmarshal error message",
Status: 400,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
r := c.Request
UnmarshalError(r)
if r.Error == nil {
t.Fatalf("expect error, got none")
}
aerr := r.Error.(awserr.RequestFailure)
if e, a := c.Code, aerr.Code(); e != a {
t.Errorf("expect %v code, got %v", e, a)
}
if e, a := c.Msg, aerr.Message(); e != a {
t.Errorf("expect %q message, got %q", e, a)
}
if e, a := c.ReqID, aerr.RequestID(); e != a {
t.Errorf("expect %v request ID, got %v", e, a)
}
if e, a := c.Status, aerr.StatusCode(); e != a {
t.Errorf("expect %v status code, got %v", e, a)
}
})
}
}
| 83 |
session-manager-plugin | aws | Go | // Code generated by models/protocol_tests/generate.go. DO NOT EDIT.
package ec2query_test
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/ec2query"
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
"github.com/aws/aws-sdk-go/private/util"
)
var _ bytes.Buffer // always import bytes
var _ http.Request
var _ json.Marshaler
var _ time.Time
var _ xmlutil.XMLNode
var _ xml.Attr
var _ = ioutil.Discard
var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
var _ = aws.String
var _ = fmt.Println
var _ = reflect.Value{}
func init() {
protocol.RandReader = &awstesting.ZeroReader{}
}
// OutputService1ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService1ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService1ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService1ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService1ProtocolTest client from just a session.
// svc := outputservice1protocoltest.New(mySession)
//
// // Create a OutputService1ProtocolTest client with additional configuration
// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest {
c := p.ClientConfig("outputservice1protocoltest", cfgs...)
return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService1ProtocolTest {
svc := &OutputService1ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService1ProtocolTest",
ServiceID: "OutputService1ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService1TestCaseOperation1 = "OperationName"
// OutputService1TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService1TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService1TestCaseOperation1 for more information on using the OutputService1TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService1TestCaseOperation1Request method.
// req, resp := client.OutputService1TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService1TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{}
}
output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService1TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService1TestCaseOperation1 for usage and error information.
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) {
req, out := c.OutputService1TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService1TestCaseOperation1WithContext is the same as OutputService1TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService1TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1WithContext(ctx aws.Context, input *OutputService1TestShapeOutputService1TestCaseOperation1Input, opts ...request.Option) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) {
req, out := c.OutputService1TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService1TestShapeOutputService1TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService1TestShapeOutputService1TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Char *string `type:"character"`
Double *float64 `type:"double"`
FalseBool *bool `type:"boolean"`
Float *float64 `type:"float"`
Long *int64 `type:"long"`
Num *int64 `locationName:"FooNum" type:"integer"`
Str *string `type:"string"`
TrueBool *bool `type:"boolean"`
}
// SetChar sets the Char field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetChar(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Char = &v
return s
}
// SetDouble sets the Double field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetDouble(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Double = &v
return s
}
// SetFalseBool sets the FalseBool field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFalseBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.FalseBool = &v
return s
}
// SetFloat sets the Float field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFloat(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Float = &v
return s
}
// SetLong sets the Long field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetLong(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Long = &v
return s
}
// SetNum sets the Num field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetNum(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Num = &v
return s
}
// SetStr sets the Str field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetStr(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Str = &v
return s
}
// SetTrueBool sets the TrueBool field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTrueBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.TrueBool = &v
return s
}
// OutputService2ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService2ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService2ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService2ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService2ProtocolTest client from just a session.
// svc := outputservice2protocoltest.New(mySession)
//
// // Create a OutputService2ProtocolTest client with additional configuration
// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest {
c := p.ClientConfig("outputservice2protocoltest", cfgs...)
return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService2ProtocolTest {
svc := &OutputService2ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService2ProtocolTest",
ServiceID: "OutputService2ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService2TestCaseOperation1 = "OperationName"
// OutputService2TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService2TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService2TestCaseOperation1 for more information on using the OutputService2TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService2TestCaseOperation1Request method.
// req, resp := client.OutputService2TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService2TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{}
}
output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService2TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService2TestCaseOperation1 for usage and error information.
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) {
req, out := c.OutputService2TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService2TestCaseOperation1WithContext is the same as OutputService2TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService2TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1WithContext(ctx aws.Context, input *OutputService2TestShapeOutputService2TestCaseOperation1Input, opts ...request.Option) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) {
req, out := c.OutputService2TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService2TestShapeOutputService2TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService2TestShapeOutputService2TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
// Blob is automatically base64 encoded/decoded by the SDK.
Blob []byte `type:"blob"`
}
// SetBlob sets the Blob field's value.
func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetBlob(v []byte) *OutputService2TestShapeOutputService2TestCaseOperation1Output {
s.Blob = v
return s
}
// OutputService3ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService3ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService3ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService3ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService3ProtocolTest client from just a session.
// svc := outputservice3protocoltest.New(mySession)
//
// // Create a OutputService3ProtocolTest client with additional configuration
// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest {
c := p.ClientConfig("outputservice3protocoltest", cfgs...)
return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService3ProtocolTest {
svc := &OutputService3ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService3ProtocolTest",
ServiceID: "OutputService3ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService3TestCaseOperation1 = "OperationName"
// OutputService3TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService3TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService3TestCaseOperation1 for more information on using the OutputService3TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService3TestCaseOperation1Request method.
// req, resp := client.OutputService3TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService3TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{}
}
output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService3TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService3TestCaseOperation1 for usage and error information.
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) {
req, out := c.OutputService3TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService3TestCaseOperation1WithContext is the same as OutputService3TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService3TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1WithContext(ctx aws.Context, input *OutputService3TestShapeOutputService3TestCaseOperation1Input, opts ...request.Option) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) {
req, out := c.OutputService3TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService3TestShapeOutputService3TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService3TestShapeOutputService3TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list"`
}
// SetListMember sets the ListMember field's value.
func (s *OutputService3TestShapeOutputService3TestCaseOperation1Output) SetListMember(v []*string) *OutputService3TestShapeOutputService3TestCaseOperation1Output {
s.ListMember = v
return s
}
// OutputService4ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService4ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService4ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService4ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService4ProtocolTest client from just a session.
// svc := outputservice4protocoltest.New(mySession)
//
// // Create a OutputService4ProtocolTest client with additional configuration
// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest {
c := p.ClientConfig("outputservice4protocoltest", cfgs...)
return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService4ProtocolTest {
svc := &OutputService4ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService4ProtocolTest",
ServiceID: "OutputService4ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService4TestCaseOperation1 = "OperationName"
// OutputService4TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService4TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService4TestCaseOperation1 for more information on using the OutputService4TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService4TestCaseOperation1Request method.
// req, resp := client.OutputService4TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService4TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{}
}
output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService4TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService4TestCaseOperation1 for usage and error information.
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) {
req, out := c.OutputService4TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService4TestCaseOperation1WithContext is the same as OutputService4TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService4TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1WithContext(ctx aws.Context, input *OutputService4TestShapeOutputService4TestCaseOperation1Input, opts ...request.Option) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) {
req, out := c.OutputService4TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService4TestShapeOutputService4TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService4TestShapeOutputService4TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `locationNameList:"item" type:"list"`
}
// SetListMember sets the ListMember field's value.
func (s *OutputService4TestShapeOutputService4TestCaseOperation1Output) SetListMember(v []*string) *OutputService4TestShapeOutputService4TestCaseOperation1Output {
s.ListMember = v
return s
}
// OutputService5ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService5ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService5ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService5ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService5ProtocolTest client from just a session.
// svc := outputservice5protocoltest.New(mySession)
//
// // Create a OutputService5ProtocolTest client with additional configuration
// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest {
c := p.ClientConfig("outputservice5protocoltest", cfgs...)
return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService5ProtocolTest {
svc := &OutputService5ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService5ProtocolTest",
ServiceID: "OutputService5ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService5TestCaseOperation1 = "OperationName"
// OutputService5TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService5TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService5TestCaseOperation1 for more information on using the OutputService5TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService5TestCaseOperation1Request method.
// req, resp := client.OutputService5TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService5TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{}
}
output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService5TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService5TestCaseOperation1 for usage and error information.
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) {
req, out := c.OutputService5TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService5TestCaseOperation1WithContext is the same as OutputService5TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService5TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1WithContext(ctx aws.Context, input *OutputService5TestShapeOutputService5TestCaseOperation1Input, opts ...request.Option) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) {
req, out := c.OutputService5TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService5TestShapeOutputService5TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService5TestShapeOutputService5TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list" flattened:"true"`
}
// SetListMember sets the ListMember field's value.
func (s *OutputService5TestShapeOutputService5TestCaseOperation1Output) SetListMember(v []*string) *OutputService5TestShapeOutputService5TestCaseOperation1Output {
s.ListMember = v
return s
}
// OutputService6ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService6ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService6ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService6ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService6ProtocolTest client from just a session.
// svc := outputservice6protocoltest.New(mySession)
//
// // Create a OutputService6ProtocolTest client with additional configuration
// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest {
c := p.ClientConfig("outputservice6protocoltest", cfgs...)
return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService6ProtocolTest {
svc := &OutputService6ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService6ProtocolTest",
ServiceID: "OutputService6ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService6TestCaseOperation1 = "OperationName"
// OutputService6TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService6TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService6TestCaseOperation1 for more information on using the OutputService6TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService6TestCaseOperation1Request method.
// req, resp := client.OutputService6TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService6TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{}
}
output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService6TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService6TestCaseOperation1 for usage and error information.
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) {
req, out := c.OutputService6TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService6TestCaseOperation1WithContext is the same as OutputService6TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService6TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1WithContext(ctx aws.Context, input *OutputService6TestShapeOutputService6TestCaseOperation1Input, opts ...request.Option) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) {
req, out := c.OutputService6TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService6TestShapeOutputService6TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService6TestShapeOutputService6TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*OutputService6TestShapeStructureType `type:"map"`
}
// SetMap sets the Map field's value.
func (s *OutputService6TestShapeOutputService6TestCaseOperation1Output) SetMap(v map[string]*OutputService6TestShapeStructureType) *OutputService6TestShapeOutputService6TestCaseOperation1Output {
s.Map = v
return s
}
type OutputService6TestShapeStructureType struct {
_ struct{} `type:"structure"`
Foo *string `locationName:"foo" type:"string"`
}
// SetFoo sets the Foo field's value.
func (s *OutputService6TestShapeStructureType) SetFoo(v string) *OutputService6TestShapeStructureType {
s.Foo = &v
return s
}
// OutputService7ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService7ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService7ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService7ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService7ProtocolTest client from just a session.
// svc := outputservice7protocoltest.New(mySession)
//
// // Create a OutputService7ProtocolTest client with additional configuration
// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest {
c := p.ClientConfig("outputservice7protocoltest", cfgs...)
return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService7ProtocolTest {
svc := &OutputService7ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService7ProtocolTest",
ServiceID: "OutputService7ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService7TestCaseOperation1 = "OperationName"
// OutputService7TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService7TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService7TestCaseOperation1 for more information on using the OutputService7TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService7TestCaseOperation1Request method.
// req, resp := client.OutputService7TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService7TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{}
}
output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService7TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService7TestCaseOperation1 for usage and error information.
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) {
req, out := c.OutputService7TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService7TestCaseOperation1WithContext is the same as OutputService7TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService7TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1WithContext(ctx aws.Context, input *OutputService7TestShapeOutputService7TestCaseOperation1Input, opts ...request.Option) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) {
req, out := c.OutputService7TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService7TestShapeOutputService7TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService7TestShapeOutputService7TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `type:"map" flattened:"true"`
}
// SetMap sets the Map field's value.
func (s *OutputService7TestShapeOutputService7TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService7TestShapeOutputService7TestCaseOperation1Output {
s.Map = v
return s
}
// OutputService8ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService8ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService8ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService8ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService8ProtocolTest client from just a session.
// svc := outputservice8protocoltest.New(mySession)
//
// // Create a OutputService8ProtocolTest client with additional configuration
// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest {
c := p.ClientConfig("outputservice8protocoltest", cfgs...)
return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService8ProtocolTest {
svc := &OutputService8ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService8ProtocolTest",
ServiceID: "OutputService8ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService8TestCaseOperation1 = "OperationName"
// OutputService8TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService8TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService8TestCaseOperation1 for more information on using the OutputService8TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService8TestCaseOperation1Request method.
// req, resp := client.OutputService8TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService8TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{}
}
output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService8TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService8TestCaseOperation1 for usage and error information.
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) {
req, out := c.OutputService8TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService8TestCaseOperation1WithContext is the same as OutputService8TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService8TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1WithContext(ctx aws.Context, input *OutputService8TestShapeOutputService8TestCaseOperation1Input, opts ...request.Option) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) {
req, out := c.OutputService8TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService8TestShapeOutputService8TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService8TestShapeOutputService8TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"`
}
// SetMap sets the Map field's value.
func (s *OutputService8TestShapeOutputService8TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService8TestShapeOutputService8TestCaseOperation1Output {
s.Map = v
return s
}
// OutputService9ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService9ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService9ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService9ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService9ProtocolTest client from just a session.
// svc := outputservice9protocoltest.New(mySession)
//
// // Create a OutputService9ProtocolTest client with additional configuration
// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest {
c := p.ClientConfig("outputservice9protocoltest", cfgs...)
return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService9ProtocolTest {
svc := &OutputService9ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService9ProtocolTest",
ServiceID: "OutputService9ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService9TestCaseOperation1 = "OperationName"
// OutputService9TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService9TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService9TestCaseOperation1 for more information on using the OutputService9TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService9TestCaseOperation1Request method.
// req, resp := client.OutputService9TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService9TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{}
}
output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService9TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService9TestCaseOperation1 for usage and error information.
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) {
req, out := c.OutputService9TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService9TestCaseOperation1WithContext is the same as OutputService9TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService9TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1WithContext(ctx aws.Context, input *OutputService9TestShapeOutputService9TestCaseOperation1Input, opts ...request.Option) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) {
req, out := c.OutputService9TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService9TestShapeOutputService9TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService9TestShapeOutputService9TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Foo *string `type:"string"`
}
// SetFoo sets the Foo field's value.
func (s *OutputService9TestShapeOutputService9TestCaseOperation1Output) SetFoo(v string) *OutputService9TestShapeOutputService9TestCaseOperation1Output {
s.Foo = &v
return s
}
// OutputService10ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService10ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService10ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService10ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService10ProtocolTest client from just a session.
// svc := outputservice10protocoltest.New(mySession)
//
// // Create a OutputService10ProtocolTest client with additional configuration
// svc := outputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService10ProtocolTest {
c := p.ClientConfig("outputservice10protocoltest", cfgs...)
return newOutputService10ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService10ProtocolTest {
svc := &OutputService10ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService10ProtocolTest",
ServiceID: "OutputService10ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService10TestCaseOperation1 = "OperationName"
// OutputService10TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService10TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService10TestCaseOperation1 for more information on using the OutputService10TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService10TestCaseOperation1Request method.
// req, resp := client.OutputService10TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService10TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{}
}
output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService10TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService10TestCaseOperation1 for usage and error information.
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) {
req, out := c.OutputService10TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService10TestCaseOperation1WithContext is the same as OutputService10TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService10TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1WithContext(ctx aws.Context, input *OutputService10TestShapeOutputService10TestCaseOperation1Input, opts ...request.Option) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) {
req, out := c.OutputService10TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService10TestShapeOutputService10TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService10TestShapeOutputService10TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
StructMember *OutputService10TestShapeTimeContainer `type:"structure"`
TimeArg *time.Time `type:"timestamp"`
TimeCustom *time.Time `type:"timestamp" timestampFormat:"rfc822"`
TimeFormat *time.Time `type:"timestamp" timestampFormat:"unixTimestamp"`
}
// SetStructMember sets the StructMember field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetStructMember(v *OutputService10TestShapeTimeContainer) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.StructMember = v
return s
}
// SetTimeArg sets the TimeArg field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetTimeArg(v time.Time) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.TimeArg = &v
return s
}
// SetTimeCustom sets the TimeCustom field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetTimeCustom(v time.Time) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.TimeCustom = &v
return s
}
// SetTimeFormat sets the TimeFormat field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetTimeFormat(v time.Time) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.TimeFormat = &v
return s
}
type OutputService10TestShapeTimeContainer struct {
_ struct{} `type:"structure"`
Bar *time.Time `locationName:"bar" type:"timestamp" timestampFormat:"unixTimestamp"`
Foo *time.Time `locationName:"foo" type:"timestamp"`
}
// SetBar sets the Bar field's value.
func (s *OutputService10TestShapeTimeContainer) SetBar(v time.Time) *OutputService10TestShapeTimeContainer {
s.Bar = &v
return s
}
// SetFoo sets the Foo field's value.
func (s *OutputService10TestShapeTimeContainer) SetFoo(v time.Time) *OutputService10TestShapeTimeContainer {
s.Foo = &v
return s
}
// OutputService11ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService11ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService11ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService11ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService11ProtocolTest client from just a session.
// svc := outputservice11protocoltest.New(mySession)
//
// // Create a OutputService11ProtocolTest client with additional configuration
// svc := outputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService11ProtocolTest {
c := p.ClientConfig("outputservice11protocoltest", cfgs...)
return newOutputService11ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService11ProtocolTest {
svc := &OutputService11ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService11ProtocolTest",
ServiceID: "OutputService11ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService11TestCaseOperation1 = "OperationName"
// OutputService11TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService11TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService11TestCaseOperation1 for more information on using the OutputService11TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService11TestCaseOperation1Request method.
// req, resp := client.OutputService11TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *request.Request, output *OutputService11TestShapeOutputService11TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService11TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{}
}
output = &OutputService11TestShapeOutputService11TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService11TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService11TestCaseOperation1 for usage and error information.
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) {
req, out := c.OutputService11TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService11TestCaseOperation1WithContext is the same as OutputService11TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService11TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1WithContext(ctx aws.Context, input *OutputService11TestShapeOutputService11TestCaseOperation1Input, opts ...request.Option) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) {
req, out := c.OutputService11TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService11TestShapeOutputService11TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService11TestShapeOutputService11TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
FooEnum *string `type:"string" enum:"OutputService11TestShapeEC2EnumType"`
ListEnums []*string `type:"list"`
}
// SetFooEnum sets the FooEnum field's value.
func (s *OutputService11TestShapeOutputService11TestCaseOperation1Output) SetFooEnum(v string) *OutputService11TestShapeOutputService11TestCaseOperation1Output {
s.FooEnum = &v
return s
}
// SetListEnums sets the ListEnums field's value.
func (s *OutputService11TestShapeOutputService11TestCaseOperation1Output) SetListEnums(v []*string) *OutputService11TestShapeOutputService11TestCaseOperation1Output {
s.ListEnums = v
return s
}
const (
// EC2EnumTypeFoo is a OutputService11TestShapeEC2EnumType enum value
EC2EnumTypeFoo = "foo"
// EC2EnumTypeBar is a OutputService11TestShapeEC2EnumType enum value
EC2EnumTypeBar = "bar"
)
// OutputService11TestShapeEC2EnumType_Values returns all elements of the OutputService11TestShapeEC2EnumType enum
func OutputService11TestShapeEC2EnumType_Values() []string {
return []string{
EC2EnumTypeFoo,
EC2EnumTypeBar,
}
}
//
// Tests begin here
//
func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) {
svc := NewOutputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Str>myname</Str><FooNum>123</FooNum><FalseBool>false</FalseBool><TrueBool>true</TrueBool><Float>1.2</Float><Double>1.3</Double><Long>200</Long><Char>a</Char><RequestId>request-id</RequestId></OperationNameResponse>"))
req, out := svc.OutputService1TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "a", *out.Char; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := 1.3, *out.Double; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := false, *out.FalseBool; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := 1.2, *out.Float; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := int64(200), *out.Long; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := int64(123), *out.Num; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "myname", *out.Str; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := true, *out.TrueBool; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService2ProtocolTestBlobCase1(t *testing.T) {
svc := NewOutputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Blob>dmFsdWU=</Blob><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService2TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "value", string(out.Blob); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService3ProtocolTestListsCase1(t *testing.T) {
svc := NewOutputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><ListMember><member>abc</member><member>123</member></ListMember><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService3TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "abc", *out.ListMember[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "123", *out.ListMember[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) {
svc := NewOutputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><ListMember><item>abc</item><item>123</item></ListMember><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService4TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "abc", *out.ListMember[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "123", *out.ListMember[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) {
svc := NewOutputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><ListMember>abc</ListMember><ListMember>123</ListMember><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService5TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "abc", *out.ListMember[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "123", *out.ListMember[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) {
svc := NewOutputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Map><entry><key>qux</key><value><foo>bar</foo></value></entry><entry><key>baz</key><value><foo>bam</foo></value></entry></Map><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService6TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "bam", *out.Map["baz"].Foo; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.Map["qux"].Foo; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) {
svc := NewOutputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Map><key>qux</key><value>bar</value></Map><Map><key>baz</key><value>bam</value></Map><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService7TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "bam", *out.Map["baz"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.Map["qux"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) {
svc := NewOutputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Map><foo>qux</foo><bar>bar</bar></Map><Map><foo>baz</foo><bar>bam</bar></Map><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService8TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "bam", *out.Map["baz"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.Map["qux"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService9ProtocolTestEmptyStringCase1(t *testing.T) {
svc := NewOutputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Foo/><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService9TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "", *out.Foo; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService10ProtocolTestTimestampMembersCase1(t *testing.T) {
svc := NewOutputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><StructMember><foo>2014-04-29T18:30:38Z</foo><bar>1398796238</bar></StructMember><TimeArg>2014-04-29T18:30:38Z</TimeArg><TimeCustom>Tue, 29 Apr 2014 18:30:38 GMT</TimeCustom><TimeFormat>1398796238</TimeFormat><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService10TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.StructMember.Bar.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.StructMember.Foo.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeArg.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeCustom.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeFormat.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService11ProtocolTestEnumOutputCase1(t *testing.T) {
svc := NewOutputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><FooEnum>foo</FooEnum><ListEnums><member>foo</member><member>bar</member></ListEnums></OperationNameResponse>"))
req, out := svc.OutputService11TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "foo", *out.FooEnum; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "foo", *out.ListEnums[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.ListEnums[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
| 2,149 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
)
type decodedMessage struct {
rawMessage
Headers decodedHeaders `json:"headers"`
}
type jsonMessage struct {
Length json.Number `json:"total_length"`
HeadersLen json.Number `json:"headers_length"`
PreludeCRC json.Number `json:"prelude_crc"`
Headers decodedHeaders `json:"headers"`
Payload []byte `json:"payload"`
CRC json.Number `json:"message_crc"`
}
func (d *decodedMessage) UnmarshalJSON(b []byte) (err error) {
var jsonMsg jsonMessage
if err = json.Unmarshal(b, &jsonMsg); err != nil {
return err
}
d.Length, err = numAsUint32(jsonMsg.Length)
if err != nil {
return err
}
d.HeadersLen, err = numAsUint32(jsonMsg.HeadersLen)
if err != nil {
return err
}
d.PreludeCRC, err = numAsUint32(jsonMsg.PreludeCRC)
if err != nil {
return err
}
d.Headers = jsonMsg.Headers
d.Payload = jsonMsg.Payload
d.CRC, err = numAsUint32(jsonMsg.CRC)
if err != nil {
return err
}
return nil
}
func (d *decodedMessage) MarshalJSON() ([]byte, error) {
jsonMsg := jsonMessage{
Length: json.Number(strconv.Itoa(int(d.Length))),
HeadersLen: json.Number(strconv.Itoa(int(d.HeadersLen))),
PreludeCRC: json.Number(strconv.Itoa(int(d.PreludeCRC))),
Headers: d.Headers,
Payload: d.Payload,
CRC: json.Number(strconv.Itoa(int(d.CRC))),
}
return json.Marshal(jsonMsg)
}
func numAsUint32(n json.Number) (uint32, error) {
v, err := n.Int64()
if err != nil {
return 0, fmt.Errorf("failed to get int64 json number, %v", err)
}
return uint32(v), nil
}
func (d decodedMessage) Message() Message {
return Message{
Headers: Headers(d.Headers),
Payload: d.Payload,
}
}
type decodedHeaders Headers
func (hs *decodedHeaders) UnmarshalJSON(b []byte) error {
var jsonHeaders []struct {
Name string `json:"name"`
Type valueType `json:"type"`
Value interface{} `json:"value"`
}
decoder := json.NewDecoder(bytes.NewReader(b))
decoder.UseNumber()
if err := decoder.Decode(&jsonHeaders); err != nil {
return err
}
var headers Headers
for _, h := range jsonHeaders {
value, err := valueFromType(h.Type, h.Value)
if err != nil {
return err
}
headers.Set(h.Name, value)
}
*hs = decodedHeaders(headers)
return nil
}
func valueFromType(typ valueType, val interface{}) (Value, error) {
switch typ {
case trueValueType:
return BoolValue(true), nil
case falseValueType:
return BoolValue(false), nil
case int8ValueType:
v, err := val.(json.Number).Int64()
return Int8Value(int8(v)), err
case int16ValueType:
v, err := val.(json.Number).Int64()
return Int16Value(int16(v)), err
case int32ValueType:
v, err := val.(json.Number).Int64()
return Int32Value(int32(v)), err
case int64ValueType:
v, err := val.(json.Number).Int64()
return Int64Value(v), err
case bytesValueType:
v, err := base64.StdEncoding.DecodeString(val.(string))
return BytesValue(v), err
case stringValueType:
v, err := base64.StdEncoding.DecodeString(val.(string))
return StringValue(string(v)), err
case timestampValueType:
v, err := val.(json.Number).Int64()
return TimestampValue(timeFromEpochMilli(v)), err
case uuidValueType:
v, err := base64.StdEncoding.DecodeString(val.(string))
var tv UUIDValue
copy(tv[:], v)
return tv, err
default:
panic(fmt.Sprintf("unknown type, %s, %T", typ.String(), val))
}
}
| 145 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"hash/crc32"
"io"
"github.com/aws/aws-sdk-go/aws"
)
// Decoder provides decoding of an Event Stream messages.
type Decoder struct {
r io.Reader
logger aws.Logger
}
// NewDecoder initializes and returns a Decoder for decoding event
// stream messages from the reader provided.
func NewDecoder(r io.Reader, opts ...func(*Decoder)) *Decoder {
d := &Decoder{
r: r,
}
for _, opt := range opts {
opt(d)
}
return d
}
// DecodeWithLogger adds a logger to be used by the decoder when decoding
// stream events.
func DecodeWithLogger(logger aws.Logger) func(*Decoder) {
return func(d *Decoder) {
d.logger = logger
}
}
// Decode attempts to decode a single message from the event stream reader.
// Will return the event stream message, or error if Decode fails to read
// the message from the stream.
func (d *Decoder) Decode(payloadBuf []byte) (m Message, err error) {
reader := d.r
if d.logger != nil {
debugMsgBuf := bytes.NewBuffer(nil)
reader = io.TeeReader(reader, debugMsgBuf)
defer func() {
logMessageDecode(d.logger, debugMsgBuf, m, err)
}()
}
m, err = Decode(reader, payloadBuf)
return m, err
}
// Decode attempts to decode a single message from the event stream reader.
// Will return the event stream message, or error if Decode fails to read
// the message from the reader.
func Decode(reader io.Reader, payloadBuf []byte) (m Message, err error) {
crc := crc32.New(crc32IEEETable)
hashReader := io.TeeReader(reader, crc)
prelude, err := decodePrelude(hashReader, crc)
if err != nil {
return Message{}, err
}
if prelude.HeadersLen > 0 {
lr := io.LimitReader(hashReader, int64(prelude.HeadersLen))
m.Headers, err = decodeHeaders(lr)
if err != nil {
return Message{}, err
}
}
if payloadLen := prelude.PayloadLen(); payloadLen > 0 {
buf, err := decodePayload(payloadBuf, io.LimitReader(hashReader, int64(payloadLen)))
if err != nil {
return Message{}, err
}
m.Payload = buf
}
msgCRC := crc.Sum32()
if err := validateCRC(reader, msgCRC); err != nil {
return Message{}, err
}
return m, nil
}
func logMessageDecode(logger aws.Logger, msgBuf *bytes.Buffer, msg Message, decodeErr error) {
w := bytes.NewBuffer(nil)
defer func() { logger.Log(w.String()) }()
fmt.Fprintf(w, "Raw message:\n%s\n",
hex.Dump(msgBuf.Bytes()))
if decodeErr != nil {
fmt.Fprintf(w, "Decode error: %v\n", decodeErr)
return
}
rawMsg, err := msg.rawMessage()
if err != nil {
fmt.Fprintf(w, "failed to create raw message, %v\n", err)
return
}
decodedMsg := decodedMessage{
rawMessage: rawMsg,
Headers: decodedHeaders(msg.Headers),
}
fmt.Fprintf(w, "Decoded message:\n")
encoder := json.NewEncoder(w)
if err := encoder.Encode(decodedMsg); err != nil {
fmt.Fprintf(w, "failed to generate decoded message, %v\n", err)
}
}
func decodePrelude(r io.Reader, crc hash.Hash32) (messagePrelude, error) {
var p messagePrelude
var err error
p.Length, err = decodeUint32(r)
if err != nil {
return messagePrelude{}, err
}
p.HeadersLen, err = decodeUint32(r)
if err != nil {
return messagePrelude{}, err
}
if err := p.ValidateLens(); err != nil {
return messagePrelude{}, err
}
preludeCRC := crc.Sum32()
if err := validateCRC(r, preludeCRC); err != nil {
return messagePrelude{}, err
}
p.PreludeCRC = preludeCRC
return p, nil
}
func decodePayload(buf []byte, r io.Reader) ([]byte, error) {
w := bytes.NewBuffer(buf[0:0])
_, err := io.Copy(w, r)
return w.Bytes(), err
}
func decodeUint8(r io.Reader) (uint8, error) {
type byteReader interface {
ReadByte() (byte, error)
}
if br, ok := r.(byteReader); ok {
v, err := br.ReadByte()
return uint8(v), err
}
var b [1]byte
_, err := io.ReadFull(r, b[:])
return uint8(b[0]), err
}
func decodeUint16(r io.Reader) (uint16, error) {
var b [2]byte
bs := b[:]
_, err := io.ReadFull(r, bs)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint16(bs), nil
}
func decodeUint32(r io.Reader) (uint32, error) {
var b [4]byte
bs := b[:]
_, err := io.ReadFull(r, bs)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(bs), nil
}
func decodeUint64(r io.Reader) (uint64, error) {
var b [8]byte
bs := b[:]
_, err := io.ReadFull(r, bs)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint64(bs), nil
}
func validateCRC(r io.Reader, expect uint32) error {
msgCRC, err := decodeUint32(r)
if err != nil {
return err
}
if msgCRC != expect {
return ChecksumError{}
}
return nil
}
| 217 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/hex"
"io/ioutil"
"os"
"reflect"
"testing"
)
func TestWriteEncodedFromDecoded(t *testing.T) {
cases, err := readPositiveTests("testdata")
if err != nil {
t.Fatalf("failed to load positive tests, %v", err)
}
for _, c := range cases {
f, err := ioutil.TempFile(os.TempDir(), "encoded_positive_"+c.Name)
if err != nil {
t.Fatalf("failed to open %q, %v", c.Name, err)
}
encoder := NewEncoder(f)
msg := c.Decoded.Message()
if err := encoder.Encode(msg); err != nil {
t.Errorf("failed to encode %q, %v", c.Name, err)
}
if err = f.Close(); err != nil {
t.Errorf("expected %v, got %v", "no error", err)
}
if err = os.Remove(f.Name()); err != nil {
t.Errorf("expected %v, got %v", "no error", err)
}
}
}
func TestDecoder_Decode(t *testing.T) {
cases, err := readPositiveTests("testdata")
if err != nil {
t.Fatalf("failed to load positive tests, %v", err)
}
for _, c := range cases {
decoder := NewDecoder(bytes.NewBuffer(c.Encoded))
msg, err := decoder.Decode(nil)
if err != nil {
t.Fatalf("%s, expect no decode error, got %v", c.Name, err)
}
raw, err := msg.rawMessage() // rawMessage will fail if payload read CRC fails
if err != nil {
t.Fatalf("%s, failed to get raw decoded message %v", c.Name, err)
}
if e, a := c.Decoded.Length, raw.Length; e != a {
t.Errorf("%s, expect %v length, got %v", c.Name, e, a)
}
if e, a := c.Decoded.HeadersLen, raw.HeadersLen; e != a {
t.Errorf("%s, expect %v HeadersLen, got %v", c.Name, e, a)
}
if e, a := c.Decoded.PreludeCRC, raw.PreludeCRC; e != a {
t.Errorf("%s, expect %v PreludeCRC, got %v", c.Name, e, a)
}
if e, a := Headers(c.Decoded.Headers), msg.Headers; !reflect.DeepEqual(e, a) {
t.Errorf("%s, expect %v headers, got %v", c.Name, e, a)
}
if e, a := c.Decoded.Payload, raw.Payload; !bytes.Equal(e, a) {
t.Errorf("%s, expect %v payload, got %v", c.Name, e, a)
}
if e, a := c.Decoded.CRC, raw.CRC; e != a {
t.Errorf("%s, expect %v CRC, got %v", c.Name, e, a)
}
}
}
func TestDecoder_Decode_Negative(t *testing.T) {
cases, err := readNegativeTests("testdata")
if err != nil {
t.Fatalf("failed to load negative tests, %v", err)
}
for _, c := range cases {
decoder := NewDecoder(bytes.NewBuffer(c.Encoded))
msg, err := decoder.Decode(nil)
if err == nil {
rawMsg, rawMsgErr := msg.rawMessage()
t.Fatalf("%s, expect error, got none, %s,\n%s\n%#v, %v\n", c.Name,
c.Err, hex.Dump(c.Encoded), rawMsg, rawMsgErr)
}
}
}
var testEncodedMsg = []byte{0, 0, 0, 61, 0, 0, 0, 32, 7, 253, 131, 150, 12, 99, 111, 110, 116, 101, 110, 116, 45, 116, 121, 112, 101, 7, 0, 16, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 123, 39, 102, 111, 111, 39, 58, 39, 98, 97, 114, 39, 125, 141, 156, 8, 177}
func TestDecoder_DecodeMultipleMessages(t *testing.T) {
const (
expectMsgCount = 10
expectPayloadLen = 13
)
r := bytes.NewBuffer(nil)
for i := 0; i < expectMsgCount; i++ {
r.Write(testEncodedMsg)
}
decoder := NewDecoder(r)
var err error
var msg Message
var count int
for {
msg, err = decoder.Decode(nil)
if err != nil {
break
}
count++
if e, a := expectPayloadLen, len(msg.Payload); e != a {
t.Errorf("expect %v payload len, got %v", e, a)
}
if e, a := []byte(`{'foo':'bar'}`), msg.Payload; !bytes.Equal(e, a) {
t.Errorf("expect %v payload, got %v", e, a)
}
}
type causer interface {
Cause() error
}
if err != nil && count != expectMsgCount {
t.Fatalf("expect, no error, got %v", err)
}
if e, a := expectMsgCount, count; e != a {
t.Errorf("expect %v messages read, got %v", e, a)
}
}
func BenchmarkDecode(b *testing.B) {
r := bytes.NewReader(testEncodedMsg)
decoder := NewDecoder(r)
payloadBuf := make([]byte, 0, 5*1024)
b.ResetTimer()
for i := 0; i < b.N; i++ {
msg, err := decoder.Decode(payloadBuf)
if err != nil {
b.Fatal(err)
}
// Release the payload buffer
payloadBuf = msg.Payload[0:0]
r.Seek(0, 0)
}
}
func BenchmarkDecode_NoPayloadBuf(b *testing.B) {
r := bytes.NewReader(testEncodedMsg)
decoder := NewDecoder(r)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := decoder.Decode(nil)
if err != nil {
b.Fatal(err)
}
r.Seek(0, 0)
}
}
| 175 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"hash/crc32"
"io"
"github.com/aws/aws-sdk-go/aws"
)
// Encoder provides EventStream message encoding.
type Encoder struct {
w io.Writer
logger aws.Logger
headersBuf *bytes.Buffer
}
// NewEncoder initializes and returns an Encoder to encode Event Stream
// messages to an io.Writer.
func NewEncoder(w io.Writer, opts ...func(*Encoder)) *Encoder {
e := &Encoder{
w: w,
headersBuf: bytes.NewBuffer(nil),
}
for _, opt := range opts {
opt(e)
}
return e
}
// EncodeWithLogger adds a logger to be used by the encode when decoding
// stream events.
func EncodeWithLogger(logger aws.Logger) func(*Encoder) {
return func(d *Encoder) {
d.logger = logger
}
}
// Encode encodes a single EventStream message to the io.Writer the Encoder
// was created with. An error is returned if writing the message fails.
func (e *Encoder) Encode(msg Message) (err error) {
e.headersBuf.Reset()
writer := e.w
if e.logger != nil {
encodeMsgBuf := bytes.NewBuffer(nil)
writer = io.MultiWriter(writer, encodeMsgBuf)
defer func() {
logMessageEncode(e.logger, encodeMsgBuf, msg, err)
}()
}
if err = EncodeHeaders(e.headersBuf, msg.Headers); err != nil {
return err
}
crc := crc32.New(crc32IEEETable)
hashWriter := io.MultiWriter(writer, crc)
headersLen := uint32(e.headersBuf.Len())
payloadLen := uint32(len(msg.Payload))
if err = encodePrelude(hashWriter, crc, headersLen, payloadLen); err != nil {
return err
}
if headersLen > 0 {
if _, err = io.Copy(hashWriter, e.headersBuf); err != nil {
return err
}
}
if payloadLen > 0 {
if _, err = hashWriter.Write(msg.Payload); err != nil {
return err
}
}
msgCRC := crc.Sum32()
return binary.Write(writer, binary.BigEndian, msgCRC)
}
func logMessageEncode(logger aws.Logger, msgBuf *bytes.Buffer, msg Message, encodeErr error) {
w := bytes.NewBuffer(nil)
defer func() { logger.Log(w.String()) }()
fmt.Fprintf(w, "Message to encode:\n")
encoder := json.NewEncoder(w)
if err := encoder.Encode(msg); err != nil {
fmt.Fprintf(w, "Failed to get encoded message, %v\n", err)
}
if encodeErr != nil {
fmt.Fprintf(w, "Encode error: %v\n", encodeErr)
return
}
fmt.Fprintf(w, "Raw message:\n%s\n", hex.Dump(msgBuf.Bytes()))
}
func encodePrelude(w io.Writer, crc hash.Hash32, headersLen, payloadLen uint32) error {
p := messagePrelude{
Length: minMsgLen + headersLen + payloadLen,
HeadersLen: headersLen,
}
if err := p.ValidateLens(); err != nil {
return err
}
err := binaryWriteFields(w, binary.BigEndian,
p.Length,
p.HeadersLen,
)
if err != nil {
return err
}
p.PreludeCRC = crc.Sum32()
err = binary.Write(w, binary.BigEndian, p.PreludeCRC)
if err != nil {
return err
}
return nil
}
// EncodeHeaders writes the header values to the writer encoded in the event
// stream format. Returns an error if a header fails to encode.
func EncodeHeaders(w io.Writer, headers Headers) error {
for _, h := range headers {
hn := headerName{
Len: uint8(len(h.Name)),
}
copy(hn.Name[:hn.Len], h.Name)
if err := hn.encode(w); err != nil {
return err
}
if err := h.Value.encode(w); err != nil {
return err
}
}
return nil
}
func binaryWriteFields(w io.Writer, order binary.ByteOrder, vs ...interface{}) error {
for _, v := range vs {
if err := binary.Write(w, order, v); err != nil {
return err
}
}
return nil
}
| 163 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/hex"
"reflect"
"testing"
)
func TestEncoder_Encode(t *testing.T) {
cases, err := readPositiveTests("testdata")
if err != nil {
t.Fatalf("failed to load positive tests, %v", err)
}
for _, c := range cases {
var w bytes.Buffer
encoder := NewEncoder(&w)
err = encoder.Encode(c.Decoded.Message())
if err != nil {
t.Fatalf("%s, failed to encode message, %v", c.Name, err)
}
if e, a := c.Encoded, w.Bytes(); !reflect.DeepEqual(e, a) {
t.Errorf("%s, expect:\n%v\nactual:\n%v\n", c.Name,
hex.Dump(e), hex.Dump(a))
}
}
}
func BenchmarkEncode(b *testing.B) {
var w bytes.Buffer
encoder := NewEncoder(&w)
msg := Message{
Headers: Headers{
{Name: "event-id", Value: Int16Value(123)},
},
Payload: []byte(`{"abc":123}`),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
err := encoder.Encode(msg)
if err != nil {
b.Fatal(err)
}
}
}
| 51 |
session-manager-plugin | aws | Go | package eventstream
import "fmt"
// LengthError provides the error for items being larger than a maximum length.
type LengthError struct {
Part string
Want int
Have int
Value interface{}
}
func (e LengthError) Error() string {
return fmt.Sprintf("%s length invalid, %d/%d, %v",
e.Part, e.Want, e.Have, e.Value)
}
// ChecksumError provides the error for message checksum invalidation errors.
type ChecksumError struct{}
func (e ChecksumError) Error() string {
return "message checksum mismatch"
}
| 24 |
session-manager-plugin | aws | Go | package eventstream
import (
"encoding/binary"
"fmt"
"io"
)
// Headers are a collection of EventStream header values.
type Headers []Header
// Header is a single EventStream Key Value header pair.
type Header struct {
Name string
Value Value
}
// Set associates the name with a value. If the header name already exists in
// the Headers the value will be replaced with the new one.
func (hs *Headers) Set(name string, value Value) {
var i int
for ; i < len(*hs); i++ {
if (*hs)[i].Name == name {
(*hs)[i].Value = value
return
}
}
*hs = append(*hs, Header{
Name: name, Value: value,
})
}
// Get returns the Value associated with the header. Nil is returned if the
// value does not exist.
func (hs Headers) Get(name string) Value {
for i := 0; i < len(hs); i++ {
if h := hs[i]; h.Name == name {
return h.Value
}
}
return nil
}
// Del deletes the value in the Headers if it exists.
func (hs *Headers) Del(name string) {
for i := 0; i < len(*hs); i++ {
if (*hs)[i].Name == name {
copy((*hs)[i:], (*hs)[i+1:])
(*hs) = (*hs)[:len(*hs)-1]
}
}
}
// Clone returns a deep copy of the headers
func (hs Headers) Clone() Headers {
o := make(Headers, 0, len(hs))
for _, h := range hs {
o.Set(h.Name, h.Value)
}
return o
}
func decodeHeaders(r io.Reader) (Headers, error) {
hs := Headers{}
for {
name, err := decodeHeaderName(r)
if err != nil {
if err == io.EOF {
// EOF while getting header name means no more headers
break
}
return nil, err
}
value, err := decodeHeaderValue(r)
if err != nil {
return nil, err
}
hs.Set(name, value)
}
return hs, nil
}
func decodeHeaderName(r io.Reader) (string, error) {
var n headerName
var err error
n.Len, err = decodeUint8(r)
if err != nil {
return "", err
}
name := n.Name[:n.Len]
if _, err := io.ReadFull(r, name); err != nil {
return "", err
}
return string(name), nil
}
func decodeHeaderValue(r io.Reader) (Value, error) {
var raw rawValue
typ, err := decodeUint8(r)
if err != nil {
return nil, err
}
raw.Type = valueType(typ)
var v Value
switch raw.Type {
case trueValueType:
v = BoolValue(true)
case falseValueType:
v = BoolValue(false)
case int8ValueType:
var tv Int8Value
err = tv.decode(r)
v = tv
case int16ValueType:
var tv Int16Value
err = tv.decode(r)
v = tv
case int32ValueType:
var tv Int32Value
err = tv.decode(r)
v = tv
case int64ValueType:
var tv Int64Value
err = tv.decode(r)
v = tv
case bytesValueType:
var tv BytesValue
err = tv.decode(r)
v = tv
case stringValueType:
var tv StringValue
err = tv.decode(r)
v = tv
case timestampValueType:
var tv TimestampValue
err = tv.decode(r)
v = tv
case uuidValueType:
var tv UUIDValue
err = tv.decode(r)
v = tv
default:
panic(fmt.Sprintf("unknown value type %d", raw.Type))
}
// Error could be EOF, let caller deal with it
return v, err
}
const maxHeaderNameLen = 255
type headerName struct {
Len uint8
Name [maxHeaderNameLen]byte
}
func (v headerName) encode(w io.Writer) error {
if err := binary.Write(w, binary.BigEndian, v.Len); err != nil {
return err
}
_, err := w.Write(v.Name[:v.Len])
return err
}
| 176 |
session-manager-plugin | aws | Go | package eventstream
import (
"reflect"
"testing"
"time"
)
func TestHeaders_Set(t *testing.T) {
expect := Headers{
{Name: "ABC", Value: StringValue("123")},
{Name: "EFG", Value: TimestampValue(time.Time{})},
}
var actual Headers
actual.Set("ABC", Int32Value(123))
actual.Set("ABC", StringValue("123")) // replace case
actual.Set("EFG", TimestampValue(time.Time{}))
if e, a := expect, actual; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v headers, got %v", e, a)
}
}
func TestHeaders_Get(t *testing.T) {
headers := Headers{
{Name: "ABC", Value: StringValue("123")},
{Name: "EFG", Value: TimestampValue(time.Time{})},
}
cases := []struct {
Name string
Value Value
}{
{Name: "ABC", Value: StringValue("123")},
{Name: "EFG", Value: TimestampValue(time.Time{})},
{Name: "NotFound"},
}
for i, c := range cases {
actual := headers.Get(c.Name)
if e, a := c.Value, actual; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %v value, got %v", i, e, a)
}
}
}
func TestHeaders_Del(t *testing.T) {
headers := Headers{
{Name: "ABC", Value: StringValue("123")},
{Name: "EFG", Value: TimestampValue(time.Time{})},
{Name: "HIJ", Value: StringValue("123")},
{Name: "KML", Value: TimestampValue(time.Time{})},
}
expectAfterDel := Headers{
{Name: "EFG", Value: TimestampValue(time.Time{})},
}
headers.Del("HIJ")
headers.Del("ABC")
headers.Del("KML")
if e, a := expectAfterDel, headers; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v headers, got %v", e, a)
}
}
| 67 |
session-manager-plugin | aws | Go | package eventstream
import (
"encoding/base64"
"encoding/binary"
"fmt"
"io"
"strconv"
"time"
)
const maxHeaderValueLen = 1<<15 - 1 // 2^15-1 or 32KB - 1
// valueType is the EventStream header value type.
type valueType uint8
// Header value types
const (
trueValueType valueType = iota
falseValueType
int8ValueType // Byte
int16ValueType // Short
int32ValueType // Integer
int64ValueType // Long
bytesValueType
stringValueType
timestampValueType
uuidValueType
)
func (t valueType) String() string {
switch t {
case trueValueType:
return "bool"
case falseValueType:
return "bool"
case int8ValueType:
return "int8"
case int16ValueType:
return "int16"
case int32ValueType:
return "int32"
case int64ValueType:
return "int64"
case bytesValueType:
return "byte_array"
case stringValueType:
return "string"
case timestampValueType:
return "timestamp"
case uuidValueType:
return "uuid"
default:
return fmt.Sprintf("unknown value type %d", uint8(t))
}
}
type rawValue struct {
Type valueType
Len uint16 // Only set for variable length slices
Value []byte // byte representation of value, BigEndian encoding.
}
func (r rawValue) encodeScalar(w io.Writer, v interface{}) error {
return binaryWriteFields(w, binary.BigEndian,
r.Type,
v,
)
}
func (r rawValue) encodeFixedSlice(w io.Writer, v []byte) error {
binary.Write(w, binary.BigEndian, r.Type)
_, err := w.Write(v)
return err
}
func (r rawValue) encodeBytes(w io.Writer, v []byte) error {
if len(v) > maxHeaderValueLen {
return LengthError{
Part: "header value",
Want: maxHeaderValueLen, Have: len(v),
Value: v,
}
}
r.Len = uint16(len(v))
err := binaryWriteFields(w, binary.BigEndian,
r.Type,
r.Len,
)
if err != nil {
return err
}
_, err = w.Write(v)
return err
}
func (r rawValue) encodeString(w io.Writer, v string) error {
if len(v) > maxHeaderValueLen {
return LengthError{
Part: "header value",
Want: maxHeaderValueLen, Have: len(v),
Value: v,
}
}
r.Len = uint16(len(v))
type stringWriter interface {
WriteString(string) (int, error)
}
err := binaryWriteFields(w, binary.BigEndian,
r.Type,
r.Len,
)
if err != nil {
return err
}
if sw, ok := w.(stringWriter); ok {
_, err = sw.WriteString(v)
} else {
_, err = w.Write([]byte(v))
}
return err
}
func decodeFixedBytesValue(r io.Reader, buf []byte) error {
_, err := io.ReadFull(r, buf)
return err
}
func decodeBytesValue(r io.Reader) ([]byte, error) {
var raw rawValue
var err error
raw.Len, err = decodeUint16(r)
if err != nil {
return nil, err
}
buf := make([]byte, raw.Len)
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, err
}
return buf, nil
}
func decodeStringValue(r io.Reader) (string, error) {
v, err := decodeBytesValue(r)
return string(v), err
}
// Value represents the abstract header value.
type Value interface {
Get() interface{}
String() string
valueType() valueType
encode(io.Writer) error
}
// An BoolValue provides eventstream encoding, and representation
// of a Go bool value.
type BoolValue bool
// Get returns the underlying type
func (v BoolValue) Get() interface{} {
return bool(v)
}
// valueType returns the EventStream header value type value.
func (v BoolValue) valueType() valueType {
if v {
return trueValueType
}
return falseValueType
}
func (v BoolValue) String() string {
return strconv.FormatBool(bool(v))
}
// encode encodes the BoolValue into an eventstream binary value
// representation.
func (v BoolValue) encode(w io.Writer) error {
return binary.Write(w, binary.BigEndian, v.valueType())
}
// An Int8Value provides eventstream encoding, and representation of a Go
// int8 value.
type Int8Value int8
// Get returns the underlying value.
func (v Int8Value) Get() interface{} {
return int8(v)
}
// valueType returns the EventStream header value type value.
func (Int8Value) valueType() valueType {
return int8ValueType
}
func (v Int8Value) String() string {
return fmt.Sprintf("0x%02x", int8(v))
}
// encode encodes the Int8Value into an eventstream binary value
// representation.
func (v Int8Value) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeScalar(w, v)
}
func (v *Int8Value) decode(r io.Reader) error {
n, err := decodeUint8(r)
if err != nil {
return err
}
*v = Int8Value(n)
return nil
}
// An Int16Value provides eventstream encoding, and representation of a Go
// int16 value.
type Int16Value int16
// Get returns the underlying value.
func (v Int16Value) Get() interface{} {
return int16(v)
}
// valueType returns the EventStream header value type value.
func (Int16Value) valueType() valueType {
return int16ValueType
}
func (v Int16Value) String() string {
return fmt.Sprintf("0x%04x", int16(v))
}
// encode encodes the Int16Value into an eventstream binary value
// representation.
func (v Int16Value) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeScalar(w, v)
}
func (v *Int16Value) decode(r io.Reader) error {
n, err := decodeUint16(r)
if err != nil {
return err
}
*v = Int16Value(n)
return nil
}
// An Int32Value provides eventstream encoding, and representation of a Go
// int32 value.
type Int32Value int32
// Get returns the underlying value.
func (v Int32Value) Get() interface{} {
return int32(v)
}
// valueType returns the EventStream header value type value.
func (Int32Value) valueType() valueType {
return int32ValueType
}
func (v Int32Value) String() string {
return fmt.Sprintf("0x%08x", int32(v))
}
// encode encodes the Int32Value into an eventstream binary value
// representation.
func (v Int32Value) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeScalar(w, v)
}
func (v *Int32Value) decode(r io.Reader) error {
n, err := decodeUint32(r)
if err != nil {
return err
}
*v = Int32Value(n)
return nil
}
// An Int64Value provides eventstream encoding, and representation of a Go
// int64 value.
type Int64Value int64
// Get returns the underlying value.
func (v Int64Value) Get() interface{} {
return int64(v)
}
// valueType returns the EventStream header value type value.
func (Int64Value) valueType() valueType {
return int64ValueType
}
func (v Int64Value) String() string {
return fmt.Sprintf("0x%016x", int64(v))
}
// encode encodes the Int64Value into an eventstream binary value
// representation.
func (v Int64Value) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeScalar(w, v)
}
func (v *Int64Value) decode(r io.Reader) error {
n, err := decodeUint64(r)
if err != nil {
return err
}
*v = Int64Value(n)
return nil
}
// An BytesValue provides eventstream encoding, and representation of a Go
// byte slice.
type BytesValue []byte
// Get returns the underlying value.
func (v BytesValue) Get() interface{} {
return []byte(v)
}
// valueType returns the EventStream header value type value.
func (BytesValue) valueType() valueType {
return bytesValueType
}
func (v BytesValue) String() string {
return base64.StdEncoding.EncodeToString([]byte(v))
}
// encode encodes the BytesValue into an eventstream binary value
// representation.
func (v BytesValue) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeBytes(w, []byte(v))
}
func (v *BytesValue) decode(r io.Reader) error {
buf, err := decodeBytesValue(r)
if err != nil {
return err
}
*v = BytesValue(buf)
return nil
}
// An StringValue provides eventstream encoding, and representation of a Go
// string.
type StringValue string
// Get returns the underlying value.
func (v StringValue) Get() interface{} {
return string(v)
}
// valueType returns the EventStream header value type value.
func (StringValue) valueType() valueType {
return stringValueType
}
func (v StringValue) String() string {
return string(v)
}
// encode encodes the StringValue into an eventstream binary value
// representation.
func (v StringValue) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeString(w, string(v))
}
func (v *StringValue) decode(r io.Reader) error {
s, err := decodeStringValue(r)
if err != nil {
return err
}
*v = StringValue(s)
return nil
}
// An TimestampValue provides eventstream encoding, and representation of a Go
// timestamp.
type TimestampValue time.Time
// Get returns the underlying value.
func (v TimestampValue) Get() interface{} {
return time.Time(v)
}
// valueType returns the EventStream header value type value.
func (TimestampValue) valueType() valueType {
return timestampValueType
}
func (v TimestampValue) epochMilli() int64 {
nano := time.Time(v).UnixNano()
msec := nano / int64(time.Millisecond)
return msec
}
func (v TimestampValue) String() string {
msec := v.epochMilli()
return strconv.FormatInt(msec, 10)
}
// encode encodes the TimestampValue into an eventstream binary value
// representation.
func (v TimestampValue) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
msec := v.epochMilli()
return raw.encodeScalar(w, msec)
}
func (v *TimestampValue) decode(r io.Reader) error {
n, err := decodeUint64(r)
if err != nil {
return err
}
*v = TimestampValue(timeFromEpochMilli(int64(n)))
return nil
}
// MarshalJSON implements the json.Marshaler interface
func (v TimestampValue) MarshalJSON() ([]byte, error) {
return []byte(v.String()), nil
}
func timeFromEpochMilli(t int64) time.Time {
secs := t / 1e3
msec := t % 1e3
return time.Unix(secs, msec*int64(time.Millisecond)).UTC()
}
// An UUIDValue provides eventstream encoding, and representation of a UUID
// value.
type UUIDValue [16]byte
// Get returns the underlying value.
func (v UUIDValue) Get() interface{} {
return v[:]
}
// valueType returns the EventStream header value type value.
func (UUIDValue) valueType() valueType {
return uuidValueType
}
func (v UUIDValue) String() string {
return fmt.Sprintf(`%X-%X-%X-%X-%X`, v[0:4], v[4:6], v[6:8], v[8:10], v[10:])
}
// encode encodes the UUIDValue into an eventstream binary value
// representation.
func (v UUIDValue) encode(w io.Writer) error {
raw := rawValue{
Type: v.valueType(),
}
return raw.encodeFixedSlice(w, v[:])
}
func (v *UUIDValue) decode(r io.Reader) error {
tv := (*v)[:]
return decodeFixedBytesValue(r, tv)
}
| 507 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/binary"
"io"
"reflect"
"testing"
"time"
)
func binWrite(v interface{}) []byte {
var w bytes.Buffer
binary.Write(&w, binary.BigEndian, v)
return w.Bytes()
}
var testValueEncodingCases = []struct {
Val Value
Expect []byte
Decode func(io.Reader) (Value, error)
}{
{
BoolValue(true),
[]byte{byte(trueValueType)},
nil,
},
{
BoolValue(false),
[]byte{byte(falseValueType)},
nil,
},
{
Int8Value(0x0f),
[]byte{byte(int8ValueType), 0x0f},
func(r io.Reader) (Value, error) {
var v Int8Value
err := v.decode(r)
return v, err
},
},
{
Int16Value(0x0f),
append([]byte{byte(int16ValueType)}, binWrite(int16(0x0f))...),
func(r io.Reader) (Value, error) {
var v Int16Value
err := v.decode(r)
return v, err
},
},
{
Int32Value(0x0f),
append([]byte{byte(int32ValueType)}, binWrite(int32(0x0f))...),
func(r io.Reader) (Value, error) {
var v Int32Value
err := v.decode(r)
return v, err
},
},
{
Int64Value(0x0f),
append([]byte{byte(int64ValueType)}, binWrite(int64(0x0f))...),
func(r io.Reader) (Value, error) {
var v Int64Value
err := v.decode(r)
return v, err
},
},
{
BytesValue([]byte{0, 1, 2, 3}),
[]byte{byte(bytesValueType), 0x00, 0x04, 0, 1, 2, 3},
func(r io.Reader) (Value, error) {
var v BytesValue
err := v.decode(r)
return v, err
},
},
{
StringValue("abc123"),
append([]byte{byte(stringValueType), 0, 6}, []byte("abc123")...),
func(r io.Reader) (Value, error) {
var v StringValue
err := v.decode(r)
return v, err
},
},
{
TimestampValue(
time.Date(2014, 04, 04, 0, 1, 0, 0, time.FixedZone("PDT", -7)),
),
append([]byte{byte(timestampValueType)}, binWrite(int64(1396569667000))...),
func(r io.Reader) (Value, error) {
var v TimestampValue
err := v.decode(r)
return v, err
},
},
{
UUIDValue(
[16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf},
),
[]byte{byte(uuidValueType), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf},
func(r io.Reader) (Value, error) {
var v UUIDValue
err := v.decode(r)
return v, err
},
},
}
func TestValue_MarshalValue(t *testing.T) {
for i, c := range testValueEncodingCases {
var w bytes.Buffer
if err := c.Val.encode(&w); err != nil {
t.Fatalf("%d, expect no error, got %v", i, err)
}
if e, a := c.Expect, w.Bytes(); !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
}
}
func TestHeader_DecodeValues(t *testing.T) {
for i, c := range testValueEncodingCases {
r := bytes.NewBuffer(c.Expect)
v, err := decodeHeaderValue(r)
if err != nil {
t.Fatalf("%d, expect no error, got %v", i, err)
}
switch tv := v.(type) {
case TimestampValue:
exp := time.Time(c.Val.(TimestampValue))
if e, a := exp, time.Time(tv); !e.Equal(a) {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
default:
if e, a := c.Val, v; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
}
}
}
func TestValue_Decode(t *testing.T) {
for i, c := range testValueEncodingCases {
if c.Decode == nil {
continue
}
r := bytes.NewBuffer(c.Expect)
r.ReadByte() // strip off Type field
v, err := c.Decode(r)
if err != nil {
t.Fatalf("%d, expect no error, got %v", i, err)
}
switch tv := v.(type) {
case TimestampValue:
exp := time.Time(c.Val.(TimestampValue))
if e, a := exp, time.Time(tv); !e.Equal(a) {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
default:
if e, a := c.Val, v; !reflect.DeepEqual(e, a) {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
}
}
}
func TestValue_String(t *testing.T) {
cases := []struct {
Val Value
Expect string
}{
{BoolValue(true), "true"},
{BoolValue(false), "false"},
{Int8Value(0x0f), "0x0f"},
{Int16Value(0x0f), "0x000f"},
{Int32Value(0x0f), "0x0000000f"},
{Int64Value(0x0f), "0x000000000000000f"},
{BytesValue([]byte{0, 1, 2, 3}), "AAECAw=="},
{StringValue("abc123"), "abc123"},
{TimestampValue(
time.Date(2014, 04, 04, 0, 1, 0, 0, time.FixedZone("PDT", -7)),
),
"1396569667000",
},
{UUIDValue([16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}),
"00010203-0405-0607-0809-0A0B0C0D0E0F",
},
}
for i, c := range cases {
if e, a := c.Expect, c.Val.String(); e != a {
t.Errorf("%d, expect %v, got %v", i, e, a)
}
}
}
| 204 |
session-manager-plugin | aws | Go | package eventstream
import (
"bytes"
"encoding/binary"
"hash/crc32"
)
const preludeLen = 8
const preludeCRCLen = 4
const msgCRCLen = 4
const minMsgLen = preludeLen + preludeCRCLen + msgCRCLen
const maxPayloadLen = 1024 * 1024 * 16 // 16MB
const maxHeadersLen = 1024 * 128 // 128KB
const maxMsgLen = minMsgLen + maxHeadersLen + maxPayloadLen
var crc32IEEETable = crc32.MakeTable(crc32.IEEE)
// A Message provides the eventstream message representation.
type Message struct {
Headers Headers
Payload []byte
}
func (m *Message) rawMessage() (rawMessage, error) {
var raw rawMessage
if len(m.Headers) > 0 {
var headers bytes.Buffer
if err := EncodeHeaders(&headers, m.Headers); err != nil {
return rawMessage{}, err
}
raw.Headers = headers.Bytes()
raw.HeadersLen = uint32(len(raw.Headers))
}
raw.Length = raw.HeadersLen + uint32(len(m.Payload)) + minMsgLen
hash := crc32.New(crc32IEEETable)
binaryWriteFields(hash, binary.BigEndian, raw.Length, raw.HeadersLen)
raw.PreludeCRC = hash.Sum32()
binaryWriteFields(hash, binary.BigEndian, raw.PreludeCRC)
if raw.HeadersLen > 0 {
hash.Write(raw.Headers)
}
// Read payload bytes and update hash for it as well.
if len(m.Payload) > 0 {
raw.Payload = m.Payload
hash.Write(raw.Payload)
}
raw.CRC = hash.Sum32()
return raw, nil
}
// Clone returns a deep copy of the message.
func (m Message) Clone() Message {
var payload []byte
if m.Payload != nil {
payload = make([]byte, len(m.Payload))
copy(payload, m.Payload)
}
return Message{
Headers: m.Headers.Clone(),
Payload: payload,
}
}
type messagePrelude struct {
Length uint32
HeadersLen uint32
PreludeCRC uint32
}
func (p messagePrelude) PayloadLen() uint32 {
return p.Length - p.HeadersLen - minMsgLen
}
func (p messagePrelude) ValidateLens() error {
if p.Length == 0 || p.Length > maxMsgLen {
return LengthError{
Part: "message prelude",
Want: maxMsgLen,
Have: int(p.Length),
}
}
if p.HeadersLen > maxHeadersLen {
return LengthError{
Part: "message headers",
Want: maxHeadersLen,
Have: int(p.HeadersLen),
}
}
if payloadLen := p.PayloadLen(); payloadLen > maxPayloadLen {
return LengthError{
Part: "message payload",
Want: maxPayloadLen,
Have: int(payloadLen),
}
}
return nil
}
type rawMessage struct {
messagePrelude
Headers []byte
Payload []byte
CRC uint32
}
| 118 |
session-manager-plugin | aws | Go | package eventstream
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"testing"
)
type testCase struct {
Name string
Encoded []byte
Decoded decodedMessage
}
type testErrorCase struct {
Name string
Encoded []byte
Err string
}
type rawTestCase struct {
Name string
Encoded, Decoded []byte
}
func readRawTestCases(root, class string) (map[string]rawTestCase, error) {
encoded, err := readTests(filepath.Join(root, "encoded", class))
if err != nil {
return nil, err
}
decoded, err := readTests(filepath.Join(root, "decoded", class))
if err != nil {
return nil, err
}
if len(encoded) == 0 {
return nil, fmt.Errorf("expect encoded cases, found none")
}
if len(encoded) != len(decoded) {
return nil, fmt.Errorf("encoded and decoded sets different")
}
rawCases := map[string]rawTestCase{}
for name, encData := range encoded {
decData, ok := decoded[name]
if !ok {
return nil, fmt.Errorf("encoded %q case not found in decoded set", name)
}
rawCases[name] = rawTestCase{
Name: name,
Encoded: encData,
Decoded: decData,
}
}
return rawCases, nil
}
func readNegativeTests(root string) ([]testErrorCase, error) {
rawCases, err := readRawTestCases(root, "negative")
if err != nil {
return nil, err
}
cases := make([]testErrorCase, 0, len(rawCases))
for name, rawCase := range rawCases {
cases = append(cases, testErrorCase{
Name: name,
Encoded: rawCase.Encoded,
Err: string(rawCase.Decoded),
})
}
return cases, nil
}
func readPositiveTests(root string) ([]testCase, error) {
rawCases, err := readRawTestCases(root, "positive")
if err != nil {
return nil, err
}
cases := make([]testCase, 0, len(rawCases))
for name, rawCase := range rawCases {
var dec decodedMessage
if err := json.Unmarshal(rawCase.Decoded, &dec); err != nil {
return nil, fmt.Errorf("failed to decode %q, %v", name, err)
}
cases = append(cases, testCase{
Name: name,
Encoded: rawCase.Encoded,
Decoded: dec,
})
}
return cases, nil
}
func readTests(root string) (map[string][]byte, error) {
items, err := ioutil.ReadDir(root)
if err != nil {
return nil, fmt.Errorf("failed to read test suite %q dirs, %v", root, err)
}
cases := map[string][]byte{}
for _, item := range items {
if item.IsDir() {
continue
}
filename := filepath.Join(root, item.Name())
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read test_data file %q, %v", filename, err)
}
cases[item.Name()] = data
}
return cases, nil
}
func compareLines(t *testing.T, a, b []byte) bool {
as := bufio.NewScanner(bytes.NewBuffer(a))
bs := bufio.NewScanner(bytes.NewBuffer(b))
var failed bool
for {
if ab, bb := as.Scan(), bs.Scan(); ab != bb {
t.Errorf("expect a & b to have same number of lines")
return false
} else if !ab {
break
}
if v1, v2 := as.Text(), bs.Text(); v1 != v2 {
t.Errorf("expect %q to be %q", v1, v2)
failed = true
}
}
return !failed
}
| 153 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"fmt"
"sync"
)
// InputWriterCloseErrorCode is used to denote an error occurred
// while closing the event stream input writer.
const InputWriterCloseErrorCode = "EventStreamInputWriterCloseError"
type messageError struct {
code string
msg string
}
func (e messageError) Code() string {
return e.code
}
func (e messageError) Message() string {
return e.msg
}
func (e messageError) Error() string {
return fmt.Sprintf("%s: %s", e.code, e.msg)
}
func (e messageError) OrigErr() error {
return nil
}
// OnceError wraps the behavior of recording an error
// once and signal on a channel when this has occurred.
// Signaling is done by closing of the channel.
//
// Type is safe for concurrent usage.
type OnceError struct {
mu sync.RWMutex
err error
ch chan struct{}
}
// NewOnceError return a new OnceError
func NewOnceError() *OnceError {
return &OnceError{
ch: make(chan struct{}, 1),
}
}
// Err acquires a read-lock and returns an
// error if one has been set.
func (e *OnceError) Err() error {
e.mu.RLock()
err := e.err
e.mu.RUnlock()
return err
}
// SetError acquires a write-lock and will set
// the underlying error value if one has not been set.
func (e *OnceError) SetError(err error) {
if err == nil {
return
}
e.mu.Lock()
if e.err == nil {
e.err = err
close(e.ch)
}
e.mu.Unlock()
}
// ErrorSet returns a channel that will be used to signal
// that an error has been set. This channel will be closed
// when the error value has been set for OnceError.
func (e *OnceError) ErrorSet() <-chan struct{} {
return e.ch
}
| 82 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"fmt"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
// Unmarshaler provides the interface for unmarshaling a EventStream
// message into a SDK type.
type Unmarshaler interface {
UnmarshalEvent(protocol.PayloadUnmarshaler, eventstream.Message) error
}
// EventReader provides reading from the EventStream of an reader.
type EventReader struct {
decoder *eventstream.Decoder
unmarshalerForEventType func(string) (Unmarshaler, error)
payloadUnmarshaler protocol.PayloadUnmarshaler
payloadBuf []byte
}
// NewEventReader returns a EventReader built from the reader and unmarshaler
// provided. Use ReadStream method to start reading from the EventStream.
func NewEventReader(
decoder *eventstream.Decoder,
payloadUnmarshaler protocol.PayloadUnmarshaler,
unmarshalerForEventType func(string) (Unmarshaler, error),
) *EventReader {
return &EventReader{
decoder: decoder,
payloadUnmarshaler: payloadUnmarshaler,
unmarshalerForEventType: unmarshalerForEventType,
payloadBuf: make([]byte, 10*1024),
}
}
// ReadEvent attempts to read a message from the EventStream and return the
// unmarshaled event value that the message is for.
//
// For EventStream API errors check if the returned error satisfies the
// awserr.Error interface to get the error's Code and Message components.
//
// EventUnmarshalers called with EventStream messages must take copies of the
// message's Payload. The payload will is reused between events read.
func (r *EventReader) ReadEvent() (event interface{}, err error) {
msg, err := r.decoder.Decode(r.payloadBuf)
if err != nil {
return nil, err
}
defer func() {
// Reclaim payload buffer for next message read.
r.payloadBuf = msg.Payload[0:0]
}()
typ, err := GetHeaderString(msg, MessageTypeHeader)
if err != nil {
return nil, err
}
switch typ {
case EventMessageType:
return r.unmarshalEventMessage(msg)
case ExceptionMessageType:
return nil, r.unmarshalEventException(msg)
case ErrorMessageType:
return nil, r.unmarshalErrorMessage(msg)
default:
return nil, &UnknownMessageTypeError{
Type: typ, Message: msg.Clone(),
}
}
}
// UnknownMessageTypeError provides an error when a message is received from
// the stream, but the reader is unable to determine what kind of message it is.
type UnknownMessageTypeError struct {
Type string
Message eventstream.Message
}
func (e *UnknownMessageTypeError) Error() string {
return "unknown eventstream message type, " + e.Type
}
func (r *EventReader) unmarshalEventMessage(
msg eventstream.Message,
) (event interface{}, err error) {
eventType, err := GetHeaderString(msg, EventTypeHeader)
if err != nil {
return nil, err
}
ev, err := r.unmarshalerForEventType(eventType)
if err != nil {
return nil, err
}
err = ev.UnmarshalEvent(r.payloadUnmarshaler, msg)
if err != nil {
return nil, err
}
return ev, nil
}
func (r *EventReader) unmarshalEventException(
msg eventstream.Message,
) (err error) {
eventType, err := GetHeaderString(msg, ExceptionTypeHeader)
if err != nil {
return err
}
ev, err := r.unmarshalerForEventType(eventType)
if err != nil {
return err
}
err = ev.UnmarshalEvent(r.payloadUnmarshaler, msg)
if err != nil {
return err
}
var ok bool
err, ok = ev.(error)
if !ok {
err = messageError{
code: "SerializationError",
msg: fmt.Sprintf(
"event stream exception %s mapped to non-error %T, %v",
eventType, ev, ev,
),
}
}
return err
}
func (r *EventReader) unmarshalErrorMessage(msg eventstream.Message) (err error) {
var msgErr messageError
msgErr.code, err = GetHeaderString(msg, ErrorCodeHeader)
if err != nil {
return err
}
msgErr.msg, err = GetHeaderString(msg, ErrorMessageHeader)
if err != nil {
return err
}
return msgErr
}
// GetHeaderString returns the value of the header as a string. If the header
// is not set or the value is not a string an error will be returned.
func GetHeaderString(msg eventstream.Message, headerName string) (string, error) {
headerVal := msg.Headers.Get(headerName)
if headerVal == nil {
return "", fmt.Errorf("error header %s not present", headerName)
}
v, ok := headerVal.Get().(string)
if !ok {
return "", fmt.Errorf("error header value is not a string, %T", headerVal)
}
return v, nil
}
| 174 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"bytes"
"fmt"
"io"
"testing"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
var eventMessageTypeHeader = eventstream.Header{
Name: MessageTypeHeader,
Value: eventstream.StringValue(EventMessageType),
}
func TestEventReader(t *testing.T) {
stream := createStream(
eventstream.Message{
Headers: eventstream.Headers{
eventMessageTypeHeader,
eventstream.Header{
Name: EventTypeHeader,
Value: eventstream.StringValue("eventABC"),
},
},
},
eventstream.Message{
Headers: eventstream.Headers{
eventMessageTypeHeader,
eventstream.Header{
Name: EventTypeHeader,
Value: eventstream.StringValue("eventEFG"),
},
},
},
)
var unmarshalers request.HandlerList
unmarshalers.PushBackNamed(restjson.UnmarshalHandler)
decoder := eventstream.NewDecoder(stream)
eventReader := NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: unmarshalers,
},
unmarshalerForEventType,
)
event, err := eventReader.ReadEvent()
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
if event == nil {
t.Fatalf("expect event got none")
}
event, err = eventReader.ReadEvent()
if err == nil {
t.Fatalf("expect error for unknown event, got none")
}
if event != nil {
t.Fatalf("expect no event, got %T, %v", event, event)
}
}
func TestEventReader_Error(t *testing.T) {
stream := createStream(
eventstream.Message{
Headers: eventstream.Headers{
eventstream.Header{
Name: MessageTypeHeader,
Value: eventstream.StringValue(ErrorMessageType),
},
eventstream.Header{
Name: ErrorCodeHeader,
Value: eventstream.StringValue("errorCode"),
},
eventstream.Header{
Name: ErrorMessageHeader,
Value: eventstream.StringValue("error message occur"),
},
},
},
)
var unmarshalers request.HandlerList
unmarshalers.PushBackNamed(restjson.UnmarshalHandler)
decoder := eventstream.NewDecoder(stream)
eventReader := NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: unmarshalers,
},
unmarshalerForEventType,
)
event, err := eventReader.ReadEvent()
if err == nil {
t.Fatalf("expect error got none")
}
if event != nil {
t.Fatalf("expect no event, got %v", event)
}
if e, a := "errorCode: error message occur", err.Error(); e != a {
t.Errorf("expect %v error, got %v", e, a)
}
}
func TestEventReader_Exception(t *testing.T) {
eventMsgs := []eventstream.Message{
{
Headers: eventstream.Headers{
eventstream.Header{
Name: MessageTypeHeader,
Value: eventstream.StringValue(ExceptionMessageType),
},
eventstream.Header{
Name: ExceptionTypeHeader,
Value: eventstream.StringValue("exception"),
},
},
Payload: []byte(`{"message":"exception message"}`),
},
}
stream := createStream(eventMsgs...)
var unmarshalers request.HandlerList
unmarshalers.PushBackNamed(restjson.UnmarshalHandler)
decoder := eventstream.NewDecoder(stream)
eventReader := NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: unmarshalers,
},
unmarshalerForEventType,
)
event, err := eventReader.ReadEvent()
if err == nil {
t.Fatalf("expect error got none")
}
if event != nil {
t.Fatalf("expect no event, got %v", event)
}
et := err.(*exceptionType)
if e, a := string(eventMsgs[0].Payload), string(et.Payload); e != a {
t.Errorf("expect %v payload, got %v", e, a)
}
}
func BenchmarkEventReader(b *testing.B) {
var buf bytes.Buffer
encoder := eventstream.NewEncoder(&buf)
msg := eventstream.Message{
Headers: eventstream.Headers{
eventMessageTypeHeader,
eventstream.Header{
Name: EventTypeHeader,
Value: eventstream.StringValue("eventStructured"),
},
},
Payload: []byte(`{"String":"stringfield","Number":123,"Nested":{"String":"fieldstring","Number":321}}`),
}
if err := encoder.Encode(msg); err != nil {
b.Fatalf("failed to encode message, %v", err)
}
stream := bytes.NewReader(buf.Bytes())
var unmarshalers request.HandlerList
unmarshalers.PushBackNamed(restjson.UnmarshalHandler)
decoder := eventstream.NewDecoder(stream)
eventReader := NewEventReader(decoder,
protocol.HandlerPayloadUnmarshal{
Unmarshalers: unmarshalers,
},
unmarshalerForEventType,
)
b.ResetTimer()
for i := 0; i < b.N; i++ {
stream.Seek(0, 0)
event, err := eventReader.ReadEvent()
if err != nil {
b.Fatalf("expect no error, got %v", err)
}
if event == nil {
b.Fatalf("expect event got none")
}
}
}
func unmarshalerForEventType(eventType string) (Unmarshaler, error) {
switch eventType {
case "eventABC":
return &eventABC{}, nil
case "eventStructured":
return &eventStructured{}, nil
case "exception":
return &exceptionType{}, nil
default:
return nil, fmt.Errorf("unknown event type, %v", eventType)
}
}
type eventABC struct {
_ struct{}
HeaderField string
Payload []byte
}
func (e *eventABC) UnmarshalEvent(
unmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
return nil
}
func createStream(msgs ...eventstream.Message) io.Reader {
w := bytes.NewBuffer(nil)
encoder := eventstream.NewEncoder(w)
for _, msg := range msgs {
if err := encoder.Encode(msg); err != nil {
panic("createStream failed, " + err.Error())
}
}
return w
}
type exceptionType struct {
Payload []byte
}
func (e exceptionType) Error() string {
return fmt.Sprintf("exception error message")
}
func (e *exceptionType) UnmarshalEvent(
unmarshaler protocol.PayloadUnmarshaler,
msg eventstream.Message,
) error {
e.Payload = msg.Payload
return nil
}
| 260 |
session-manager-plugin | aws | Go | package eventstreamapi
// EventStream headers with specific meaning to async API functionality.
const (
ChunkSignatureHeader = `:chunk-signature` // chunk signature for message
DateHeader = `:date` // Date header for signature
// Message header and values
MessageTypeHeader = `:message-type` // Identifies type of message.
EventMessageType = `event`
ErrorMessageType = `error`
ExceptionMessageType = `exception`
// Message Events
EventTypeHeader = `:event-type` // Identifies message event type e.g. "Stats".
// Message Error
ErrorCodeHeader = `:error-code`
ErrorMessageHeader = `:error-message`
// Message Exception
ExceptionTypeHeader = `:exception-type`
)
| 24 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"bytes"
"encoding/hex"
"time"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
type mockChunkSigner struct {
signature string
err error
}
func (m mockChunkSigner) GetSignature(_, _ []byte, _ time.Time) ([]byte, error) {
return mustDecodeBytes(hex.DecodeString(m.signature)), m.err
}
type eventStructured struct {
_ struct{} `type:"structure"`
String *string `type:"string"`
Number *int64 `type:"long"`
Nested *eventStructured `type:"structure"`
}
func (e *eventStructured) MarshalEvent(pm protocol.PayloadMarshaler) (eventstream.Message, error) {
var msg eventstream.Message
msg.Headers.Set(MessageTypeHeader, eventstream.StringValue(EventMessageType))
var buf bytes.Buffer
if err := pm.MarshalPayload(&buf, e); err != nil {
return eventstream.Message{}, err
}
msg.Payload = buf.Bytes()
return msg, nil
}
func (e *eventStructured) UnmarshalEvent(pm protocol.PayloadUnmarshaler, msg eventstream.Message) error {
return pm.UnmarshalPayload(bytes.NewReader(msg.Payload), e)
}
func mustDecodeBytes(b []byte, err error) []byte {
if err != nil {
panic(err)
}
return b
}
func swapTimeNow(f func() time.Time) func() {
if f == nil {
return func() {}
}
timeNow = f
return func() {
timeNow = time.Now
}
}
| 65 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"bytes"
"strings"
"time"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
var timeNow = time.Now
// StreamSigner defines an interface for the implementation of signing of event stream payloads
type StreamSigner interface {
GetSignature(headers, payload []byte, date time.Time) ([]byte, error)
}
// SignEncoder envelopes event stream messages
// into an event stream message payload with included
// signature headers using the provided signer and encoder.
type SignEncoder struct {
signer StreamSigner
encoder Encoder
bufEncoder *BufferEncoder
closeErr error
closed bool
}
// NewSignEncoder returns a new SignEncoder using the provided stream signer and
// event stream encoder.
func NewSignEncoder(signer StreamSigner, encoder Encoder) *SignEncoder {
// TODO: Need to pass down logging
return &SignEncoder{
signer: signer,
encoder: encoder,
bufEncoder: NewBufferEncoder(),
}
}
// Close encodes a final event stream signing envelope with an empty event stream
// payload. This final end-frame is used to mark the conclusion of the stream.
func (s *SignEncoder) Close() error {
if s.closed {
return s.closeErr
}
if err := s.encode([]byte{}); err != nil {
if strings.Contains(err.Error(), "on closed pipe") {
return nil
}
s.closeErr = err
s.closed = true
return s.closeErr
}
return nil
}
// Encode takes the provided message and add envelopes the message
// with the required signature.
func (s *SignEncoder) Encode(msg eventstream.Message) error {
payload, err := s.bufEncoder.Encode(msg)
if err != nil {
return err
}
return s.encode(payload)
}
func (s SignEncoder) encode(payload []byte) error {
date := timeNow()
var msg eventstream.Message
msg.Headers.Set(DateHeader, eventstream.TimestampValue(date))
msg.Payload = payload
var headers bytes.Buffer
if err := eventstream.EncodeHeaders(&headers, msg.Headers); err != nil {
return err
}
sig, err := s.signer.GetSignature(headers.Bytes(), msg.Payload, date)
if err != nil {
return err
}
msg.Headers.Set(ChunkSignatureHeader, eventstream.BytesValue(sig))
return s.encoder.Encode(msg)
}
// BufferEncoder is a utility that provides a buffered
// event stream encoder
type BufferEncoder struct {
encoder Encoder
buffer *bytes.Buffer
}
// NewBufferEncoder returns a new BufferEncoder initialized
// with a 1024 byte buffer.
func NewBufferEncoder() *BufferEncoder {
buf := bytes.NewBuffer(make([]byte, 1024))
return &BufferEncoder{
encoder: eventstream.NewEncoder(buf),
buffer: buf,
}
}
// Encode returns the encoded message as a byte slice.
// The returned byte slice will be modified on the next encode call
// and should not be held onto.
func (e *BufferEncoder) Encode(msg eventstream.Message) ([]byte, error) {
e.buffer.Reset()
if err := e.encoder.Encode(msg); err != nil {
return nil, err
}
return e.buffer.Bytes(), nil
}
| 124 |
session-manager-plugin | aws | Go | // +build go1.7
package eventstreamapi
import (
"bytes"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamtest"
)
func TestSignEncoder(t *testing.T) {
currentTime := time.Date(2019, 1, 27, 22, 37, 54, 0, time.UTC)
cases := map[string]struct {
Signer StreamSigner
Input eventstream.Message
Expect eventstream.Message
NestedExpect *eventstream.Message
Err string
}{
"sign message": {
Signer: mockChunkSigner{
signature: "524f1d03d1d81e94a099042736d40bd9681b867321443ff58a4568e274dbd83bff",
},
Input: eventstream.Message{
Headers: eventstream.Headers{
{
Name: "header_name",
Value: eventstream.StringValue("header value"),
},
},
Payload: []byte("payload"),
},
Expect: eventstream.Message{
Headers: eventstream.Headers{
{
Name: ":date",
Value: eventstream.TimestampValue(currentTime),
},
{
Name: ":chunk-signature",
Value: eventstream.BytesValue(mustDecodeBytes(
hex.DecodeString("524f1d03d1d81e94a099042736d40bd9681b867321443ff58a4568e274dbd83bff"),
)),
},
},
Payload: mustDecodeBytes(
base64.StdEncoding.DecodeString(
`AAAAMgAAABs0pv1jC2hlYWRlcl9uYW1lBwAMaGVhZGVyIHZhbHVlcGF5bG9hZH4tKFg=`,
),
),
},
NestedExpect: &eventstream.Message{
Headers: eventstream.Headers{
{
Name: "header_name",
Value: eventstream.StringValue("header value"),
},
},
Payload: []byte(`payload`),
},
},
"signing error": {
Signer: mockChunkSigner{err: fmt.Errorf("signing error")},
Input: eventstream.Message{
Headers: []eventstream.Header{
{
Name: "header_name",
Value: eventstream.StringValue("header value"),
},
},
Payload: []byte("payload"),
},
Err: "signing error",
},
}
origNowFn := timeNow
timeNow = func() time.Time { return currentTime }
defer func() { timeNow = origNowFn }()
decodeBuf := make([]byte, 1024)
for name, c := range cases {
t.Run(name, func(t *testing.T) {
encoder := &mockEncoder{}
signer := NewSignEncoder(c.Signer, encoder)
err := signer.Encode(c.Input)
if err == nil && len(c.Err) > 0 {
t.Fatalf("expected error, but got nil")
} else if err != nil && len(c.Err) == 0 {
t.Fatalf("expected no error, but got %v", err)
} else if err != nil && len(c.Err) > 0 && !strings.Contains(err.Error(), c.Err) {
t.Fatalf("expected %v, but got %v", c.Err, err)
} else if len(c.Err) > 0 {
return
}
eventstreamtest.AssertMessageEqual(t, c.Expect, encoder.msgs[0], "envelope msg")
if c.NestedExpect != nil {
nested := eventstream.NewDecoder(bytes.NewReader(encoder.msgs[0].Payload))
nestedMsg, err := nested.Decode(decodeBuf)
if err != nil {
t.Fatalf("expect no decode error got, %v", err)
}
eventstreamtest.AssertMessageEqual(t, *c.NestedExpect, nestedMsg, "nested msg")
}
})
}
}
type mockEncoder struct {
msgs []eventstream.Message
}
func (m *mockEncoder) Encode(msg eventstream.Message) error {
m.msgs = append(m.msgs, msg)
return nil
}
| 129 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"fmt"
"io"
"sync"
"github.com/aws/aws-sdk-go/aws"
)
// StreamWriter provides concurrent safe writing to an event stream.
type StreamWriter struct {
eventWriter *EventWriter
stream chan eventWriteAsyncReport
done chan struct{}
closeOnce sync.Once
err *OnceError
streamCloser io.Closer
}
// NewStreamWriter returns a StreamWriter for the event writer, and stream
// closer provided.
func NewStreamWriter(eventWriter *EventWriter, streamCloser io.Closer) *StreamWriter {
w := &StreamWriter{
eventWriter: eventWriter,
streamCloser: streamCloser,
stream: make(chan eventWriteAsyncReport),
done: make(chan struct{}),
err: NewOnceError(),
}
go w.writeStream()
return w
}
// Close terminates the writers ability to write new events to the stream. Any
// future call to Send will fail with an error.
func (w *StreamWriter) Close() error {
w.closeOnce.Do(w.safeClose)
return w.Err()
}
func (w *StreamWriter) safeClose() {
close(w.done)
}
// ErrorSet returns a channel which will be closed
// if an error occurs.
func (w *StreamWriter) ErrorSet() <-chan struct{} {
return w.err.ErrorSet()
}
// Err returns any error that occurred while attempting to write an event to the
// stream.
func (w *StreamWriter) Err() error {
return w.err.Err()
}
// Send writes a single event to the stream returning an error if the write
// failed.
//
// Send may be called concurrently. Events will be written to the stream
// safely.
func (w *StreamWriter) Send(ctx aws.Context, event Marshaler) error {
if err := w.Err(); err != nil {
return err
}
resultCh := make(chan error)
wrapped := eventWriteAsyncReport{
Event: event,
Result: resultCh,
}
select {
case w.stream <- wrapped:
case <-ctx.Done():
return ctx.Err()
case <-w.done:
return fmt.Errorf("stream closed, unable to send event")
}
select {
case err := <-resultCh:
return err
case <-ctx.Done():
return ctx.Err()
case <-w.done:
return fmt.Errorf("stream closed, unable to send event")
}
}
func (w *StreamWriter) writeStream() {
defer w.Close()
for {
select {
case wrapper := <-w.stream:
err := w.eventWriter.WriteEvent(wrapper.Event)
wrapper.ReportResult(w.done, err)
if err != nil {
w.err.SetError(err)
return
}
case <-w.done:
if err := w.streamCloser.Close(); err != nil {
w.err.SetError(err)
}
return
}
}
}
type eventWriteAsyncReport struct {
Event Marshaler
Result chan<- error
}
func (e eventWriteAsyncReport) ReportResult(cancel <-chan struct{}, err error) bool {
select {
case e.Result <- err:
return true
case <-cancel:
return false
}
}
| 130 |
session-manager-plugin | aws | Go | package eventstreamapi
import (
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
// Marshaler provides a marshaling interface for event types to event stream
// messages.
type Marshaler interface {
MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)
}
// Encoder is an stream encoder that will encode an event stream message for
// the transport.
type Encoder interface {
Encode(eventstream.Message) error
}
// EventWriter provides a wrapper around the underlying event stream encoder
// for an io.WriteCloser.
type EventWriter struct {
encoder Encoder
payloadMarshaler protocol.PayloadMarshaler
eventTypeFor func(Marshaler) (string, error)
}
// NewEventWriter returns a new event stream writer, that will write to the
// writer provided. Use the WriteEvent method to write an event to the stream.
func NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error),
) *EventWriter {
return &EventWriter{
encoder: encoder,
payloadMarshaler: pm,
eventTypeFor: eventTypeFor,
}
}
// WriteEvent writes an event to the stream. Returns an error if the event
// fails to marshal into a message, or writing to the underlying writer fails.
func (w *EventWriter) WriteEvent(event Marshaler) error {
msg, err := w.marshal(event)
if err != nil {
return err
}
return w.encoder.Encode(msg)
}
func (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) {
eventType, err := w.eventTypeFor(event)
if err != nil {
return eventstream.Message{}, err
}
msg, err := event.MarshalEvent(w.payloadMarshaler)
if err != nil {
return eventstream.Message{}, err
}
msg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType))
return msg, nil
}
| 64 |
session-manager-plugin | aws | Go | // +build go1.7
package eventstreamapi
import (
"bytes"
"encoding/base64"
"encoding/hex"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamtest"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
func TestEventWriter(t *testing.T) {
cases := map[string]struct {
Event Marshaler
EncodeWrapper func(e Encoder) Encoder
TimeFunc func() time.Time
Expect eventstream.Message
NestedExpect *eventstream.Message
}{
"structured event": {
Event: &eventStructured{
String: aws.String("stringfield"),
Number: aws.Int64(123),
Nested: &eventStructured{
String: aws.String("fieldstring"),
Number: aws.Int64(321),
},
},
Expect: eventstream.Message{
Headers: eventstream.Headers{
eventMessageTypeHeader,
eventstream.Header{
Name: EventTypeHeader,
Value: eventstream.StringValue("eventStructured"),
},
},
Payload: []byte(`{"String":"stringfield","Number":123,"Nested":{"String":"fieldstring","Number":321}}`),
},
},
"signed event": {
Event: &eventStructured{
String: aws.String("stringfield"),
Number: aws.Int64(123),
Nested: &eventStructured{
String: aws.String("fieldstring"),
Number: aws.Int64(321),
},
},
EncodeWrapper: func(e Encoder) Encoder {
return NewSignEncoder(
&mockChunkSigner{
signature: "524f1d03d1d81e94a099042736d40bd9681b867321443ff58a4568e274dbd83bff",
},
e,
)
},
TimeFunc: func() time.Time {
return time.Date(2019, 1, 27, 22, 37, 54, 0, time.UTC)
},
Expect: eventstream.Message{
Headers: eventstream.Headers{
{
Name: DateHeader,
Value: eventstream.TimestampValue(time.Date(2019, 1, 27, 22, 37, 54, 0, time.UTC)),
},
{
Name: ChunkSignatureHeader,
Value: eventstream.BytesValue(mustDecodeBytes(
hex.DecodeString("524f1d03d1d81e94a099042736d40bd9681b867321443ff58a4568e274dbd83bff"),
)),
},
},
Payload: mustDecodeBytes(base64.StdEncoding.DecodeString(
`AAAAmAAAADSl4EcNDTptZXNzYWdlLXR5cGUHAAVldmVudAs6ZXZlbnQtdHlwZQcAD2V2ZW50U3RydWN0dXJlZHsiU3RyaW5nIjoic3RyaW5nZmllbGQiLCJOdW1iZXIiOjEyMywiTmVzdGVkIjp7IlN0cmluZyI6ImZpZWxkc3RyaW5nIiwiTnVtYmVyIjozMjF9fdVW3Ow=`,
)),
},
},
}
var marshalers request.HandlerList
marshalers.PushBackNamed(restjson.BuildHandler)
var stream bytes.Buffer
decodeBuf := make([]byte, 1024)
for name, c := range cases {
t.Run(name, func(t *testing.T) {
defer swapTimeNow(c.TimeFunc)()
stream.Reset()
var encoder Encoder
encoder = eventstream.NewEncoder(&stream, eventstream.EncodeWithLogger(t))
if c.EncodeWrapper != nil {
encoder = c.EncodeWrapper(encoder)
}
eventWriter := NewEventWriter(encoder,
protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
},
func(event Marshaler) (string, error) {
return "eventStructured", nil
},
)
decoder := eventstream.NewDecoder(&stream)
if err := eventWriter.WriteEvent(c.Event); err != nil {
t.Fatalf("expect no write error, got %v", err)
}
msg, err := decoder.Decode(decodeBuf)
if err != nil {
t.Fatalf("expect no decode error got, %v", err)
}
eventstreamtest.AssertMessageEqual(t, c.Expect, msg)
})
}
}
func BenchmarkEventWriter(b *testing.B) {
var marshalers request.HandlerList
marshalers.PushBackNamed(restjson.BuildHandler)
var stream bytes.Buffer
encoder := eventstream.NewEncoder(&stream)
eventWriter := NewEventWriter(encoder,
protocol.HandlerPayloadMarshal{
Marshalers: marshalers,
},
func(event Marshaler) (string, error) {
return "eventStructured", nil
},
)
event := &eventStructured{
String: aws.String("stringfield"),
Number: aws.Int64(123),
Nested: &eventStructured{
String: aws.String("fieldstring"),
Number: aws.Int64(321),
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := eventWriter.WriteEvent(event); err != nil {
b.Fatalf("expect no write error, got %v", err)
}
}
}
| 162 |
session-manager-plugin | aws | Go | // +build !go1.10
package eventstreamtest
import (
"net/http"
"net/http/httptest"
)
// /x/net/http2 is only available for the latest two versions of Go. Any Go
// version older than that cannot use the utility to configure the http2
// server.
func setupServer(server *httptest.Server, useH2 bool) *http.Client {
server.Start()
return nil
}
| 18 |
session-manager-plugin | aws | Go | // +build go1.15
package eventstreamtest
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"golang.org/x/net/http2"
)
// /x/net/http2 is only available for the latest two versions of Go. Any Go
// version older than that cannot use the utility to configure the http2
// server.
func setupServer(server *httptest.Server, useH2 bool) *http.Client {
server.Config.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
}
clientTrans := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
if useH2 {
http2.ConfigureServer(server.Config, nil)
http2.ConfigureTransport(clientTrans)
server.Config.TLSConfig.NextProtos = []string{http2.NextProtoTLS}
clientTrans.TLSClientConfig.NextProtos = []string{http2.NextProtoTLS}
}
server.TLS = server.Config.TLSConfig
server.StartTLS()
return &http.Client{
Transport: clientTrans,
}
}
| 41 |
session-manager-plugin | aws | Go | // +build go1.9
package eventstreamtest
import "testing"
var getHelper = func(t testing.TB) func() {
return t.Helper
}
| 10 |
session-manager-plugin | aws | Go | // +build !go1.9
package eventstreamtest
import "testing"
var getHelper = func(t testing.TB) func() {
return nopHelper
}
func nopHelper() {}
| 12 |
session-manager-plugin | aws | Go | // +build go1.15
package eventstreamtest
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"golang.org/x/net/http2"
)
const (
errClientDisconnected = "client disconnected"
errStreamClosed = "http2: stream closed"
)
// ServeEventStream provides serving EventStream messages from a HTTP server to
// the client. The events are sent sequentially to the client without delay.
type ServeEventStream struct {
T *testing.T
BiDirectional bool
Events []eventstream.Message
ClientEvents []eventstream.Message
ForceCloseAfter time.Duration
requestsIdx int
}
func (s ServeEventStream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
if s.BiDirectional {
s.serveBiDirectionalStream(w, r)
} else {
s.serveReadOnlyStream(w, r)
}
}
func (s *ServeEventStream) serveReadOnlyStream(w http.ResponseWriter, r *http.Request) {
encoder := eventstream.NewEncoder(flushWriter{w})
for _, event := range s.Events {
encoder.Encode(event)
}
}
func (s *ServeEventStream) serveBiDirectionalStream(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
ctx := context.Background()
if s.ForceCloseAfter > 0 {
var cancelFunc func()
ctx, cancelFunc = context.WithTimeout(context.Background(), s.ForceCloseAfter)
defer cancelFunc()
}
var (
err error
m sync.Mutex
)
wg.Add(1)
go func() {
defer wg.Done()
readErr := s.readEvents(ctx, r)
if readErr != nil {
m.Lock()
if err == nil {
err = readErr
}
m.Unlock()
}
}()
writeErr := s.writeEvents(ctx, w)
if writeErr != nil {
m.Lock()
if err != nil {
err = writeErr
}
m.Unlock()
}
wg.Wait()
if err != nil && isError(err) {
s.T.Error(err.Error())
}
}
func isError(err error) bool {
switch err.(type) {
case http2.StreamError:
return false
}
for _, s := range []string{errClientDisconnected, errStreamClosed} {
if strings.Contains(err.Error(), s) {
return false
}
}
return true
}
func (s ServeEventStream) readEvents(ctx context.Context, r *http.Request) error {
signBuffer := make([]byte, 1024)
messageBuffer := make([]byte, 1024)
decoder := eventstream.NewDecoder(r.Body)
for {
select {
case <-ctx.Done():
return nil
default:
}
// unwrap signing envelope
signedMessage, err := decoder.Decode(signBuffer)
if err != nil {
if err == io.EOF {
break
}
return err
}
// empty payload is expected for the last signing message
if len(signedMessage.Payload) == 0 {
break
}
// get service event message from payload
msg, err := eventstream.Decode(bytes.NewReader(signedMessage.Payload), messageBuffer)
if err != nil {
if err == io.EOF {
break
}
return err
}
if len(s.ClientEvents) > 0 {
i := s.requestsIdx
s.requestsIdx++
if e, a := s.ClientEvents[i], msg; !reflect.DeepEqual(e, a) {
return fmt.Errorf("expected %v, got %v", e, a)
}
}
}
return nil
}
func (s *ServeEventStream) writeEvents(ctx context.Context, w http.ResponseWriter) error {
encoder := eventstream.NewEncoder(flushWriter{w})
var event eventstream.Message
pendingEvents := s.Events
for len(pendingEvents) > 0 {
event, pendingEvents = pendingEvents[0], pendingEvents[1:]
select {
case <-ctx.Done():
return nil
default:
err := encoder.Encode(event)
if err != nil {
if err == io.EOF {
return nil
}
return fmt.Errorf("expected no error encoding event, got %v", err)
}
}
}
return nil
}
// SetupEventStreamSession creates a HTTP server SDK session for communicating
// with that server to be used for EventStream APIs. If HTTP/2 is enabled the
// server/client will only attempt to use HTTP/2.
func SetupEventStreamSession(
t *testing.T, handler http.Handler, h2 bool,
) (sess *session.Session, cleanupFn func(), err error) {
server := httptest.NewUnstartedServer(handler)
client := setupServer(server, h2)
cleanupFn = func() {
server.Close()
}
sess, err = session.NewSession(unit.Session.Config, &aws.Config{
Endpoint: &server.URL,
DisableParamValidation: aws.Bool(true),
HTTPClient: client,
// LogLevel: aws.LogLevel(aws.LogDebugWithEventStreamBody),
})
if err != nil {
return nil, nil, err
}
return sess, cleanupFn, nil
}
type flushWriter struct {
w io.Writer
}
func (fw flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.w.Write(p)
if f, ok := fw.w.(http.Flusher); ok {
f.Flush()
}
return
}
// MarshalEventPayload marshals a SDK API shape into its associated wire
// protocol payload.
func MarshalEventPayload(
payloadMarshaler protocol.PayloadMarshaler,
v interface{},
) []byte {
var w bytes.Buffer
err := payloadMarshaler.MarshalPayload(&w, v)
if err != nil {
panic(fmt.Sprintf("failed to marshal event %T, %v, %v", v, v, err))
}
return w.Bytes()
}
// Prevent circular dependencies on eventstreamapi redefine these here.
const (
messageTypeHeader = `:message-type` // Identifies type of message.
eventMessageType = `event`
exceptionMessageType = `exception`
)
// EventMessageTypeHeader is an event message type header for specifying an
// event is an message type.
var EventMessageTypeHeader = eventstream.Header{
Name: messageTypeHeader,
Value: eventstream.StringValue(eventMessageType),
}
// EventExceptionTypeHeader is an event exception type header for specifying an
// event is an exception type.
var EventExceptionTypeHeader = eventstream.Header{
Name: messageTypeHeader,
Value: eventstream.StringValue(exceptionMessageType),
}
| 268 |
session-manager-plugin | aws | Go | // +build go1.7
package eventstreamtest
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
// AssertMessageEqual compares to event stream messages, and determines if they
// are equal. Will trigger an testing Error if components of the message are
// not equal.
func AssertMessageEqual(t testing.TB, a, b eventstream.Message, msg ...interface{}) {
getHelper(t)()
ah, err := bytesEncodeHeader(a.Headers)
if err != nil {
t.Fatalf("unable to encode a's headers, %v", err)
}
bh, err := bytesEncodeHeader(b.Headers)
if err != nil {
t.Fatalf("unable to encode b's headers, %v", err)
}
if !bytes.Equal(ah, bh) {
aj, err := json.Marshal(ah)
if err != nil {
t.Fatalf("unable to json encode a's headers, %v", err)
}
bj, err := json.Marshal(bh)
if err != nil {
t.Fatalf("unable to json encode b's headers, %v", err)
}
t.Errorf("%s\nexpect headers: %v\n\t%v\nactual headers: %v\n\t%v\n",
fmt.Sprint(msg...),
base64.StdEncoding.EncodeToString(ah), aj,
base64.StdEncoding.EncodeToString(bh), bj,
)
}
if !bytes.Equal(a.Payload, b.Payload) {
t.Errorf("%s\nexpect payload: %v\nactual payload: %v\n",
fmt.Sprint(msg...),
base64.StdEncoding.EncodeToString(a.Payload),
base64.StdEncoding.EncodeToString(b.Payload),
)
}
}
func bytesEncodeHeader(v eventstream.Headers) ([]byte, error) {
var buf bytes.Buffer
if err := eventstream.EncodeHeaders(&buf, v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
| 64 |
session-manager-plugin | aws | Go | // Package jsonutil provides JSON serialization of AWS requests and responses.
package jsonutil
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"reflect"
"sort"
"strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/private/protocol"
)
var timeType = reflect.ValueOf(time.Time{}).Type()
var byteSliceType = reflect.ValueOf([]byte{}).Type()
// BuildJSON builds a JSON string for a given object v.
func BuildJSON(v interface{}) ([]byte, error) {
var buf bytes.Buffer
err := buildAny(reflect.ValueOf(v), &buf, "")
return buf.Bytes(), err
}
func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
origVal := value
value = reflect.Indirect(value)
if !value.IsValid() {
return nil
}
vtype := value.Type()
t := tag.Get("type")
if t == "" {
switch vtype.Kind() {
case reflect.Struct:
// also it can't be a time object
if value.Type() != timeType {
t = "structure"
}
case reflect.Slice:
// also it can't be a byte slice
if _, ok := value.Interface().([]byte); !ok {
t = "list"
}
case reflect.Map:
// cannot be a JSONValue map
if _, ok := value.Interface().(aws.JSONValue); !ok {
t = "map"
}
}
}
switch t {
case "structure":
if field, ok := vtype.FieldByName("_"); ok {
tag = field.Tag
}
return buildStruct(value, buf, tag)
case "list":
return buildList(value, buf, tag)
case "map":
return buildMap(value, buf, tag)
default:
return buildScalar(origVal, buf, tag)
}
}
func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
if !value.IsValid() {
return nil
}
// unwrap payloads
if payload := tag.Get("payload"); payload != "" {
field, _ := value.Type().FieldByName(payload)
tag = field.Tag
value = elemOf(value.FieldByName(payload))
if !value.IsValid() {
return nil
}
}
buf.WriteByte('{')
t := value.Type()
first := true
for i := 0; i < t.NumField(); i++ {
member := value.Field(i)
// This allocates the most memory.
// Additionally, we cannot skip nil fields due to
// idempotency auto filling.
field := t.Field(i)
if field.PkgPath != "" {
continue // ignore unexported fields
}
if field.Tag.Get("json") == "-" {
continue
}
if field.Tag.Get("location") != "" {
continue // ignore non-body elements
}
if field.Tag.Get("ignore") != "" {
continue
}
if protocol.CanSetIdempotencyToken(member, field) {
token := protocol.GetIdempotencyToken()
member = reflect.ValueOf(&token)
}
if (member.Kind() == reflect.Ptr || member.Kind() == reflect.Slice || member.Kind() == reflect.Map) && member.IsNil() {
continue // ignore unset fields
}
if first {
first = false
} else {
buf.WriteByte(',')
}
// figure out what this field is called
name := field.Name
if locName := field.Tag.Get("locationName"); locName != "" {
name = locName
}
writeString(name, buf)
buf.WriteString(`:`)
err := buildAny(member, buf, field.Tag)
if err != nil {
return err
}
}
buf.WriteString("}")
return nil
}
func buildList(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
buf.WriteString("[")
for i := 0; i < value.Len(); i++ {
buildAny(value.Index(i), buf, "")
if i < value.Len()-1 {
buf.WriteString(",")
}
}
buf.WriteString("]")
return nil
}
type sortedValues []reflect.Value
func (sv sortedValues) Len() int { return len(sv) }
func (sv sortedValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
func (sv sortedValues) Less(i, j int) bool { return sv[i].String() < sv[j].String() }
func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
buf.WriteString("{")
sv := sortedValues(value.MapKeys())
sort.Sort(sv)
for i, k := range sv {
if i > 0 {
buf.WriteByte(',')
}
writeString(k.String(), buf)
buf.WriteString(`:`)
buildAny(value.MapIndex(k), buf, "")
}
buf.WriteString("}")
return nil
}
func buildScalar(v reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
// prevents allocation on the heap.
scratch := [64]byte{}
switch value := reflect.Indirect(v); value.Kind() {
case reflect.String:
writeString(value.String(), buf)
case reflect.Bool:
if value.Bool() {
buf.WriteString("true")
} else {
buf.WriteString("false")
}
case reflect.Int64:
buf.Write(strconv.AppendInt(scratch[:0], value.Int(), 10))
case reflect.Float64:
f := value.Float()
if math.IsInf(f, 0) || math.IsNaN(f) {
return &json.UnsupportedValueError{Value: v, Str: strconv.FormatFloat(f, 'f', -1, 64)}
}
buf.Write(strconv.AppendFloat(scratch[:0], f, 'f', -1, 64))
default:
switch converted := value.Interface().(type) {
case time.Time:
format := tag.Get("timestampFormat")
if len(format) == 0 {
format = protocol.UnixTimeFormatName
}
ts := protocol.FormatTime(format, converted)
if format != protocol.UnixTimeFormatName {
ts = `"` + ts + `"`
}
buf.WriteString(ts)
case []byte:
if !value.IsNil() {
buf.WriteByte('"')
if len(converted) < 1024 {
// for small buffers, using Encode directly is much faster.
dst := make([]byte, base64.StdEncoding.EncodedLen(len(converted)))
base64.StdEncoding.Encode(dst, converted)
buf.Write(dst)
} else {
// for large buffers, avoid unnecessary extra temporary
// buffer space.
enc := base64.NewEncoder(base64.StdEncoding, buf)
enc.Write(converted)
enc.Close()
}
buf.WriteByte('"')
}
case aws.JSONValue:
str, err := protocol.EncodeJSONValue(converted, protocol.QuotedEscape)
if err != nil {
return fmt.Errorf("unable to encode JSONValue, %v", err)
}
buf.WriteString(str)
default:
return fmt.Errorf("unsupported JSON value %v (%s)", value.Interface(), value.Type())
}
}
return nil
}
var hex = "0123456789abcdef"
func writeString(s string, buf *bytes.Buffer) {
buf.WriteByte('"')
for i := 0; i < len(s); i++ {
if s[i] == '"' {
buf.WriteString(`\"`)
} else if s[i] == '\\' {
buf.WriteString(`\\`)
} else if s[i] == '\b' {
buf.WriteString(`\b`)
} else if s[i] == '\f' {
buf.WriteString(`\f`)
} else if s[i] == '\r' {
buf.WriteString(`\r`)
} else if s[i] == '\t' {
buf.WriteString(`\t`)
} else if s[i] == '\n' {
buf.WriteString(`\n`)
} else if s[i] < 32 {
buf.WriteString("\\u00")
buf.WriteByte(hex[s[i]>>4])
buf.WriteByte(hex[s[i]&0xF])
} else {
buf.WriteByte(s[i])
}
}
buf.WriteByte('"')
}
// Returns the reflection element of a value, if it is a pointer.
func elemOf(value reflect.Value) reflect.Value {
for value.Kind() == reflect.Ptr {
value = value.Elem()
}
return value
}
| 297 |
session-manager-plugin | aws | Go | package jsonutil_test
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
)
func S(s string) *string {
return &s
}
func D(s int64) *int64 {
return &s
}
func F(s float64) *float64 {
return &s
}
func T(s time.Time) *time.Time {
return &s
}
type J struct {
S *string
SS []string
D *int64
F *float64
T *time.Time
}
var zero = 0.0
var jsonTests = []struct {
in interface{}
out string
err string
}{
{
J{},
`{}`,
``,
},
{
J{
S: S("str"),
SS: []string{"A", "B", "C"},
D: D(123),
F: F(4.56),
T: T(time.Unix(987, 0)),
},
`{"S":"str","SS":["A","B","C"],"D":123,"F":4.56,"T":987}`,
``,
},
{
J{
S: S(`"''"`),
},
`{"S":"\"''\""}`,
``,
},
{
J{
S: S("\x00føø\u00FF\n\\\"\r\t\b\f"),
},
`{"S":"\u0000føøÿ\n\\\"\r\t\b\f"}`,
``,
},
{
J{
F: F(4.56 / zero),
},
"",
`json: unsupported value: +Inf`,
},
}
func TestBuildJSON(t *testing.T) {
for _, test := range jsonTests {
out, err := jsonutil.BuildJSON(test.in)
if test.err != "" {
if err == nil {
t.Errorf("expect error")
}
if e, a := test.err, err.Error(); !strings.Contains(a, e) {
t.Errorf("expect %v, to contain %v", e, a)
}
} else {
if err != nil {
t.Errorf("expect nil, %v", err)
}
if e, a := string(out), test.out; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
}
}
func BenchmarkBuildJSON(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, test := range jsonTests {
jsonutil.BuildJSON(test.in)
}
}
}
func BenchmarkStdlibJSON(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, test := range jsonTests {
json.Marshal(test.in)
}
}
}
| 118 |
session-manager-plugin | aws | Go | package jsonutil
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/big"
"reflect"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/private/protocol"
)
var millisecondsFloat = new(big.Float).SetInt64(1e3)
// UnmarshalJSONError unmarshal's the reader's JSON document into the passed in
// type. The value to unmarshal the json document into must be a pointer to the
// type.
func UnmarshalJSONError(v interface{}, stream io.Reader) error {
var errBuf bytes.Buffer
body := io.TeeReader(stream, &errBuf)
err := json.NewDecoder(body).Decode(v)
if err != nil {
msg := "failed decoding error message"
if err == io.EOF {
msg = "error message missing"
err = nil
}
return awserr.NewUnmarshalError(err, msg, errBuf.Bytes())
}
return nil
}
// UnmarshalJSON reads a stream and unmarshals the results in object v.
func UnmarshalJSON(v interface{}, stream io.Reader) error {
var out interface{}
decoder := json.NewDecoder(stream)
decoder.UseNumber()
err := decoder.Decode(&out)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
return unmarshaler{}.unmarshalAny(reflect.ValueOf(v), out, "")
}
// UnmarshalJSONCaseInsensitive reads a stream and unmarshals the result into the
// object v. Ignores casing for structure members.
func UnmarshalJSONCaseInsensitive(v interface{}, stream io.Reader) error {
var out interface{}
decoder := json.NewDecoder(stream)
decoder.UseNumber()
err := decoder.Decode(&out)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
return unmarshaler{
caseInsensitive: true,
}.unmarshalAny(reflect.ValueOf(v), out, "")
}
type unmarshaler struct {
caseInsensitive bool
}
func (u unmarshaler) unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error {
vtype := value.Type()
if vtype.Kind() == reflect.Ptr {
vtype = vtype.Elem() // check kind of actual element type
}
t := tag.Get("type")
if t == "" {
switch vtype.Kind() {
case reflect.Struct:
// also it can't be a time object
if _, ok := value.Interface().(*time.Time); !ok {
t = "structure"
}
case reflect.Slice:
// also it can't be a byte slice
if _, ok := value.Interface().([]byte); !ok {
t = "list"
}
case reflect.Map:
// cannot be a JSONValue map
if _, ok := value.Interface().(aws.JSONValue); !ok {
t = "map"
}
}
}
switch t {
case "structure":
if field, ok := vtype.FieldByName("_"); ok {
tag = field.Tag
}
return u.unmarshalStruct(value, data, tag)
case "list":
return u.unmarshalList(value, data, tag)
case "map":
return u.unmarshalMap(value, data, tag)
default:
return u.unmarshalScalar(value, data, tag)
}
}
func (u unmarshaler) unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error {
if data == nil {
return nil
}
mapData, ok := data.(map[string]interface{})
if !ok {
return fmt.Errorf("JSON value is not a structure (%#v)", data)
}
t := value.Type()
if value.Kind() == reflect.Ptr {
if value.IsNil() { // create the structure if it's nil
s := reflect.New(value.Type().Elem())
value.Set(s)
value = s
}
value = value.Elem()
t = t.Elem()
}
// unwrap any payloads
if payload := tag.Get("payload"); payload != "" {
field, _ := t.FieldByName(payload)
return u.unmarshalAny(value.FieldByName(payload), data, field.Tag)
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" {
continue // ignore unexported fields
}
// figure out what this field is called
name := field.Name
if locName := field.Tag.Get("locationName"); locName != "" {
name = locName
}
if u.caseInsensitive {
if _, ok := mapData[name]; !ok {
// Fallback to uncased name search if the exact name didn't match.
for kn, v := range mapData {
if strings.EqualFold(kn, name) {
mapData[name] = v
}
}
}
}
member := value.FieldByIndex(field.Index)
err := u.unmarshalAny(member, mapData[name], field.Tag)
if err != nil {
return err
}
}
return nil
}
func (u unmarshaler) unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error {
if data == nil {
return nil
}
listData, ok := data.([]interface{})
if !ok {
return fmt.Errorf("JSON value is not a list (%#v)", data)
}
if value.IsNil() {
l := len(listData)
value.Set(reflect.MakeSlice(value.Type(), l, l))
}
for i, c := range listData {
err := u.unmarshalAny(value.Index(i), c, "")
if err != nil {
return err
}
}
return nil
}
func (u unmarshaler) unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error {
if data == nil {
return nil
}
mapData, ok := data.(map[string]interface{})
if !ok {
return fmt.Errorf("JSON value is not a map (%#v)", data)
}
if value.IsNil() {
value.Set(reflect.MakeMap(value.Type()))
}
for k, v := range mapData {
kvalue := reflect.ValueOf(k)
vvalue := reflect.New(value.Type().Elem()).Elem()
u.unmarshalAny(vvalue, v, "")
value.SetMapIndex(kvalue, vvalue)
}
return nil
}
func (u unmarshaler) unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error {
switch d := data.(type) {
case nil:
return nil // nothing to do here
case string:
switch value.Interface().(type) {
case *string:
value.Set(reflect.ValueOf(&d))
case []byte:
b, err := base64.StdEncoding.DecodeString(d)
if err != nil {
return err
}
value.Set(reflect.ValueOf(b))
case *time.Time:
format := tag.Get("timestampFormat")
if len(format) == 0 {
format = protocol.ISO8601TimeFormatName
}
t, err := protocol.ParseTime(format, d)
if err != nil {
return err
}
value.Set(reflect.ValueOf(&t))
case aws.JSONValue:
// No need to use escaping as the value is a non-quoted string.
v, err := protocol.DecodeJSONValue(d, protocol.NoEscape)
if err != nil {
return err
}
value.Set(reflect.ValueOf(v))
default:
return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
}
case json.Number:
switch value.Interface().(type) {
case *int64:
// Retain the old behavior where we would just truncate the float64
// calling d.Int64() here could cause an invalid syntax error due to the usage of strconv.ParseInt
f, err := d.Float64()
if err != nil {
return err
}
di := int64(f)
value.Set(reflect.ValueOf(&di))
case *float64:
f, err := d.Float64()
if err != nil {
return err
}
value.Set(reflect.ValueOf(&f))
case *time.Time:
float, ok := new(big.Float).SetString(d.String())
if !ok {
return fmt.Errorf("unsupported float time representation: %v", d.String())
}
float = float.Mul(float, millisecondsFloat)
ms, _ := float.Int64()
t := time.Unix(0, ms*1e6).UTC()
value.Set(reflect.ValueOf(&t))
default:
return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
}
case bool:
switch value.Interface().(type) {
case *bool:
value.Set(reflect.ValueOf(&d))
default:
return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
}
default:
return fmt.Errorf("unsupported JSON value (%v)", data)
}
return nil
}
| 305 |
session-manager-plugin | aws | Go | // +build go1.7
package jsonutil_test
import (
"bytes"
"reflect"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
)
func TestUnmarshalJSON_JSONNumber(t *testing.T) {
type input struct {
TimeField *time.Time `locationName:"timeField"`
IntField *int64 `locationName:"intField"`
FloatField *float64 `locationName:"floatField"`
}
cases := map[string]struct {
JSON string
Value input
Expected input
}{
"seconds precision": {
JSON: `{"timeField":1597094942}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, 00, time.UTC)
return &dt
}(),
},
},
"exact milliseconds precision": {
JSON: `{"timeField":1597094942.123}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, int(123*time.Millisecond), time.UTC)
return &dt
}(),
},
},
"microsecond precision truncated": {
JSON: `{"timeField":1597094942.1235}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, int(123*time.Millisecond), time.UTC)
return &dt
}(),
},
},
"nanosecond precision truncated": {
JSON: `{"timeField":1597094942.123456789}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, int(123*time.Millisecond), time.UTC)
return &dt
}(),
},
},
"milliseconds precision as small exponent": {
JSON: `{"timeField":1.597094942123e9}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, int(123*time.Millisecond), time.UTC)
return &dt
}(),
},
},
"milliseconds precision as large exponent": {
JSON: `{"timeField":1.597094942123E9}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, int(123*time.Millisecond), time.UTC)
return &dt
}(),
},
},
"milliseconds precision as exponent with sign": {
JSON: `{"timeField":1.597094942123e+9}`,
Expected: input{
TimeField: func() *time.Time {
dt := time.Date(2020, 8, 10, 21, 29, 02, int(123*time.Millisecond), time.UTC)
return &dt
}(),
},
},
"integer field": {
JSON: `{"intField":123456789}`,
Expected: input{
IntField: aws.Int64(123456789),
},
},
"integer field truncated": {
JSON: `{"intField":123456789.123}`,
Expected: input{
IntField: aws.Int64(123456789),
},
},
"float64 field": {
JSON: `{"floatField":123456789.123}`,
Expected: input{
FloatField: aws.Float64(123456789.123),
},
},
}
for name, tt := range cases {
t.Run(name, func(t *testing.T) {
err := jsonutil.UnmarshalJSON(&tt.Value, bytes.NewReader([]byte(tt.JSON)))
if err != nil {
t.Errorf("expect no error, got %v", err)
}
if e, a := tt.Expected, tt.Value; !reflect.DeepEqual(e, a) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
| 122 |
session-manager-plugin | aws | Go | // +build bench
package jsonrpc_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
func BenchmarkJSONRPCBuild_Simple_dynamodbPutItem(b *testing.B) {
svc := awstesting.NewClient()
params := getDynamodbPutItemParams(b)
for i := 0; i < b.N; i++ {
r := svc.NewRequest(&request.Operation{Name: "Operation"}, params, nil)
jsonrpc.Build(r)
if r.Error != nil {
b.Fatal("Unexpected error", r.Error)
}
}
}
func BenchmarkJSONUtilBuild_Simple_dynamodbPutItem(b *testing.B) {
svc := awstesting.NewClient()
params := getDynamodbPutItemParams(b)
for i := 0; i < b.N; i++ {
r := svc.NewRequest(&request.Operation{Name: "Operation"}, params, nil)
_, err := jsonutil.BuildJSON(r.Params)
if err != nil {
b.Fatal("Unexpected error", err)
}
}
}
func BenchmarkEncodingJSONMarshal_Simple_dynamodbPutItem(b *testing.B) {
params := getDynamodbPutItemParams(b)
for i := 0; i < b.N; i++ {
buf := &bytes.Buffer{}
encoder := json.NewEncoder(buf)
if err := encoder.Encode(params); err != nil {
b.Fatal("Unexpected error", err)
}
}
}
func getDynamodbPutItemParams(b *testing.B) *dynamodb.PutItemInput {
av, err := dynamodbattribute.ConvertToMap(struct {
Key string
Data string
}{Key: "MyKey", Data: "MyData"})
if err != nil {
b.Fatal("benchPutItem, expect no ConvertToMap errors", err)
}
return &dynamodb.PutItemInput{
Item: av,
TableName: aws.String("tablename"),
}
}
| 72 |
session-manager-plugin | aws | Go | // Code generated by models/protocol_tests/generate.go. DO NOT EDIT.
package jsonrpc_test
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
"github.com/aws/aws-sdk-go/private/util"
)
var _ bytes.Buffer // always import bytes
var _ http.Request
var _ json.Marshaler
var _ time.Time
var _ xmlutil.XMLNode
var _ xml.Attr
var _ = ioutil.Discard
var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
var _ = aws.String
var _ = fmt.Println
var _ = reflect.Value{}
func init() {
protocol.RandReader = &awstesting.ZeroReader{}
}
// InputService1ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService1ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService1ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService1ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService1ProtocolTest client from just a session.
// svc := inputservice1protocoltest.New(mySession)
//
// // Create a InputService1ProtocolTest client with additional configuration
// svc := inputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService1ProtocolTest {
c := p.ClientConfig("inputservice1protocoltest", cfgs...)
return newInputService1ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService1ProtocolTest {
svc := &InputService1ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService1ProtocolTest",
ServiceID: "InputService1ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService1ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService1TestCaseOperation1 = "OperationName"
// InputService1TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService1TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService1TestCaseOperation1 for more information on using the InputService1TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService1TestCaseOperation1Request method.
// req, resp := client.InputService1TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService1TestCaseOperation1,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService1TestShapeInputService1TestCaseOperation1Input{}
}
output = &InputService1TestShapeInputService1TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService1TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService1TestCaseOperation1 for usage and error information.
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) {
req, out := c.InputService1TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService1TestCaseOperation1WithContext is the same as InputService1TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService1TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation1Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) {
req, out := c.InputService1TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService1TestShapeInputService1TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Name *string `type:"string"`
}
// SetName sets the Name field's value.
func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetName(v string) *InputService1TestShapeInputService1TestCaseOperation1Input {
s.Name = &v
return s
}
type InputService1TestShapeInputService1TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService2ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService2ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService2ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService2ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService2ProtocolTest client from just a session.
// svc := inputservice2protocoltest.New(mySession)
//
// // Create a InputService2ProtocolTest client with additional configuration
// svc := inputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService2ProtocolTest {
c := p.ClientConfig("inputservice2protocoltest", cfgs...)
return newInputService2ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService2ProtocolTest {
svc := &InputService2ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService2ProtocolTest",
ServiceID: "InputService2ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService2ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService2TestCaseOperation1 = "OperationName"
// InputService2TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService2TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService2TestCaseOperation1 for more information on using the InputService2TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService2TestCaseOperation1Request method.
// req, resp := client.InputService2TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService2TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService2TestShapeInputService2TestCaseOperation1Input{}
}
output = &InputService2TestShapeInputService2TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService2TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService2TestCaseOperation1 for usage and error information.
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) {
req, out := c.InputService2TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService2TestCaseOperation1WithContext is the same as InputService2TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService2TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1WithContext(ctx aws.Context, input *InputService2TestShapeInputService2TestCaseOperation1Input, opts ...request.Option) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) {
req, out := c.InputService2TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService2TestShapeInputService2TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
TimeArg *time.Time `type:"timestamp"`
TimeCustom *time.Time `type:"timestamp" timestampFormat:"rfc822"`
TimeFormat *time.Time `type:"timestamp" timestampFormat:"rfc822"`
}
// SetTimeArg sets the TimeArg field's value.
func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetTimeArg(v time.Time) *InputService2TestShapeInputService2TestCaseOperation1Input {
s.TimeArg = &v
return s
}
// SetTimeCustom sets the TimeCustom field's value.
func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetTimeCustom(v time.Time) *InputService2TestShapeInputService2TestCaseOperation1Input {
s.TimeCustom = &v
return s
}
// SetTimeFormat sets the TimeFormat field's value.
func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetTimeFormat(v time.Time) *InputService2TestShapeInputService2TestCaseOperation1Input {
s.TimeFormat = &v
return s
}
type InputService2TestShapeInputService2TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService3ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService3ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService3ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService3ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService3ProtocolTest client from just a session.
// svc := inputservice3protocoltest.New(mySession)
//
// // Create a InputService3ProtocolTest client with additional configuration
// svc := inputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService3ProtocolTest {
c := p.ClientConfig("inputservice3protocoltest", cfgs...)
return newInputService3ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService3ProtocolTest {
svc := &InputService3ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService3ProtocolTest",
ServiceID: "InputService3ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService3ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService3TestCaseOperation1 = "OperationName"
// InputService3TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService3TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService3TestCaseOperation1 for more information on using the InputService3TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService3TestCaseOperation1Request method.
// req, resp := client.InputService3TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService3TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService3TestShapeInputService3TestCaseOperation1Input{}
}
output = &InputService3TestShapeInputService3TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService3TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService3TestCaseOperation1 for usage and error information.
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) {
req, out := c.InputService3TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService3TestCaseOperation1WithContext is the same as InputService3TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService3TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation1Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) {
req, out := c.InputService3TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService3TestCaseOperation2 = "OperationName"
// InputService3TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService3TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService3TestCaseOperation2 for more information on using the InputService3TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService3TestCaseOperation2Request method.
// req, resp := client.InputService3TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService3ProtocolTest) InputService3TestCaseOperation2Request(input *InputService3TestShapeInputService3TestCaseOperation2Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService3TestCaseOperation2,
HTTPPath: "/",
}
if input == nil {
input = &InputService3TestShapeInputService3TestCaseOperation2Input{}
}
output = &InputService3TestShapeInputService3TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService3TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService3TestCaseOperation2 for usage and error information.
func (c *InputService3ProtocolTest) InputService3TestCaseOperation2(input *InputService3TestShapeInputService3TestCaseOperation2Input) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) {
req, out := c.InputService3TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService3TestCaseOperation2WithContext is the same as InputService3TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService3TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService3ProtocolTest) InputService3TestCaseOperation2WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation2Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) {
req, out := c.InputService3TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService3TestShapeInputService3TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
// BlobArg is automatically base64 encoded/decoded by the SDK.
BlobArg []byte `type:"blob"`
BlobMap map[string][]byte `type:"map"`
}
// SetBlobArg sets the BlobArg field's value.
func (s *InputService3TestShapeInputService3TestCaseOperation1Input) SetBlobArg(v []byte) *InputService3TestShapeInputService3TestCaseOperation1Input {
s.BlobArg = v
return s
}
// SetBlobMap sets the BlobMap field's value.
func (s *InputService3TestShapeInputService3TestCaseOperation1Input) SetBlobMap(v map[string][]byte) *InputService3TestShapeInputService3TestCaseOperation1Input {
s.BlobMap = v
return s
}
type InputService3TestShapeInputService3TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService3TestShapeInputService3TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
// BlobArg is automatically base64 encoded/decoded by the SDK.
BlobArg []byte `type:"blob"`
BlobMap map[string][]byte `type:"map"`
}
// SetBlobArg sets the BlobArg field's value.
func (s *InputService3TestShapeInputService3TestCaseOperation2Input) SetBlobArg(v []byte) *InputService3TestShapeInputService3TestCaseOperation2Input {
s.BlobArg = v
return s
}
// SetBlobMap sets the BlobMap field's value.
func (s *InputService3TestShapeInputService3TestCaseOperation2Input) SetBlobMap(v map[string][]byte) *InputService3TestShapeInputService3TestCaseOperation2Input {
s.BlobMap = v
return s
}
type InputService3TestShapeInputService3TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
// InputService4ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService4ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService4ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService4ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService4ProtocolTest client from just a session.
// svc := inputservice4protocoltest.New(mySession)
//
// // Create a InputService4ProtocolTest client with additional configuration
// svc := inputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService4ProtocolTest {
c := p.ClientConfig("inputservice4protocoltest", cfgs...)
return newInputService4ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService4ProtocolTest {
svc := &InputService4ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService4ProtocolTest",
ServiceID: "InputService4ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService4ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService4TestCaseOperation1 = "OperationName"
// InputService4TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService4TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService4TestCaseOperation1 for more information on using the InputService4TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService4TestCaseOperation1Request method.
// req, resp := client.InputService4TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService4TestCaseOperation1,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService4TestShapeInputService4TestCaseOperation1Input{}
}
output = &InputService4TestShapeInputService4TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService4TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService4TestCaseOperation1 for usage and error information.
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) {
req, out := c.InputService4TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService4TestCaseOperation1WithContext is the same as InputService4TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService4TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation1Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) {
req, out := c.InputService4TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService4TestShapeInputService4TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
ListParam [][]byte `type:"list"`
}
// SetListParam sets the ListParam field's value.
func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListParam(v [][]byte) *InputService4TestShapeInputService4TestCaseOperation1Input {
s.ListParam = v
return s
}
type InputService4TestShapeInputService4TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService5ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService5ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService5ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService5ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService5ProtocolTest client from just a session.
// svc := inputservice5protocoltest.New(mySession)
//
// // Create a InputService5ProtocolTest client with additional configuration
// svc := inputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService5ProtocolTest {
c := p.ClientConfig("inputservice5protocoltest", cfgs...)
return newInputService5ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService5ProtocolTest {
svc := &InputService5ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService5ProtocolTest",
ServiceID: "InputService5ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService5ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService5TestCaseOperation1 = "OperationName"
// InputService5TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation1 for more information on using the InputService5TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation1Request method.
// req, resp := client.InputService5TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation1Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation1 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) {
req, out := c.InputService5TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation1WithContext is the same as InputService5TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation1Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) {
req, out := c.InputService5TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService5TestCaseOperation2 = "OperationName"
// InputService5TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation2 for more information on using the InputService5TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation2Request method.
// req, resp := client.InputService5TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation2Request(input *InputService5TestShapeInputService5TestCaseOperation2Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation2,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation2Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation2 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation2(input *InputService5TestShapeInputService5TestCaseOperation2Input) (*InputService5TestShapeInputService5TestCaseOperation2Output, error) {
req, out := c.InputService5TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation2WithContext is the same as InputService5TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation2WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation2Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation2Output, error) {
req, out := c.InputService5TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService5TestCaseOperation3 = "OperationName"
// InputService5TestCaseOperation3Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation3 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation3 for more information on using the InputService5TestCaseOperation3
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation3Request method.
// req, resp := client.InputService5TestCaseOperation3Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation3Request(input *InputService5TestShapeInputService5TestCaseOperation3Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation3Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation3,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation3Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation3Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation3 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation3 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation3(input *InputService5TestShapeInputService5TestCaseOperation3Input) (*InputService5TestShapeInputService5TestCaseOperation3Output, error) {
req, out := c.InputService5TestCaseOperation3Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation3WithContext is the same as InputService5TestCaseOperation3 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation3 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation3WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation3Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation3Output, error) {
req, out := c.InputService5TestCaseOperation3Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService5TestCaseOperation4 = "OperationName"
// InputService5TestCaseOperation4Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation4 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation4 for more information on using the InputService5TestCaseOperation4
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation4Request method.
// req, resp := client.InputService5TestCaseOperation4Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation4Request(input *InputService5TestShapeInputService5TestCaseOperation4Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation4Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation4,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation4Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation4Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation4 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation4 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation4(input *InputService5TestShapeInputService5TestCaseOperation4Input) (*InputService5TestShapeInputService5TestCaseOperation4Output, error) {
req, out := c.InputService5TestCaseOperation4Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation4WithContext is the same as InputService5TestCaseOperation4 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation4 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation4WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation4Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation4Output, error) {
req, out := c.InputService5TestCaseOperation4Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService5TestCaseOperation5 = "OperationName"
// InputService5TestCaseOperation5Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation5 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation5 for more information on using the InputService5TestCaseOperation5
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation5Request method.
// req, resp := client.InputService5TestCaseOperation5Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation5Request(input *InputService5TestShapeInputService5TestCaseOperation5Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation5Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation5,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation5Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation5Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation5 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation5 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation5(input *InputService5TestShapeInputService5TestCaseOperation5Input) (*InputService5TestShapeInputService5TestCaseOperation5Output, error) {
req, out := c.InputService5TestCaseOperation5Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation5WithContext is the same as InputService5TestCaseOperation5 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation5 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation5WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation5Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation5Output, error) {
req, out := c.InputService5TestCaseOperation5Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService5TestCaseOperation6 = "OperationName"
// InputService5TestCaseOperation6Request generates a "aws/request.Request" representing the
// client's request for the InputService5TestCaseOperation6 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService5TestCaseOperation6 for more information on using the InputService5TestCaseOperation6
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService5TestCaseOperation6Request method.
// req, resp := client.InputService5TestCaseOperation6Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation6Request(input *InputService5TestShapeInputService5TestCaseOperation6Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation6Output) {
op := &request.Operation{
Name: opInputService5TestCaseOperation6,
HTTPPath: "/",
}
if input == nil {
input = &InputService5TestShapeInputService5TestCaseOperation6Input{}
}
output = &InputService5TestShapeInputService5TestCaseOperation6Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService5TestCaseOperation6 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService5TestCaseOperation6 for usage and error information.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation6(input *InputService5TestShapeInputService5TestCaseOperation6Input) (*InputService5TestShapeInputService5TestCaseOperation6Output, error) {
req, out := c.InputService5TestCaseOperation6Request(input)
return out, req.Send()
}
// InputService5TestCaseOperation6WithContext is the same as InputService5TestCaseOperation6 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService5TestCaseOperation6 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService5ProtocolTest) InputService5TestCaseOperation6WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation6Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation6Output, error) {
req, out := c.InputService5TestCaseOperation6Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService5TestShapeInputService5TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation1Input) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeInputService5TestCaseOperation1Input {
s.RecursiveStruct = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService5TestShapeInputService5TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation2Input) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeInputService5TestCaseOperation2Input {
s.RecursiveStruct = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
type InputService5TestShapeInputService5TestCaseOperation3Input struct {
_ struct{} `type:"structure"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation3Input) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeInputService5TestCaseOperation3Input {
s.RecursiveStruct = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation3Output struct {
_ struct{} `type:"structure"`
}
type InputService5TestShapeInputService5TestCaseOperation4Input struct {
_ struct{} `type:"structure"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation4Input) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeInputService5TestCaseOperation4Input {
s.RecursiveStruct = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation4Output struct {
_ struct{} `type:"structure"`
}
type InputService5TestShapeInputService5TestCaseOperation5Input struct {
_ struct{} `type:"structure"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation5Input) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeInputService5TestCaseOperation5Input {
s.RecursiveStruct = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation5Output struct {
_ struct{} `type:"structure"`
}
type InputService5TestShapeInputService5TestCaseOperation6Input struct {
_ struct{} `type:"structure"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeInputService5TestCaseOperation6Input) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeInputService5TestCaseOperation6Input {
s.RecursiveStruct = v
return s
}
type InputService5TestShapeInputService5TestCaseOperation6Output struct {
_ struct{} `type:"structure"`
}
type InputService5TestShapeRecursiveStructType struct {
_ struct{} `type:"structure"`
NoRecurse *string `type:"string"`
RecursiveList []*InputService5TestShapeRecursiveStructType `type:"list"`
RecursiveMap map[string]*InputService5TestShapeRecursiveStructType `type:"map"`
RecursiveStruct *InputService5TestShapeRecursiveStructType `type:"structure"`
}
// SetNoRecurse sets the NoRecurse field's value.
func (s *InputService5TestShapeRecursiveStructType) SetNoRecurse(v string) *InputService5TestShapeRecursiveStructType {
s.NoRecurse = &v
return s
}
// SetRecursiveList sets the RecursiveList field's value.
func (s *InputService5TestShapeRecursiveStructType) SetRecursiveList(v []*InputService5TestShapeRecursiveStructType) *InputService5TestShapeRecursiveStructType {
s.RecursiveList = v
return s
}
// SetRecursiveMap sets the RecursiveMap field's value.
func (s *InputService5TestShapeRecursiveStructType) SetRecursiveMap(v map[string]*InputService5TestShapeRecursiveStructType) *InputService5TestShapeRecursiveStructType {
s.RecursiveMap = v
return s
}
// SetRecursiveStruct sets the RecursiveStruct field's value.
func (s *InputService5TestShapeRecursiveStructType) SetRecursiveStruct(v *InputService5TestShapeRecursiveStructType) *InputService5TestShapeRecursiveStructType {
s.RecursiveStruct = v
return s
}
// InputService6ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService6ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService6ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService6ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService6ProtocolTest client from just a session.
// svc := inputservice6protocoltest.New(mySession)
//
// // Create a InputService6ProtocolTest client with additional configuration
// svc := inputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService6ProtocolTest {
c := p.ClientConfig("inputservice6protocoltest", cfgs...)
return newInputService6ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService6ProtocolTest {
svc := &InputService6ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService6ProtocolTest",
ServiceID: "InputService6ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService6ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService6TestCaseOperation1 = "OperationName"
// InputService6TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService6TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService6TestCaseOperation1 for more information on using the InputService6TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService6TestCaseOperation1Request method.
// req, resp := client.InputService6TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService6TestCaseOperation1,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService6TestShapeInputService6TestCaseOperation1Input{}
}
output = &InputService6TestShapeInputService6TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService6TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService6TestCaseOperation1 for usage and error information.
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) {
req, out := c.InputService6TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService6TestCaseOperation1WithContext is the same as InputService6TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService6TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1WithContext(ctx aws.Context, input *InputService6TestShapeInputService6TestCaseOperation1Input, opts ...request.Option) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) {
req, out := c.InputService6TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService6TestShapeInputService6TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Map map[string]*string `type:"map"`
}
// SetMap sets the Map field's value.
func (s *InputService6TestShapeInputService6TestCaseOperation1Input) SetMap(v map[string]*string) *InputService6TestShapeInputService6TestCaseOperation1Input {
s.Map = v
return s
}
type InputService6TestShapeInputService6TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
// InputService7ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService7ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService7ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService7ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService7ProtocolTest client from just a session.
// svc := inputservice7protocoltest.New(mySession)
//
// // Create a InputService7ProtocolTest client with additional configuration
// svc := inputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService7ProtocolTest {
c := p.ClientConfig("inputservice7protocoltest", cfgs...)
return newInputService7ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService7ProtocolTest {
svc := &InputService7ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService7ProtocolTest",
ServiceID: "InputService7ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService7ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService7TestCaseOperation1 = "OperationName"
// InputService7TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService7TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService7TestCaseOperation1 for more information on using the InputService7TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService7TestCaseOperation1Request method.
// req, resp := client.InputService7TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService7TestCaseOperation1,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService7TestShapeInputService7TestCaseOperation1Input{}
}
output = &InputService7TestShapeInputService7TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService7TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService7TestCaseOperation1 for usage and error information.
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) {
req, out := c.InputService7TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService7TestCaseOperation1WithContext is the same as InputService7TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService7TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation1Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) {
req, out := c.InputService7TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService7TestCaseOperation2 = "OperationName"
// InputService7TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService7TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService7TestCaseOperation2 for more information on using the InputService7TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService7TestCaseOperation2Request method.
// req, resp := client.InputService7TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService7ProtocolTest) InputService7TestCaseOperation2Request(input *InputService7TestShapeInputService7TestCaseOperation2Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService7TestCaseOperation2,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService7TestShapeInputService7TestCaseOperation2Input{}
}
output = &InputService7TestShapeInputService7TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService7TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService7TestCaseOperation2 for usage and error information.
func (c *InputService7ProtocolTest) InputService7TestCaseOperation2(input *InputService7TestShapeInputService7TestCaseOperation2Input) (*InputService7TestShapeInputService7TestCaseOperation2Output, error) {
req, out := c.InputService7TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService7TestCaseOperation2WithContext is the same as InputService7TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService7TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService7ProtocolTest) InputService7TestCaseOperation2WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation2Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation2Output, error) {
req, out := c.InputService7TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService7TestShapeInputService7TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Token *string `type:"string" idempotencyToken:"true"`
}
// SetToken sets the Token field's value.
func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetToken(v string) *InputService7TestShapeInputService7TestCaseOperation1Input {
s.Token = &v
return s
}
type InputService7TestShapeInputService7TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService7TestShapeInputService7TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
Token *string `type:"string" idempotencyToken:"true"`
}
// SetToken sets the Token field's value.
func (s *InputService7TestShapeInputService7TestCaseOperation2Input) SetToken(v string) *InputService7TestShapeInputService7TestCaseOperation2Input {
s.Token = &v
return s
}
type InputService7TestShapeInputService7TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
// InputService8ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService8ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService8ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService8ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService8ProtocolTest client from just a session.
// svc := inputservice8protocoltest.New(mySession)
//
// // Create a InputService8ProtocolTest client with additional configuration
// svc := inputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService8ProtocolTest {
c := p.ClientConfig("inputservice8protocoltest", cfgs...)
return newInputService8ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService8ProtocolTest {
svc := &InputService8ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService8ProtocolTest",
ServiceID: "InputService8ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-01-01",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService8ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService8TestCaseOperation1 = "OperationName"
// InputService8TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService8TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService8TestCaseOperation1 for more information on using the InputService8TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService8TestCaseOperation1Request method.
// req, resp := client.InputService8TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService8TestCaseOperation1,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService8TestShapeInputService8TestCaseOperation1Input{}
}
output = &InputService8TestShapeInputService8TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService8TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService8TestCaseOperation1 for usage and error information.
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) {
req, out := c.InputService8TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService8TestCaseOperation1WithContext is the same as InputService8TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService8TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation1Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) {
req, out := c.InputService8TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService8TestCaseOperation2 = "OperationName"
// InputService8TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService8TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService8TestCaseOperation2 for more information on using the InputService8TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService8TestCaseOperation2Request method.
// req, resp := client.InputService8TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService8ProtocolTest) InputService8TestCaseOperation2Request(input *InputService8TestShapeInputService8TestCaseOperation2Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService8TestCaseOperation2,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService8TestShapeInputService8TestCaseOperation2Input{}
}
output = &InputService8TestShapeInputService8TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// InputService8TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService8TestCaseOperation2 for usage and error information.
func (c *InputService8ProtocolTest) InputService8TestCaseOperation2(input *InputService8TestShapeInputService8TestCaseOperation2Input) (*InputService8TestShapeInputService8TestCaseOperation2Output, error) {
req, out := c.InputService8TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService8TestCaseOperation2WithContext is the same as InputService8TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService8TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService8ProtocolTest) InputService8TestCaseOperation2WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation2Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation2Output, error) {
req, out := c.InputService8TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService8TestShapeInputService8TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
FooEnum *string `type:"string" enum:"InputService8TestShapeEnumType"`
ListEnums []*string `type:"list"`
}
// SetFooEnum sets the FooEnum field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetFooEnum(v string) *InputService8TestShapeInputService8TestCaseOperation1Input {
s.FooEnum = &v
return s
}
// SetListEnums sets the ListEnums field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetListEnums(v []*string) *InputService8TestShapeInputService8TestCaseOperation1Input {
s.ListEnums = v
return s
}
type InputService8TestShapeInputService8TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService8TestShapeInputService8TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
FooEnum *string `type:"string" enum:"InputService8TestShapeEnumType"`
ListEnums []*string `type:"list"`
}
// SetFooEnum sets the FooEnum field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation2Input) SetFooEnum(v string) *InputService8TestShapeInputService8TestCaseOperation2Input {
s.FooEnum = &v
return s
}
// SetListEnums sets the ListEnums field's value.
func (s *InputService8TestShapeInputService8TestCaseOperation2Input) SetListEnums(v []*string) *InputService8TestShapeInputService8TestCaseOperation2Input {
s.ListEnums = v
return s
}
type InputService8TestShapeInputService8TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
const (
// EnumTypeFoo is a InputService8TestShapeEnumType enum value
EnumTypeFoo = "foo"
// EnumTypeBar is a InputService8TestShapeEnumType enum value
EnumTypeBar = "bar"
)
// InputService8TestShapeEnumType_Values returns all elements of the InputService8TestShapeEnumType enum
func InputService8TestShapeEnumType_Values() []string {
return []string{
EnumTypeFoo,
EnumTypeBar,
}
}
// InputService9ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// InputService9ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type InputService9ProtocolTest struct {
*client.Client
}
// New creates a new instance of the InputService9ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a InputService9ProtocolTest client from just a session.
// svc := inputservice9protocoltest.New(mySession)
//
// // Create a InputService9ProtocolTest client with additional configuration
// svc := inputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewInputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService9ProtocolTest {
c := p.ClientConfig("inputservice9protocoltest", cfgs...)
return newInputService9ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newInputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *InputService9ProtocolTest {
svc := &InputService9ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "InputService9ProtocolTest",
ServiceID: "InputService9ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
JSONVersion: "1.1",
TargetPrefix: "com.amazonaws.foo",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a InputService9ProtocolTest operation and runs any
// custom request initialization.
func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opInputService9TestCaseOperation1 = "StaticOp"
// InputService9TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the InputService9TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService9TestCaseOperation1 for more information on using the InputService9TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService9TestCaseOperation1Request method.
// req, resp := client.InputService9TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputService9TestCaseOperation1Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) {
op := &request.Operation{
Name: opInputService9TestCaseOperation1,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService9TestShapeInputService9TestCaseOperation1Input{}
}
output = &InputService9TestShapeInputService9TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
req.Handlers.Build.PushBackNamed(protocol.NewHostPrefixHandler("data-", nil))
req.Handlers.Build.PushBackNamed(protocol.ValidateEndpointHostHandler)
return
}
// InputService9TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService9TestCaseOperation1 for usage and error information.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputService9TestCaseOperation1Input) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) {
req, out := c.InputService9TestCaseOperation1Request(input)
return out, req.Send()
}
// InputService9TestCaseOperation1WithContext is the same as InputService9TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService9TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation1WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation1Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) {
req, out := c.InputService9TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opInputService9TestCaseOperation2 = "MemberRefOp"
// InputService9TestCaseOperation2Request generates a "aws/request.Request" representing the
// client's request for the InputService9TestCaseOperation2 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See InputService9TestCaseOperation2 for more information on using the InputService9TestCaseOperation2
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the InputService9TestCaseOperation2Request method.
// req, resp := client.InputService9TestCaseOperation2Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputService9TestCaseOperation2Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) {
op := &request.Operation{
Name: opInputService9TestCaseOperation2,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &InputService9TestShapeInputService9TestCaseOperation2Input{}
}
output = &InputService9TestShapeInputService9TestCaseOperation2Output{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
req.Handlers.Build.PushBackNamed(protocol.NewHostPrefixHandler("foo-{Name}.", input.hostLabels))
req.Handlers.Build.PushBackNamed(protocol.ValidateEndpointHostHandler)
return
}
// InputService9TestCaseOperation2 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation InputService9TestCaseOperation2 for usage and error information.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *InputService9TestShapeInputService9TestCaseOperation2Input) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) {
req, out := c.InputService9TestCaseOperation2Request(input)
return out, req.Send()
}
// InputService9TestCaseOperation2WithContext is the same as InputService9TestCaseOperation2 with the addition of
// the ability to pass a context and additional request options.
//
// See InputService9TestCaseOperation2 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *InputService9ProtocolTest) InputService9TestCaseOperation2WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation2Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) {
req, out := c.InputService9TestCaseOperation2Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type InputService9TestShapeInputService9TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
Name *string `type:"string"`
}
// SetName sets the Name field's value.
func (s *InputService9TestShapeInputService9TestCaseOperation1Input) SetName(v string) *InputService9TestShapeInputService9TestCaseOperation1Input {
s.Name = &v
return s
}
type InputService9TestShapeInputService9TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
}
type InputService9TestShapeInputService9TestCaseOperation2Input struct {
_ struct{} `type:"structure"`
// Name is a required field
Name *string `type:"string" required:"true"`
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *InputService9TestShapeInputService9TestCaseOperation2Input) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "InputService9TestShapeInputService9TestCaseOperation2Input"}
if s.Name == nil {
invalidParams.Add(request.NewErrParamRequired("Name"))
}
if s.Name != nil && len(*s.Name) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Name", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetName sets the Name field's value.
func (s *InputService9TestShapeInputService9TestCaseOperation2Input) SetName(v string) *InputService9TestShapeInputService9TestCaseOperation2Input {
s.Name = &v
return s
}
func (s *InputService9TestShapeInputService9TestCaseOperation2Input) hostLabels() map[string]string {
return map[string]string{
"Name": aws.StringValue(s.Name),
}
}
type InputService9TestShapeInputService9TestCaseOperation2Output struct {
_ struct{} `type:"structure"`
}
//
// Tests begin here
//
func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) {
svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService1TestShapeInputService1TestCaseOperation1Input{
Name: aws.String("myname"),
}
req, _ := svc.InputService1TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"Name": "myname"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService2ProtocolTestTimestampValuesCase1(t *testing.T) {
svc := NewInputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService2TestShapeInputService2TestCaseOperation1Input{
TimeArg: aws.Time(time.Unix(1422172800, 0)),
TimeCustom: aws.Time(time.Unix(1422172800, 0)),
TimeFormat: aws.Time(time.Unix(1422172800, 0)),
}
req, _ := svc.InputService2TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"TimeArg": 1422172800, "TimeCustom": "Sun, 25 Jan 2015 08:00:00 GMT", "TimeFormat": "Sun, 25 Jan 2015 08:00:00 GMT"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService3ProtocolTestBase64EncodedBlobsCase1(t *testing.T) {
svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService3TestShapeInputService3TestCaseOperation1Input{
BlobArg: []byte("foo"),
}
req, _ := svc.InputService3TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"BlobArg": "Zm9v"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService3ProtocolTestBase64EncodedBlobsCase2(t *testing.T) {
svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService3TestShapeInputService3TestCaseOperation2Input{
BlobMap: map[string][]byte{
"key1": []byte("foo"),
"key2": []byte("bar"),
},
}
req, _ := svc.InputService3TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"BlobMap": {"key1": "Zm9v", "key2": "YmFy"}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService4ProtocolTestNestedBlobsCase1(t *testing.T) {
svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService4TestShapeInputService4TestCaseOperation1Input{
ListParam: [][]byte{
[]byte("foo"),
[]byte("bar"),
},
}
req, _ := svc.InputService4TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"ListParam": ["Zm9v", "YmFy"]}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService5ProtocolTestRecursiveShapesCase1(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation1Input{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
NoRecurse: aws.String("foo"),
},
}
req, _ := svc.InputService5TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"RecursiveStruct": {"NoRecurse": "foo"}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService5ProtocolTestRecursiveShapesCase2(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation2Input{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
NoRecurse: aws.String("foo"),
},
},
}
req, _ := svc.InputService5TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"RecursiveStruct": {"RecursiveStruct": {"NoRecurse": "foo"}}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService5ProtocolTestRecursiveShapesCase3(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation3Input{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
NoRecurse: aws.String("foo"),
},
},
},
},
}
req, _ := svc.InputService5TestCaseOperation3Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"RecursiveStruct": {"RecursiveStruct": {"RecursiveStruct": {"RecursiveStruct": {"NoRecurse": "foo"}}}}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService5ProtocolTestRecursiveShapesCase4(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation4Input{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveList: []*InputService5TestShapeRecursiveStructType{
{
NoRecurse: aws.String("foo"),
},
{
NoRecurse: aws.String("bar"),
},
},
},
}
req, _ := svc.InputService5TestCaseOperation4Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"RecursiveStruct": {"RecursiveList": [{"NoRecurse": "foo"}, {"NoRecurse": "bar"}]}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService5ProtocolTestRecursiveShapesCase5(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation5Input{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveList: []*InputService5TestShapeRecursiveStructType{
{
NoRecurse: aws.String("foo"),
},
{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
NoRecurse: aws.String("bar"),
},
},
},
},
}
req, _ := svc.InputService5TestCaseOperation5Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"RecursiveStruct": {"RecursiveList": [{"NoRecurse": "foo"}, {"RecursiveStruct": {"NoRecurse": "bar"}}]}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService5ProtocolTestRecursiveShapesCase6(t *testing.T) {
svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService5TestShapeInputService5TestCaseOperation6Input{
RecursiveStruct: &InputService5TestShapeRecursiveStructType{
RecursiveMap: map[string]*InputService5TestShapeRecursiveStructType{
"bar": {
NoRecurse: aws.String("bar"),
},
"foo": {
NoRecurse: aws.String("foo"),
},
},
},
}
req, _ := svc.InputService5TestCaseOperation6Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"RecursiveStruct": {"RecursiveMap": {"foo": {"NoRecurse": "foo"}, "bar": {"NoRecurse": "bar"}}}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService6ProtocolTestEmptyMapsCase1(t *testing.T) {
svc := NewInputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService6TestShapeInputService6TestCaseOperation1Input{
Map: map[string]*string{},
}
req, _ := svc.InputService6TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"Map": {}}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService7ProtocolTestIdempotencyTokenAutoFillCase1(t *testing.T) {
svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService7TestShapeInputService7TestCaseOperation1Input{
Token: aws.String("abc123"),
}
req, _ := svc.InputService7TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"Token": "abc123"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService7ProtocolTestIdempotencyTokenAutoFillCase2(t *testing.T) {
svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService7TestShapeInputService7TestCaseOperation2Input{}
req, _ := svc.InputService7TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"Token": "00000000-0000-4000-8000-000000000000"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService8ProtocolTestEnumCase1(t *testing.T) {
svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService8TestShapeInputService8TestCaseOperation1Input{
FooEnum: aws.String("foo"),
ListEnums: []*string{
aws.String("foo"),
aws.String(""),
aws.String("bar"),
},
}
req, _ := svc.InputService8TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"FooEnum": "foo", "ListEnums": ["foo", "", "bar"]}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService8ProtocolTestEnumCase2(t *testing.T) {
svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
input := &InputService8TestShapeInputService8TestCaseOperation2Input{}
req, _ := svc.InputService8TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert URL
awstesting.AssertURL(t, "https://test/", r.URL.String())
// assert headers
}
func TestInputService9ProtocolTestEndpointHostTraitStaticPrefixCase1(t *testing.T) {
svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://service.region.amazonaws.com")})
input := &InputService9TestShapeInputService9TestCaseOperation1Input{
Name: aws.String("myname"),
}
req, _ := svc.InputService9TestCaseOperation1Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"Name": "myname"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://data-service.region.amazonaws.com/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.StaticOp", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestInputService9ProtocolTestEndpointHostTraitStaticPrefixCase2(t *testing.T) {
svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://service.region.amazonaws.com")})
input := &InputService9TestShapeInputService9TestCaseOperation2Input{
Name: aws.String("myname"),
}
req, _ := svc.InputService9TestCaseOperation2Request(input)
r := req.HTTPRequest
// build request
req.Build()
if req.Error != nil {
t.Errorf("expect no error, got %v", req.Error)
}
// assert body
if r.Body == nil {
t.Errorf("expect body not to be nil")
}
body, _ := ioutil.ReadAll(r.Body)
awstesting.AssertJSON(t, `{"Name": "myname"}`, util.Trim(string(body)))
// assert URL
awstesting.AssertURL(t, "https://foo-myname.service.region.amazonaws.com/", r.URL.String())
// assert headers
if e, a := "application/x-amz-json-1.1", r.Header.Get("Content-Type"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "com.amazonaws.foo.MemberRefOp", r.Header.Get("X-Amz-Target"); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
| 2,934 |
session-manager-plugin | aws | Go | // Package jsonrpc provides JSON RPC utilities for serialization of AWS
// requests and responses.
package jsonrpc
//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/input/json.json build_test.go
//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/output/json.json unmarshal_test.go
import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
"github.com/aws/aws-sdk-go/private/protocol/rest"
)
var emptyJSON = []byte("{}")
// BuildHandler is a named request handler for building jsonrpc protocol
// requests
var BuildHandler = request.NamedHandler{
Name: "awssdk.jsonrpc.Build",
Fn: Build,
}
// UnmarshalHandler is a named request handler for unmarshaling jsonrpc
// protocol requests
var UnmarshalHandler = request.NamedHandler{
Name: "awssdk.jsonrpc.Unmarshal",
Fn: Unmarshal,
}
// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc
// protocol request metadata
var UnmarshalMetaHandler = request.NamedHandler{
Name: "awssdk.jsonrpc.UnmarshalMeta",
Fn: UnmarshalMeta,
}
// Build builds a JSON payload for a JSON RPC request.
func Build(req *request.Request) {
var buf []byte
var err error
if req.ParamsFilled() {
buf, err = jsonutil.BuildJSON(req.Params)
if err != nil {
req.Error = awserr.New(request.ErrCodeSerialization, "failed encoding JSON RPC request", err)
return
}
} else {
buf = emptyJSON
}
if req.ClientInfo.TargetPrefix != "" || string(buf) != "{}" {
req.SetBufferBody(buf)
}
if req.ClientInfo.TargetPrefix != "" {
target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name
req.HTTPRequest.Header.Add("X-Amz-Target", target)
}
// Only set the content type if one is not already specified and an
// JSONVersion is specified.
if ct, v := req.HTTPRequest.Header.Get("Content-Type"), req.ClientInfo.JSONVersion; len(ct) == 0 && len(v) != 0 {
jsonVersion := req.ClientInfo.JSONVersion
req.HTTPRequest.Header.Set("Content-Type", "application/x-amz-json-"+jsonVersion)
}
}
// Unmarshal unmarshals a response for a JSON RPC service.
func Unmarshal(req *request.Request) {
defer req.HTTPResponse.Body.Close()
if req.DataFilled() {
err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body)
if err != nil {
req.Error = awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization, "failed decoding JSON RPC response", err),
req.HTTPResponse.StatusCode,
req.RequestID,
)
}
}
return
}
// UnmarshalMeta unmarshals headers from a response for a JSON RPC service.
func UnmarshalMeta(req *request.Request) {
rest.UnmarshalMeta(req)
}
| 89 |
session-manager-plugin | aws | Go | package jsonrpc
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
)
// UnmarshalTypedError provides unmarshaling errors API response errors
// for both typed and untyped errors.
type UnmarshalTypedError struct {
exceptions map[string]func(protocol.ResponseMetadata) error
}
// NewUnmarshalTypedError returns an UnmarshalTypedError initialized for the
// set of exception names to the error unmarshalers
func NewUnmarshalTypedError(exceptions map[string]func(protocol.ResponseMetadata) error) *UnmarshalTypedError {
return &UnmarshalTypedError{
exceptions: exceptions,
}
}
// UnmarshalError attempts to unmarshal the HTTP response error as a known
// error type. If unable to unmarshal the error type, the generic SDK error
// type will be used.
func (u *UnmarshalTypedError) UnmarshalError(
resp *http.Response,
respMeta protocol.ResponseMetadata,
) (error, error) {
var buf bytes.Buffer
var jsonErr jsonErrorResponse
teeReader := io.TeeReader(resp.Body, &buf)
err := jsonutil.UnmarshalJSONError(&jsonErr, teeReader)
if err != nil {
return nil, err
}
body := ioutil.NopCloser(&buf)
// Code may be separated by hash(#), with the last element being the code
// used by the SDK.
codeParts := strings.SplitN(jsonErr.Code, "#", 2)
code := codeParts[len(codeParts)-1]
msg := jsonErr.Message
if fn, ok := u.exceptions[code]; ok {
// If exception code is know, use associated constructor to get a value
// for the exception that the JSON body can be unmarshaled into.
v := fn(respMeta)
err := jsonutil.UnmarshalJSONCaseInsensitive(v, body)
if err != nil {
return nil, err
}
return v, nil
}
// fallback to unmodeled generic exceptions
return awserr.NewRequestFailure(
awserr.New(code, msg, nil),
respMeta.StatusCode,
respMeta.RequestID,
), nil
}
// UnmarshalErrorHandler is a named request handler for unmarshaling jsonrpc
// protocol request errors
var UnmarshalErrorHandler = request.NamedHandler{
Name: "awssdk.jsonrpc.UnmarshalError",
Fn: UnmarshalError,
}
// UnmarshalError unmarshals an error response for a JSON RPC service.
func UnmarshalError(req *request.Request) {
defer req.HTTPResponse.Body.Close()
var jsonErr jsonErrorResponse
err := jsonutil.UnmarshalJSONError(&jsonErr, req.HTTPResponse.Body)
if err != nil {
req.Error = awserr.NewRequestFailure(
awserr.New(request.ErrCodeSerialization,
"failed to unmarshal error message", err),
req.HTTPResponse.StatusCode,
req.RequestID,
)
return
}
codes := strings.SplitN(jsonErr.Code, "#", 2)
req.Error = awserr.NewRequestFailure(
awserr.New(codes[len(codes)-1], jsonErr.Message, nil),
req.HTTPResponse.StatusCode,
req.RequestID,
)
}
type jsonErrorResponse struct {
Code string `json:"__type"`
Message string `json:"message"`
}
| 108 |