proxy.go70 lines, 2.4 KB
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "log/slog" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httputil" |
| 10 | "net/url" |
| 11 | "sync" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 15 | "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" |
| 16 | ) |
| 17 | |
| 18 | // newProxy returns a reverse proxy to the service at target, like |
| 19 | // http://localhost:8082. |
| 20 | func newProxy(target *url.URL) *httputil.ReverseProxy { |
| 21 | return &httputil.ReverseProxy{ |
| 22 | // Rewrite drops X-Forwarded headers a client made up. |
| 23 | Rewrite: func(pr *httputil.ProxyRequest) { |
| 24 | pr.SetURL(target) |
| 25 | pr.SetXForwarded() |
| 26 | pr.Out.Header.Set(httpx.RequestIDHeader, httpx.RequestIDFrom(pr.In.Context())) |
| 27 | }, |
| 28 | // A span for each call upstream, and the trace context in its headers. |
| 29 | Transport: otelhttp.NewTransport(&http.Transport{ |
| 30 | DialContext: (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext, |
| 31 | // The default keeps only two idle connections per host. |
| 32 | MaxIdleConns: 100, |
| 33 | MaxIdleConnsPerHost: 100, |
| 34 | IdleConnTimeout: 90 * time.Second, |
| 35 | ResponseHeaderTimeout: 10 * time.Second, |
| 36 | }), |
| 37 | // Our RequestID middleware already set it: don't send it twice. |
| 38 | ModifyResponse: func(resp *http.Response) error { |
| 39 | resp.Header.Del(httpx.RequestIDHeader) |
| 40 | return nil |
| 41 | }, |
| 42 | ErrorHandler: proxyError, |
| 43 | BufferPool: buffers, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // buffers lends every proxy a 32 KB buffer to copy a response with, and takes |
| 48 | // it back afterwards. Without one, each response gets a buffer of its own. |
| 49 | var buffers = &bufferPool{sync.Pool{New: func() any { b := make([]byte, 32<<10); return &b }}} |
| 50 | |
| 51 | // bufferPool is a sync.Pool, as an httputil.BufferPool. It keeps pointers to |
| 52 | // slices: putting a slice itself in a sync.Pool allocates, every time. |
| 53 | type bufferPool struct{ pool sync.Pool } |
| 54 | |
| 55 | func (p *bufferPool) Get() []byte { return *p.pool.Get().(*[]byte) } |
| 56 | func (p *bufferPool) Put(b []byte) { p.pool.Put(&b) } |
| 57 | |
| 58 | // proxyError answers in our JSON format when the service can't. |
| 59 | func proxyError(w http.ResponseWriter, r *http.Request, err error) { |
| 60 | switch { |
| 61 | case errors.Is(err, context.DeadlineExceeded): |
| 62 | httpx.Error(w, r, errUpstreamTimeout) |
| 63 | case errors.Is(err, context.Canceled): |
| 64 | // The client hung up: no one to answer. |
| 65 | default: |
| 66 | // The details, like an internal address, are for our logs only. |
| 67 | slog.WarnContext(r.Context(), "upstream unavailable", "err", err) |
| 68 | httpx.Error(w, r, errUpstreamDown) |
| 69 | } |
| 70 | } |