Skip to content

feat: add server-side request context#201

Open
dustinbyrne wants to merge 3 commits into
mainfrom
feat/server-request-context
Open

feat: add server-side request context#201
dustinbyrne wants to merge 3 commits into
mainfrom
feat/server-request-context

Conversation

@dustinbyrne
Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Adds server-side request context support for Go net/http apps, matching the request-context patterns used in other PostHog server SDKs.

This lets handlers enqueue capture and exception events with request-scoped metadata and optional frontend tracing headers, while keeping explicit event identity authoritative and falling back to personless events when no identity is available.

Key changes:

  • Add RequestContext helpers, NewRequestContextMiddleware, and EnqueueWithContext.
  • Attach safe request metadata ($current_url, $request_method, $request_path, $user_agent, $ip) and optional tracing header values.
  • Support personless capture/exception fallback with $process_person_profile: false.
  • Add opt-in panic capture that re-panics and preserves host-app behavior.
  • Document tracing headers as client-controlled analytics context, not auth/authz.

💚 How did you test it?

  • gofmt -l $(git diff --name-only -- '*.go') request_context.go request_context_test.go
  • go test ./...

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran pnpm changeset to generate a changeset file

@dustinbyrne dustinbyrne added the release Add this label to trigger a release from a PR label May 20, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 20, 2026

posthog-go Compliance Report

Date: 2026-05-22 21:27:16 UTC
Duration: 107277ms

⚠️ Some Tests Failed

39/45 tests passed, 6 failed


Capture Tests

29/29 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields 614ms
Format Validation.Event Has Uuid 607ms
Format Validation.Event Has Lib Properties 608ms
Format Validation.Distinct Id Is String 608ms
Format Validation.Token Is Present 608ms
Format Validation.Custom Properties Preserved 607ms
Format Validation.Event Has Timestamp 608ms
Retry Behavior.Retries On 503 5613ms
Retry Behavior.Does Not Retry On 400 2609ms
Retry Behavior.Does Not Retry On 401 2610ms
Retry Behavior.Respects Retry After Header 5613ms
Retry Behavior.Implements Backoff 15614ms
Retry Behavior.Retries On 500 5613ms
Retry Behavior.Retries On 502 5613ms
Retry Behavior.Retries On 504 5613ms
Retry Behavior.Max Retries Respected 15614ms
Deduplication.Generates Unique Uuids 616ms
Deduplication.Preserves Uuid On Retry 5613ms
Deduplication.Preserves Uuid And Timestamp On Retry 10619ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 5614ms
Deduplication.No Duplicate Events In Batch 612ms
Deduplication.Different Events Have Different Uuids 610ms
Compression.Sends Gzip When Enabled 607ms
Batch Format.Uses Proper Batch Structure 608ms
Batch Format.Flush With No Events Sends Nothing 606ms
Batch Format.Multiple Events Batched Together 611ms
Error Handling.Does Not Retry On 403 2610ms
Error Handling.Does Not Retry On 413 2610ms
Error Handling.Retries On 408 5612ms

Feature_Flags Tests

⚠️ 10/16 tests passed, 6 failed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 8ms
Request Payload.Flags Request Uses V2 Query Param 6ms
Request Payload.Flags Request Hits Flags Path Not Decide 6ms
Request Payload.Flags Request Omits Authorization Header 6ms
Request Payload.Token In Flags Body Matches Init 6ms
Request Payload.Groups Round Trip 7ms
Request Payload.Groups Default To Empty Object 6ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It 7ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 6ms
Request Payload.Disable Geoip Omitted Defaults To False 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 6ms
Request Lifecycle.No Flags Request On Init Alone 4ms
Request Lifecycle.No Flags Request On Normal Capture 607ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 10ms
Request Lifecycle.Mock Response Value Is Returned To Caller 5ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 609ms

Failures

request_payload.request_with_person_properties_device_id

Field 'distinct_id' not found in /flags request body at path 'person_properties.distinct_id'. Available keys: ['$device_id']

request_payload.person_properties_distinct_id_auto_populated_when_caller_omits_it

Field 'distinct_id' not found in /flags request body at path 'person_properties.distinct_id'. Available keys: ['email']

request_payload.disable_geoip_false_propagates_as_geoip_disable_false

Expected geoip_disable=False, got True

request_payload.disable_geoip_omitted_defaults_to_false

Expected geoip_disable=False, got True

request_payload.flag_keys_to_evaluate_contains_only_requested_key

Field 'flag_keys_to_evaluate' not found in /flags request body at path 'flag_keys_to_evaluate'. Available keys: ['api_key', 'distinct_id', 'groups', 'person_properties', 'group_properties', 'geoip_disable']

side_effect_events.get_feature_flag_captures_feature_flag_called_event

Expected 1 events with name '$feature_flag_called', got 2

@dustinbyrne dustinbyrne force-pushed the feat/server-request-context branch from 0ca790a to f744a05 Compare May 22, 2026 19:46
@dustinbyrne dustinbyrne marked this pull request as ready for review May 22, 2026 19:59
@dustinbyrne dustinbyrne requested a review from a team as a code owner May 22, 2026 19:59
@dustinbyrne dustinbyrne force-pushed the feat/server-request-context branch from c9573cc to bf6f924 Compare May 22, 2026 20:12
@dustinbyrne
Copy link
Copy Markdown
Contributor Author

