101 lines
2.1 KiB
Go
101 lines
2.1 KiB
Go
package proxy
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"isp-router-service/domain"
|
|
|
|
"github.com/pkg/errors"
|
|
"github.com/txix-open/isp-kit/lb"
|
|
)
|
|
|
|
// nolint:gochecknoglobals,mnd
|
|
var (
|
|
httpTransport = &http.Transport{
|
|
Proxy: http.ProxyFromEnvironment,
|
|
DialContext: defaultTransportDialContext(&net.Dialer{
|
|
Timeout: 3 * time.Second,
|
|
KeepAlive: 90 * time.Second,
|
|
}),
|
|
ForceAttemptHTTP2: true,
|
|
MaxIdleConns: 1024,
|
|
MaxIdleConnsPerHost: 256,
|
|
IdleConnTimeout: 60 * time.Second,
|
|
TLSHandshakeTimeout: 5 * time.Second,
|
|
ExpectContinueTimeout: 1 * time.Second,
|
|
}
|
|
)
|
|
|
|
type Http struct {
|
|
hostManager *lb.RoundRobin
|
|
}
|
|
|
|
func NewHttp(addresses []string) Http {
|
|
p := Http{
|
|
hostManager: lb.NewRoundRobin(addresses),
|
|
}
|
|
|
|
return p
|
|
}
|
|
|
|
func (p Http) PrepareEndpoint(endpoint string, proxyApiPrefix bool) string {
|
|
if !proxyApiPrefix {
|
|
return endpoint
|
|
}
|
|
|
|
if strings.HasPrefix(endpoint, domain.ApiPrefix) {
|
|
return endpoint
|
|
}
|
|
|
|
return domain.ApiPrefix + endpoint
|
|
}
|
|
|
|
func (p Http) Handle(ctx *domain.RequestContext) error {
|
|
host, err := p.hostManager.Next()
|
|
if err != nil {
|
|
return errors.WithMessage(err, "http: next host")
|
|
}
|
|
|
|
rawUrl := fmt.Sprintf("http://%s", host) // secure HTTP links are reset connection
|
|
target, err := url.Parse(rawUrl)
|
|
if err != nil {
|
|
return errors.WithMessage(err, "http: parse url")
|
|
}
|
|
|
|
proxy := httputil.NewSingleHostReverseProxy(target)
|
|
proxy.Transport = httpTransport
|
|
|
|
req := ctx.Request()
|
|
req.URL.Scheme = "http"
|
|
req.URL.Host = host
|
|
req.Host = host
|
|
req.URL.Path = ctx.Endpoint()
|
|
var resultError error
|
|
proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, err error) {
|
|
resultError = domain.NewHttpError(
|
|
http.StatusServiceUnavailable,
|
|
"upstream is not available",
|
|
errors.WithMessagef(err, "http proxy to %s", host),
|
|
)
|
|
}
|
|
|
|
proxy.ServeHTTP(ctx.ResponseWriter(), req)
|
|
|
|
return resultError // nolint:wrapcheck
|
|
}
|
|
|
|
func (p Http) Close() error {
|
|
return nil
|
|
}
|
|
|
|
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
|
return dialer.DialContext
|
|
}
|