|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + |
| 9 | + "github.com/stackitcloud/stackit-sdk-go/core/config" |
| 10 | + "github.com/stackitcloud/stackit-sdk-go/services/argus" |
| 11 | +) |
| 12 | + |
| 13 | +// RequestCapturer is a middleware that prints the request and a status it receives. |
| 14 | +func RequestCapturer(status string) config.Middleware { |
| 15 | + return func(rt http.RoundTripper) http.RoundTripper { |
| 16 | + return &roundTripperWithCapture{rt, status} |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +// roundTripperWithCapture is a custom round tripper that prints the request and an input it receives. |
| 21 | +type roundTripperWithCapture struct { |
| 22 | + transport http.RoundTripper |
| 23 | + inputString string |
| 24 | +} |
| 25 | + |
| 26 | +func (rt roundTripperWithCapture) RoundTrip(req *http.Request) (*http.Response, error) { |
| 27 | + returnStr := fmt.Sprintf("%s %s", req.Method, req.URL.String()) |
| 28 | + |
| 29 | + fmt.Println("Captured request:", returnStr) |
| 30 | + fmt.Println("Input:", rt.inputString) |
| 31 | + |
| 32 | + // Proceed with the original round trip |
| 33 | + // This step is important to preserve the original behavior of the client |
| 34 | + resp, err := rt.transport.RoundTrip(req) |
| 35 | + |
| 36 | + fmt.Println("Captured response status:", resp.Status) |
| 37 | + |
| 38 | + return resp, err |
| 39 | +} |
| 40 | + |
| 41 | +func main() { |
| 42 | + // Specify the project ID |
| 43 | + projectId := "PROJECT_ID" |
| 44 | + |
| 45 | + // Create a new API client, that uses default authentication |
| 46 | + // Use the `WithMiddleware` option to add the middleware to the client |
| 47 | + // The middleware will be executed in the reverse order they are added |
| 48 | + // In this case, the middleware with status "1" will be executed first |
| 49 | + argusClient, err := argus.NewAPIClient( |
| 50 | + config.WithRegion("eu01"), |
| 51 | + config.WithMiddleware(RequestCapturer("Middleware 2")), |
| 52 | + config.WithMiddleware(RequestCapturer("Middleware 1")), |
| 53 | + ) |
| 54 | + if err != nil { |
| 55 | + fmt.Fprintf(os.Stderr, "[Argus API] Creating API client: %v\n", err) |
| 56 | + os.Exit(1) |
| 57 | + } |
| 58 | + |
| 59 | + // Get the argus instances for your project |
| 60 | + getInstanceResp, err := argusClient.ListInstances(context.Background(), projectId).Execute() |
| 61 | + |
| 62 | + if err != nil { |
| 63 | + fmt.Fprintf(os.Stderr, "[Argus API] Error when calling `GetInstances`: %v\n", err) |
| 64 | + } else { |
| 65 | + fmt.Printf("[Argus API] Number of instances: %v\n", len(*getInstanceResp.Instances)) |
| 66 | + } |
| 67 | +} |
0 commit comments