File: middleware_http_logging.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 (75 lines) | stat: -rw-r--r-- 2,085 bytes parent folder | download | duplicates (5)
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
package http

import (
	"context"
	"fmt"
	"net/http/httputil"

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

// RequestResponseLogger is a deserialize middleware that will log the request and response HTTP messages and optionally
// their respective bodies. Will not perform any logging if none of the options are set.
type RequestResponseLogger struct {
	LogRequest         bool
	LogRequestWithBody bool

	LogResponse         bool
	LogResponseWithBody bool
}

// ID is the middleware identifier.
func (r *RequestResponseLogger) ID() string {
	return "RequestResponseLogger"
}

// HandleDeserialize will log the request and response HTTP messages if configured accordingly.
func (r *RequestResponseLogger) HandleDeserialize(
	ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler,
) (
	out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
	logger := middleware.GetLogger(ctx)

	if r.LogRequest || r.LogRequestWithBody {
		smithyRequest, ok := in.Request.(*Request)
		if !ok {
			return out, metadata, fmt.Errorf("unknown transport type %T", in)
		}

		rc := smithyRequest.Build(ctx)
		reqBytes, err := httputil.DumpRequestOut(rc, r.LogRequestWithBody)
		if err != nil {
			return out, metadata, err
		}

		logger.Logf(logging.Debug, "Request\n%v", string(reqBytes))

		if r.LogRequestWithBody {
			smithyRequest, err = smithyRequest.SetStream(rc.Body)
			if err != nil {
				return out, metadata, err
			}
			in.Request = smithyRequest
		}
	}

	out, metadata, err = next.HandleDeserialize(ctx, in)

	if (err == nil) && (r.LogResponse || r.LogResponseWithBody) {
		smithyResponse, ok := out.RawResponse.(*Response)
		if !ok {
			return out, metadata, fmt.Errorf("unknown transport type %T", out.RawResponse)
		}

		respBytes, err := httputil.DumpResponse(smithyResponse.Response, r.LogResponseWithBody)
		if err != nil {
			return out, metadata, fmt.Errorf("failed to dump response %w", err)
		}

		logger.Logf(logging.Debug, "Response\n%v", string(respBytes))
	}

	return out, metadata, err
}