...

Source file src/github.com/aws/smithy-go/transport/http/serialize_example_test.go

Documentation: github.com/aws/smithy-go/transport/http

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"os"
     8  	"strconv"
     9  
    10  	"github.com/aws/smithy-go/middleware"
    11  )
    12  
    13  func ExampleRequest_serializeMiddleware() {
    14  	// Create the stack and provide the function that will create a new Request
    15  	// when the SerializeStep is invoked.
    16  	stack := middleware.NewStack("serialize example", NewStackRequest)
    17  
    18  	type Input struct {
    19  		FooName  string
    20  		BarCount int
    21  	}
    22  
    23  	// Add the serialization middleware.
    24  	stack.Serialize.Add(middleware.SerializeMiddlewareFunc("example serialize",
    25  		func(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
    26  			middleware.SerializeOutput, middleware.Metadata, error,
    27  		) {
    28  			req := in.Request.(*Request)
    29  			input := in.Parameters.(*Input)
    30  
    31  			req.Header.Set("foo-name", input.FooName)
    32  			req.Header.Set("bar-count", strconv.Itoa(input.BarCount))
    33  
    34  			return next.HandleSerialize(ctx, in)
    35  		}),
    36  		middleware.After,
    37  	)
    38  
    39  	// Mock example handler taking the request input and returning a response
    40  	mockHandler := middleware.HandlerFunc(func(ctx context.Context, in interface{}) (
    41  		output interface{}, metadata middleware.Metadata, err error,
    42  	) {
    43  		// Returns the standard http Request for the handler to make request
    44  		// using standard http compatible client.
    45  		req := in.(*Request).Build(context.Background())
    46  
    47  		fmt.Println("foo-name", req.Header.Get("foo-name"))
    48  		fmt.Println("bar-count", req.Header.Get("bar-count"))
    49  
    50  		return &Response{
    51  			Response: &http.Response{
    52  				StatusCode: 200,
    53  				Header:     http.Header{},
    54  			},
    55  		}, metadata, nil
    56  	})
    57  
    58  	// Use the stack to decorate the handler then invoke the decorated handler
    59  	// with the inputs.
    60  	handler := middleware.DecorateHandler(mockHandler, stack)
    61  	_, _, err := handler.Handle(context.Background(), &Input{FooName: "abc", BarCount: 123})
    62  	if err != nil {
    63  		fmt.Fprintf(os.Stderr, "failed to call operation, %v", err)
    64  		return
    65  	}
    66  
    67  	// Output:
    68  	// foo-name abc
    69  	// bar-count 123
    70  }
    71  

View as plain text