-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
81 lines (71 loc) · 2.36 KB
/
example.go
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
package main
import (
"context"
"fmt"
"log"
"net/http/httptest"
"os"
"time"
"github.com/aws/aws-xray-sdk-go/xray"
"github.com/gogama/aws-xray-httpx/httpxxray"
"github.com/gogama/httpx"
"github.com/gogama/httpx/racing"
"github.com/gogama/httpx/request"
"github.com/gogama/httpx/timeout"
"github.com/gogama/testserv"
)
// Before running the program, make sure you have the X-Ray daemon installed and
// running (see AWS X-Ray documentation for more detail).
//
// e.g.
//
// $ xray -o -n us-west-2 -f /tmp/xray.log &
func main() {
// Start a test HTTPS server which will cause the following:
// 1. On first request, return 503 Service Unavailable error (retryable)
// 2. On second request, cause a timeout waiting for request headers.
// 3. On third request, return a 429 Too Many Requests error (retryable)
// 4. On fourth request, caues a timeout reading response body.
// 5. On the fifth request, uneventfully serve a success response.
server := httptest.NewTLSServer(&testserv.Handler{
Inst: []testserv.Instruction{
{StatusCode: 503},
{StatusCode: 500, HeaderDelay: 5 * time.Second},
{StatusCode: 429, Body: []byte(`You makin' me crazy.`)},
{StatusCode: 200, BodyDelay: 50 * time.Millisecond, BodyServiceTime: 5 * time.Second, Body: []byte("I will eventually finish serving this sentence.")},
{StatusCode: 200, Body: []byte("Success!")},
},
})
defer server.Close()
// Start an X-Ray segment for the example application.
ctx, seg := xray.BeginSegment(context.Background(), "example/normal")
defer func() {
seg.Close(nil)
}()
// Create the robust httpx.Client and install the X-Ray plugin.
cl := &httpx.Client{
HTTPDoer: server.Client(),
TimeoutPolicy: timeout.Fixed(100 * time.Millisecond),
RacingPolicy: racing.NewPolicy(
racing.NewStaticScheduler(50*time.Millisecond, 99*time.Millisecond),
racing.AlwaysStart,
),
}
logger := log.New(os.Stdout, "httpxxray", log.Ldate|log.Ltime)
httpxxray.OnClient(cl, logger)
// Use the robust httpx.Client to send a request, and print the response.
p, err := request.NewPlanWithContext(ctx, "GET", server.URL, nil)
if err != nil {
fail(seg, err)
}
e, err := cl.Do(p)
if err != nil {
fail(seg, err)
}
fmt.Printf("Status: %d\nBody: %s\n", e.StatusCode(), e.Body)
}
func fail(seg *xray.Segment, err error) {
seg.Close(err)
println(err.Error())
os.Exit(1)
}