Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a hook for errors occurring before the roundtrip. #32

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions rp.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,21 @@
// RoundTrip performs the round trip of the request.
// It is necessary to implement the functions that http.Transport is responsible for (e.g. MaxIdleConnsPerHost).
RoundTrip(r *http.Request) (*http.Response, error)
RoundTripOnError(r *http.Request) (*http.Response, error)
}

type RoundTipperOnErrorer interface {

Check failure on line 40 in rp.go

View workflow job for this annotation

GitHub Actions / Test

[gostyle.ifacenames] By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun. (ref: https://go.dev/doc/effective_go#interface-names ): RoundTipperOnErrorer
// RoundTripOnError performs the round trip of the request when the upstream returns an error.
// If this method is not implemented, the request will be sent to the default transport error.
RoundTripOnError(r *http.Request) (*http.Response, error)
}

type relayer struct {
Relayer
Rewrite func(*httputil.ProxyRequest) error
GetCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error)
RoundTrip func(*http.Request) (*http.Response, error)
Rewrite func(*httputil.ProxyRequest) error
GetCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error)
RoundTrip func(*http.Request) (*http.Response, error)
RoundTripOnError func(*http.Request) (*http.Response, error)
}

func newRelayer(r Relayer) *relayer {
Expand All @@ -58,6 +66,9 @@
} else {
rr.RoundTrip = http.DefaultTransport.RoundTrip
}
if v, ok := r.(RoundTipperOnErrorer); ok {
rr.RoundTripOnError = v.RoundTripOnError
}
return rr
}

Expand Down Expand Up @@ -144,6 +155,9 @@

func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
if v := r.Header.Get(errorKey); v != "" {
if t.rr.RoundTripOnError != nil {
return t.rr.RoundTripOnError(r)
}
// If errorKey is set, return error response.
body := v
resp := &http.Response{
Expand Down
22 changes: 15 additions & 7 deletions rp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,26 @@
}

func TestHTTPRouting(t *testing.T) {
simpleRelayer := func(m map[string]string) rp.Relayer {
return testutil.NewSimpleRelayer(m)
}
roundTripErrorRelayer := func(m map[string]string) rp.Relayer {
return testutil.NewRoundTripOnErrorRelayer(m)
}
tests := []struct {
upstreams []upstream
reqURL string
want string
wantStatusCode int
setupRelayer func(m map[string]string) rp.Relayer
}{
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://a.example.com", "response from / [a.example.com]", http.StatusOK},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://b.example.com/hello", "response from /hello [b.example.com]", http.StatusOK},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://a.example.com/hello?foo=bar", "response from /hello?foo=bar [a.example.com]", http.StatusOK},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://x.example.com/hello", "not found upstream: x.example.com", http.StatusBadGateway},
{[]upstream{{"a.example.com", "/A"}}, "http://a.example.com", "response from /A [a.example.com]", http.StatusOK},
{[]upstream{{"a.example.com", "/A"}}, "http://a.example.com/hello?foo=bar", "response from /A/hello?foo=bar [a.example.com]", http.StatusOK},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://a.example.com", "response from / [a.example.com]", http.StatusOK, simpleRelayer},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://b.example.com/hello", "response from /hello [b.example.com]", http.StatusOK, simpleRelayer},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://a.example.com/hello?foo=bar", "response from /hello?foo=bar [a.example.com]", http.StatusOK, simpleRelayer},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://x.example.com/hello", "not found upstream: x.example.com", http.StatusBadGateway, simpleRelayer},
{[]upstream{{"a.example.com", "/A"}}, "http://a.example.com", "response from /A [a.example.com]", http.StatusOK, simpleRelayer},
{[]upstream{{"a.example.com", "/A"}}, "http://a.example.com/hello?foo=bar", "response from /A/hello?foo=bar [a.example.com]", http.StatusOK, simpleRelayer},
{[]upstream{{"a.example.com", "/"}, {"b.example.com", "/"}}, "http://x.example.com/hello", "round trip on error: x.example.com", http.StatusBadGateway, roundTripErrorRelayer},
}
for _, tt := range tests {
t.Run(tt.reqURL, func(t *testing.T) {
Expand All @@ -47,7 +55,7 @@
us := testutil.NewUpstreamServer(t, u.hostname)
m[u.hostname] = us.URL + u.rootPath
}
r := testutil.NewSimpleRelayer(m)
r := tt.setupRelayer(m)
port, err := testutil.NewPort()
if err != nil {
t.Fatal(err)
Expand All @@ -62,10 +70,10 @@
}
}()
t.Cleanup(func() {
_ = proxy.Shutdown(context.Background())

Check failure on line 73 in rp_test.go

View workflow job for this annotation

GitHub Actions / Test

[gostyle.handlerrors] Do not discard errors using `_` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic. (ref: https://github.com/golang/go/wiki/CodeReviewComments#handle-errors )
})
t.Cleanup(func() {
_ = proxy.Shutdown(context.Background())

Check failure on line 76 in rp_test.go

View workflow job for this annotation

GitHub Actions / Test

[gostyle.handlerrors] Do not discard errors using `_` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic. (ref: https://github.com/golang/go/wiki/CodeReviewComments#handle-errors )
})
proxyURL, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port))
if err != nil {
Expand Down Expand Up @@ -142,7 +150,7 @@
}
}()
t.Cleanup(func() {
_ = proxy.Shutdown(context.Background())

Check failure on line 153 in rp_test.go

View workflow job for this annotation

GitHub Actions / Test

[gostyle.handlerrors] Do not discard errors using `_` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic. (ref: https://github.com/golang/go/wiki/CodeReviewComments#handle-errors )
})
proxyURL, err := url.Parse(fmt.Sprintf("https://127.0.0.1:%d", port))
if err != nil {
Expand Down Expand Up @@ -193,7 +201,7 @@
return
}
if tt.wantErr {
b, _ := httputil.DumpResponse(resp, true)

Check failure on line 204 in rp_test.go

View workflow job for this annotation

GitHub Actions / Test

[gostyle.handlerrors] Do not discard errors using `_` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic. (ref: https://github.com/golang/go/wiki/CodeReviewComments#handle-errors )
t.Errorf("want error, got resp:\n%s", string(b))
return
}
Expand Down
28 changes: 28 additions & 0 deletions testutil/relayer.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package testutil

import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
Expand Down Expand Up @@ -80,3 +82,29 @@ func (r *SimpleRelayer) GetUpstream(req *http.Request) (*url.URL, error) {
}
return nil, fmt.Errorf("not found upstream: %v", host)
}

type RoundTripOnErrorRelayer struct {
SimpleRelayer
}

func NewRoundTripOnErrorRelayer(h map[string]string) *RoundTripOnErrorRelayer {
return &RoundTripOnErrorRelayer{
SimpleRelayer: SimpleRelayer{
h: h,
},
}
}
func (r *RoundTripOnErrorRelayer) RoundTripOnError(req *http.Request) (*http.Response, error) {
body := fmt.Sprintf("round trip on error: %v", req.Host)
return &http.Response{
Status: http.StatusText(http.StatusBadGateway),
StatusCode: http.StatusBadGateway,
Proto: req.Proto,
ProtoMajor: req.ProtoMajor,
ProtoMinor: req.ProtoMinor,
Body: io.NopCloser(bytes.NewBufferString(body)),
ContentLength: int64(len(body)),
Request: req,
Header: make(http.Header, 0),
}, nil
}
Loading