Menu
AWS X-Ray
Developer Guide

Instrumenting Incoming HTTP Requests with the X-Ray SDK for Go

You can use the X-Ray SDK to trace incoming HTTP requests that your application serves on an EC2 instance in Amazon EC2, AWS Elastic Beanstalk, or Amazon ECS.

Use xray.handler to instrument incoming HTTP requests. The X-Ray SDK for Go implements the standard Go library http.handler interface in the xay.Handler class to intercept web requests. The xay.Handler class wraps the provided http.handler with xray.Capture using the request's context, parsing the incoming headers, adding response headers if needed, and sets HTTP-specific trace fields.

When you use this class to handle HTTP requests and responses, the X-Ray SDK for Go creates a segment for each sampled request. Any segments created by additional instrumentation become subsegments of the request-level segment that provides information about the HTTP request and response, including timing, method, and disposition of the request.

The following example intercepts requests on port 8000 and returns "Hello!" as a response. It creates the segment myApp and instruments calls through any application.

func main() {
  http.Handle("/", xray.Handler(xray.NewFixedSegmentNamer("myApp"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello!"))
  })))

  http.ListenAndServe(":8000", nil)
}

Each segment has a name that identifies your application in the service map. The segment can be named statically, or you can configure the SDK to name it dynamically based on the host header in the incoming request. Dynamic naming lets you group traces based on the domain name in the request, and apply a default name if the name doesn't match an expected pattern (for example, if the host header is forged).

Forwarded Requests

If a load balancer or other intermediary forwards a request to your application, X-Ray takes the client IP from the X-Forwarded-For header in the request instead of from the source IP in the IP packet. The client IP that is recorded for a forwarded request can be forged, so it should not be trusted.

When a request is forwarded, the SDK sets an additional field in the segment to indicate this. If the segment contains the field x_forwarded_for set to true, the client IP was taken from the X-Forwarded-For header in the HTTP request.

The handler creates a segment for each incoming request with an http block that contains the following information:

  • HTTP method – GET, POST, PUT, DELETE, etc.

  • Client address – The IP address of the client that sent the request.

  • Response code – The HTTP response code for the completed request.

  • Timing – The start time (when the request was received) and end time (when the response was sent).

  • User agent — The user-agent from the request.

  • Content length — The content-length from the response.

Sections