45 lines
950 B
Go
45 lines
950 B
Go
package deconnector
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
func (d *Deconnector) forwardHTTP(ctx context.Context, clientConn net.Conn, req *http.Request) {
|
|
upstreamConn, err := d.dialer.Dial(ctx)
|
|
if err != nil {
|
|
d.app.Logger().WithError(err).Error("upstream dial failed")
|
|
fmt.Fprintf(clientConn, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
|
|
|
|
return
|
|
}
|
|
defer upstreamConn.Close()
|
|
|
|
if authHeader, ok := d.dialer.Auth(); ok {
|
|
req.Header.Set("Proxy-Authorization", "Basic "+authHeader)
|
|
}
|
|
|
|
if err := req.WriteProxy(upstreamConn); err != nil {
|
|
d.app.Logger().WithError(err).Error("failed to write request")
|
|
|
|
return
|
|
}
|
|
|
|
resp, err := http.ReadResponse(bufio.NewReader(upstreamConn), req)
|
|
if err != nil {
|
|
d.app.Logger().WithError(err).Error("failed to read response")
|
|
|
|
return
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
err = resp.Write(clientConn)
|
|
if err != nil {
|
|
d.app.Logger().WithError(err).Error("failed to write response")
|
|
}
|
|
}
|