summoning greptile

@dustinbyrne dustinbyrne reopened this May 22, 2026
@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented May 22, 2026

Comments Outside Diff (2)

  1. request_context.go, line 760-768 (link)

    P1 $current_url scheme is wrong behind a TLS-terminating proxy

    In a standard production deployment (nginx, Traefik, AWS ALB), TLS is terminated at the proxy layer. The Go app receives plain HTTP, so r.TLS == nil and r.URL.Scheme == ""requestScheme then returns "http". Every $current_url event will show http://example.com/... even when users actually visited https://example.com/.... Checking X-Forwarded-Proto (which is set by trusted proxies and typically stripped from public requests by the same proxies) would fix the common case for services that already trust this header. Without it, the feature is effectively broken for any production app that terminates TLS at a load balancer.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: request_context.go
    Line: 760-768
    
    Comment:
    **`$current_url` scheme is wrong behind a TLS-terminating proxy**
    
    In a standard production deployment (nginx, Traefik, AWS ALB), TLS is terminated at the proxy layer. The Go app receives plain HTTP, so `r.TLS == nil` and `r.URL.Scheme == ""``requestScheme` then returns `"http"`. Every `$current_url` event will show `http://example.com/...` even when users actually visited `https://example.com/...`. Checking `X-Forwarded-Proto` (which is set by trusted proxies and typically stripped from public requests by the same proxies) would fix the common case for services that already trust this header. Without it, the feature is effectively broken for any production app that terminates TLS at a load balancer.
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. request_context.go, line 830-840 (link)

    P2 Context is silently dropped when client doesn't implement EnqueueWithContext

    When a caller passes a custom EnqueueClient that does not implement the EnqueueWithContext optional interface, the fallback is client.Enqueue(msg) — the original, unenriched message. Request context properties are never applied, DistinctId is not resolved from context, and there is no personless fallback. A handler that relied on EnqueueWithContext to supply the DistinctId would silently receive a "DistinctId required" error from the inner Enqueue, with no indication that context resolution was skipped. A comment documenting this fallback behaviour (or at least an attempt to apply context enrichment before the fallback) would make the contract clearer for custom-client users.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: request_context.go
    Line: 830-840
    
    Comment:
    **Context is silently dropped when client doesn't implement `EnqueueWithContext`**
    
    When a caller passes a custom `EnqueueClient` that does not implement the `EnqueueWithContext` optional interface, the fallback is `client.Enqueue(msg)` — the original, unenriched message. Request context properties are never applied, `DistinctId` is not resolved from context, and there is no personless fallback. A handler that relied on `EnqueueWithContext` to supply the `DistinctId` would silently receive a "DistinctId required" error from the inner `Enqueue`, with no indication that context resolution was skipped. A comment documenting this fallback behaviour (or at least an attempt to apply context enrichment before the fallback) would make the contract clearer for custom-client users.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
request_context.go:760-768
**`$current_url` scheme is wrong behind a TLS-terminating proxy**

In a standard production deployment (nginx, Traefik, AWS ALB), TLS is terminated at the proxy layer. The Go app receives plain HTTP, so `r.TLS == nil` and `r.URL.Scheme == ""``requestScheme` then returns `"http"`. Every `$current_url` event will show `http://example.com/...` even when users actually visited `https://example.com/...`. Checking `X-Forwarded-Proto` (which is set by trusted proxies and typically stripped from public requests by the same proxies) would fix the common case for services that already trust this header. Without it, the feature is effectively broken for any production app that terminates TLS at a load balancer.

### Issue 2 of 3
request_context.go:830-840
**Context is silently dropped when client doesn't implement `EnqueueWithContext`**

When a caller passes a custom `EnqueueClient` that does not implement the `EnqueueWithContext` optional interface, the fallback is `client.Enqueue(msg)` — the original, unenriched message. Request context properties are never applied, `DistinctId` is not resolved from context, and there is no personless fallback. A handler that relied on `EnqueueWithContext` to supply the `DistinctId` would silently receive a "DistinctId required" error from the inner `Enqueue`, with no indication that context resolution was skipped. A comment documenting this fallback behaviour (or at least an attempt to apply context enrichment before the fallback) would make the contract clearer for custom-client users.

### Issue 3 of 3
posthog.go:398-401
**`Capture.Validate()` is now bypassed on the main enqueue path**

Before this PR, `msg.Validate()` was called once at the top of `Enqueue` for all message types. Now the Capture branch calls only `validateCaptureEvent` (Event check) and delegates the DistinctId check to `resolveCaptureContext`, meaning `Capture.Validate()` has no internal callers. Any validation logic added to `Capture.Validate()` in the future won't be enforced via `EnqueueWithContext`. By contrast, the `Exception` branch does call `m.Validate()` after context resolution. Aligning Capture to follow the same pattern — calling `m.Validate()` after `m.DistinctId` is set — would eliminate this divergence and keep `Capture.Validate()` as the single place for capture validation rules.

Reviews (1): Last reviewed commit: "refactor: remove unused feature flag eva..." | Re-trigger Greptile

Comment thread posthog.go
Comment thread request_context.go
scheme := requestScheme(r)
host := requestHost(r)
if scheme == "" || host == "" {
return ""
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for this all and other methods here better to return nil instead of empty if we cannot derive the prop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release Add this label to trigger a release from a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants