net/http: add ProxyConnectError type for proxy CONNECT failures
## Summary
Introduces `ProxyConnectError` type to provide structured access to proxy response details when HTTP CONNECT requests fail with non-200 status codes. Maintains full backward compatibility with existing error strings.
## Problem
When proxies return non-200 status codes during CONNECT, Go currently returns generic error strings, making it impossible to access potentially useful diagnostic information like `X-Squid-Error` headers, custom error codes, or response bodies.
## Motivation
This addresses a long-standing issue (#30560) where users cannot access proxy error details during failed CONNECT attempts. Real-world scenarios include:
- **Squid proxies** returning 503 errors with `X-Squid-Error` headers containing detailed failure reasons
- **Corporate proxies** providing custom error codes and authentication requirements
- **Load balancers** including retry hints or upstream service information
- **Health check failures** where response bodies contain diagnostic data
Currently, all this information is lost, and users only see generic errors like "Service Unavailable".
## Solution
\`\`\`go
// ProxyConnectError holds the response to an unsuccessful proxy CONNECT request.
type ProxyConnectError struct {
Response *Response
}
\`\`\`
## Backward Compatibility
The \`Error()\` method returns only the status text (e.g., "Service Unavailable") to match existing behavior exactly. Only callers explicitly using \`errors.As()\` gain access to the structured response.
## Testing
- New test \`TestRoundTripReturnsProxyConnectError\` verifies error type and backward compatibility
- All existing proxy tests pass
## Related Work
Based on #44123 by @logandavies181, updated for current \`master\` and adapted to resolve 4 years of code changes.
Fixes #30560
diff --git a/src/net/http/transport.go b/src/net/http/transport.go
index 924e7cf..44d89b5 100644
--- a/src/net/http/transport.go
+++ b/src/net/http/transport.go
@@ -1764,6 +1764,20 @@
RoundTripErr() error
}
+// ProxyConnectError holds the response to an unsuccessful proxy CONNECT request.
+type ProxyConnectError struct {
+ Response *Response
+}
+
+func (p *ProxyConnectError) Error() string {
+ // Don't return full Response.Status for backwards compatibility
+ f := strings.SplitN(p.Response.Status, " ", 2)
+ if len(f) < 2 {
+ return "unknown status code"
+ }
+ return f[1]
+}
+
var testHookProxyConnectTimeout = context.WithTimeout
func (t *Transport) dialConn(ctx context.Context, cm connectMethod, isClientConn bool, internalStateHook func()) (pconn *persistConn, err error) {
@@ -1929,12 +1943,10 @@
}
if resp.StatusCode != 200 {
- _, text, ok := strings.Cut(resp.Status, " ")
conn.Close()
- if !ok {
- return nil, errors.New("unknown status code")
+ return nil, &ProxyConnectError{
+ Response: resp,
}
- return nil, errors.New(text)
}
}
diff --git a/src/net/http/transport_test.go b/src/net/http/transport_test.go
index 37e6cbb..a4d2dbe 100644
--- a/src/net/http/transport_test.go
+++ b/src/net/http/transport_test.go
@@ -4329,6 +4329,41 @@
}
}
+// Test for issue 38143
+// Return an error containing the proxy CONNECT request if status is not 200
+func TestRoundTripReturnsProxyConnectError(t *testing.T) {
+ s := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.WriteHeader(StatusServiceUnavailable)
+ }))
+ defer s.Close()
+
+ proxyURL, err := url.Parse(s.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tr := &Transport{
+ Proxy: ProxyURL(proxyURL),
+ }
+
+ req, err := NewRequest("GET", "https://example.com", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ _, got := tr.RoundTrip(req)
+
+ switch errType := got.(type) {
+ case *ProxyConnectError:
+ default:
+ t.Errorf("Wrong error type returned, Got: %T, Want: *ProxyConnectError", errType)
+ }
+
+ // Test backwards compatibility
+ if got.Error() != "Service Unavailable" {
+ t.Error("Non-backwards compatible error message from *ProxyConnectError")
+ }
+}
+
// tests that putting an idle conn after a call to CloseIdleConns does return it
func TestTransportCloseIdleConnsThenReturn(t *testing.T) {
tr := &Transport{}
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
I spotted some possible problems with your PR:
1. You have a long 243 character line in the commit message body. Please add line breaks to long lines that should be wrapped. Lines in the commit message body should be wrapped at ~76 characters unless needed for things like URLs or tables. (Note: GitHub might render long lines as soft-wrapped, so double-check in the Gerrit commit message shown above.)
2. It looks like you are using markdown in the commit message. If so, please remove it. Be sure to double-check the plain text shown in the Gerrit commit message above for any markdown backticks, markdown links, or other markdown formatting.
Please address any problems by updating the GitHub PR.
When complete, mark this comment as 'Done' and click the [blue 'Reply' button](https://go.dev/wiki/GerritBot#i-left-a-reply-to-a-comment-in-gerrit-but-no-one-but-me-can-see-it) above. These findings are based on heuristics; if a finding does not apply, briefly reply here saying so.
To update the commit title or commit message body shown here in Gerrit, you must edit the GitHub PR title and PR description (the first comment) in the GitHub web interface using the 'Edit' button or 'Edit' menu entry there. Note: pushing a new commit to the PR will not automatically update the commit message used by Gerrit.
For more details, see:
(In general for Gerrit code reviews, the change author is expected to [log in to Gerrit](https://go-review.googlesource.com/login/) with a Gmail or other Google account and then close out each piece of feedback by marking it as 'Done' if implemented as suggested or otherwise reply to each review comment. See the [Review](https://go.dev/doc/contribute#review) section of the Contributing Guide for details.)
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
I spotted some possible problems with your PR:
1. You have a long 243 character line in the commit message body. Please add line breaks to long lines that should be wrapped. Lines in the commit message body should be wrapped at ~76 characters unless needed for things like URLs or tables. (Note: GitHub might render long lines as soft-wrapped, so double-check in the Gerrit commit message shown above.)
2. It looks like you are using markdown in the commit message. If so, please remove it. Be sure to double-check the plain text shown in the Gerrit commit message above for any markdown backticks, markdown links, or other markdown formatting.Please address any problems by updating the GitHub PR.
When complete, mark this comment as 'Done' and click the [blue 'Reply' button](https://go.dev/wiki/GerritBot#i-left-a-reply-to-a-comment-in-gerrit-but-no-one-but-me-can-see-it) above. These findings are based on heuristics; if a finding does not apply, briefly reply here saying so.
To update the commit title or commit message body shown here in Gerrit, you must edit the GitHub PR title and PR description (the first comment) in the GitHub web interface using the 'Edit' button or 'Edit' menu entry there. Note: pushing a new commit to the PR will not automatically update the commit message used by Gerrit.
For more details, see:
- [how to update commit messages](https://go.dev/wiki/GerritBot/#how-does-gerritbot-determine-the-final-commit-message) for PRs imported into Gerrit.
- the Go project's [conventions for commit messages](https://go.dev/doc/contribute#commit_messages) that you should follow.
(In general for Gerrit code reviews, the change author is expected to [log in to Gerrit](https://go-review.googlesource.com/login/) with a Gmail or other Google account and then close out each piece of feedback by marking it as 'Done' if implemented as suggested or otherwise reply to each review comment. See the [Review](https://go.dev/doc/contribute#review) section of the Contributing Guide for details.)
Done
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
new api would need an accepted proposal
As Sean says, any new exported symbols must go through the proposal process:
https://github.com/golang/proposal
The general idea of `ProxyConnectError` sounds reasonable to me on first glance. The proposal process tends to grind very slowly, but if you want to file a short proposal for this I think it has a reasonable chance of being accepted.
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |
f := strings.SplitN(p.Response.Status, " ", 2)Why not simply use `strings.Cut`?
| Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. |