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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
package http
import (
"context"
"fmt"
"net/http"
"os"
"strconv"
"github.com/aws/smithy-go/middleware"
)
func ExampleResponse_deserializeMiddleware() {
// Create the stack and provide the function that will create a new Request
// when the SerializeStep is invoked.
stack := middleware.NewStack("deserialize example", NewStackRequest)
type Output struct {
FooName string
BarCount int
}
// Add a Deserialize middleware that will extract the RawResponse and
// deserialize into the target output type.
stack.Deserialize.Add(middleware.DeserializeMiddlewareFunc("example deserialize",
func(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return middleware.DeserializeOutput{}, metadata, err
}
metadata.Set("example-meta", "meta-value")
rawResp := out.RawResponse.(*Response)
out.Result = &Output{
FooName: rawResp.Header.Get("foo-name"),
BarCount: func() int {
v, _ := strconv.Atoi(rawResp.Header.Get("bar-count"))
return v
}(),
}
return out, metadata, nil
}),
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,
) {
resp := &http.Response{
StatusCode: 200,
Header: http.Header{},
}
resp.Header.Set("foo-name", "abc")
resp.Header.Set("bar-count", "123")
// The handler's returned response will be available as the
// DeserializeOutput.RawResponse field.
return &Response{
Response: resp,
}, metadata, nil
})
// Use the stack to decorate the handler then invoke the decorated handler
// with the inputs.
handler := middleware.DecorateHandler(mockHandler, stack)
result, metadata, err := handler.Handle(context.Background(), struct{}{})
if err != nil {
fmt.Fprintf(os.Stderr, "failed to call operation, %v", err)
return
}
// Cast the result returned by the handler to the expected Output type.
res := result.(*Output)
fmt.Println("FooName", res.FooName)
fmt.Println("BarCount", res.BarCount)
fmt.Println("Metadata:", "example-meta:", metadata.Get("example-meta"))
// Output:
// FooName abc
// BarCount 123
// Metadata: example-meta: meta-value
}
|