File: serialize_example_test.go

package info (click to toggle)
golang-github-aws-smithy-go 1.20.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,116 kB
  • sloc: java: 19,678; xml: 166; sh: 131; makefile: 70
file content (70 lines) | stat: -rw-r--r-- 1,941 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package http

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/aws/smithy-go/middleware"
)

func ExampleRequest_serializeMiddleware() {
	// Create the stack and provide the function that will create a new Request
	// when the SerializeStep is invoked.
	stack := middleware.NewStack("serialize example", NewStackRequest)

	type Input struct {
		FooName  string
		BarCount int
	}

	// Add the serialization middleware.
	stack.Serialize.Add(middleware.SerializeMiddlewareFunc("example serialize",
		func(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
			middleware.SerializeOutput, middleware.Metadata, error,
		) {
			req := in.Request.(*Request)
			input := in.Parameters.(*Input)

			req.Header.Set("foo-name", input.FooName)
			req.Header.Set("bar-count", strconv.Itoa(input.BarCount))

			return next.HandleSerialize(ctx, in)
		}),
		middleware.After,
	)

	// Mock example handler taking the request input and returning a response
	mockHandler := middleware.HandlerFunc(func(ctx context.Context, in interface{}) (
		output interface{}, metadata middleware.Metadata, err error,
	) {
		// Returns the standard http Request for the handler to make request
		// using standard http compatible client.
		req := in.(*Request).Build(context.Background())

		fmt.Println("foo-name", req.Header.Get("foo-name"))
		fmt.Println("bar-count", req.Header.Get("bar-count"))

		return &Response{
			Response: &http.Response{
				StatusCode: 200,
				Header:     http.Header{},
			},
		}, metadata, nil
	})

	// Use the stack to decorate the handler then invoke the decorated handler
	// with the inputs.
	handler := middleware.DecorateHandler(mockHandler, stack)
	_, _, err := handler.Handle(context.Background(), &Input{FooName: "abc", BarCount: 123})
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to call operation, %v", err)
		return
	}

	// Output:
	// foo-name abc
	// bar-count 123
}