Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ReRouter ¶
type ReRouter struct {
// Logger may be provided for monitoring purposes. Defaults to io.Discard.
Logger *slog.Logger
// Next is the next roundtripper to be called in the chain, defaults to http.DefaultTransport
Next http.RoundTripper
// contains filtered or unexported fields
}
ReRouter is a http.RoundTripper that allows you to register alternative hosts for outgoing HTTP requests. If the original host is unreachable or a 5xx HTTP status code the ReRouter will move to the next registered host and perform another attempt. If an alternative host succeeds, the new host is considered the primary and moved to the front of the fallback list.
Example ¶
httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer httpServer.Close()
reRouter := &ReRouter{}
_ = reRouter.RegisterFallbacks("localhost:1", []string{httpServer.URL})
client := &http.Client{Transport: reRouter}
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:1/foo/bar", http.NoBody)
res, _ := client.Do(req)
_ = res.Body.Close()
fmt.Println(res.StatusCode)
Output: 200
func (*ReRouter) RegisterFallbacks ¶
RegisterFallbacks registers fallbacks for a host. Schemes and paths are stripped from both the host and the callbacks so that only the hostname and port (if any) remain.
func (*ReRouter) RoundTrip ¶
RoundTrip uses the registered fallbacks to loop through hosts if the initial call fails. If an alternative hosts succeeds, it is elected as the new primary and will be tried first in subsequent calls. If no alternative hosts are set, the request is directly forwarded to the next transport.