reroute

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 12, 2026 License: MIT Imports: 7 Imported by: 0

README

📡 Go Reroute

Go ReRoute is a http.RoundTripper implementation that allows you to register alternative hosts for an outgoing HTTP request.

⬇️ Installation

go get github.com/survivorbat/go-reroute

📋 Usage

package main

func getClient() *http.Client {
	reRouter := &ReRouter{}

	_ = reRouter.RegisterFallbacks("localhost:1", []string{"localhost:8080"})

	client := &http.Client{Transport: reRouter}

	req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:1/foo/bar", http.NoBody)

	res, _ := client.Do(req)

  fmt.Println(res.Request.URL) // localhost:8080
}

🔭 Plans

  • Perhaps add switchover capabilities
  • Perhaps add loadbalancer capabilities

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

func (r *ReRouter) RegisterFallbacks(host string, fallbacks []string) error

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

func (r *ReRouter) RoundTrip(req *http.Request) (*http.Response, error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL