|
6 | 6 | "github.com/kumahq/kuma-counter-demo/pkg/api" |
7 | 7 | "go.opentelemetry.io/otel/trace" |
8 | 8 | "log/slog" |
| 9 | + "math/rand" |
9 | 10 | "net/http" |
10 | 11 | "strconv" |
11 | 12 | "sync" |
@@ -40,12 +41,23 @@ func (s *ServerImpl) writeResponse(w http.ResponseWriter, r *http.Request, origi |
40 | 41 | if originalStatusCode/100 < 5 { // If the original status is 5xx ignore our override |
41 | 42 | statusStr := r.Header.Get("x-set-response-status-code") |
42 | 43 | if st, _ := strconv.Atoi(statusStr); st != 0 { |
43 | | - originalStatusCode = st |
| 44 | + statusCode = st |
| 45 | + } |
| 46 | + // Handle fault injection via x-failure-percentage header |
| 47 | + if statusCode/100 < 4 { // Only inject faults for successful responses (2xx, 3xx) |
| 48 | + failurePercentageStr := r.Header.Get("x-failure-percentage") |
| 49 | + if failurePercentage, parseErr := strconv.Atoi(failurePercentageStr); parseErr == nil && failurePercentage > 0 { |
| 50 | + if failurePercentage >= 100 || rand.Intn(100) < failurePercentage { |
| 51 | + statusCode = http.StatusInternalServerError |
| 52 | + err = fmt.Errorf("simulated failure with %d%% chance", failurePercentage) |
| 53 | + } |
| 54 | + } |
44 | 55 | } |
45 | 56 | } |
46 | 57 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
47 | 58 | w.Header().Set("X-Demo-App-Version", s.version) |
48 | | - w.WriteHeader(originalStatusCode) |
| 59 | + w.Header().Set("X-Original-Status-Code", strconv.Itoa(originalStatusCode)) |
| 60 | + w.WriteHeader(statusCode) |
49 | 61 | if err != nil { |
50 | 62 | slog.ErrorContext(r.Context(), "failed request with error", "err", err, "status", statusCode, "response", response) |
51 | 63 | } else { |
|
0 commit comments