zrok/http/http.go

81 lines
1.7 KiB
Go
Raw Normal View History

2022-07-20 19:18:40 +02:00
package http
import (
2022-07-21 22:01:39 +02:00
"github.com/openziti-test-kitchen/zrok/util"
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/config"
2022-08-09 19:57:45 +02:00
"github.com/openziti/sdk-golang/ziti/edge"
"github.com/pkg/errors"
2022-08-10 21:16:36 +02:00
"github.com/sirupsen/logrus"
"net/http"
2022-08-10 21:16:36 +02:00
"net/http/httputil"
"net/url"
"time"
)
2022-08-10 21:16:36 +02:00
type Config struct {
IdentityPath string
EndpointAddress string
Service string
}
2022-08-09 19:57:45 +02:00
type httpProxy struct {
Requests func() int32
listener edge.Listener
handler http.Handler
}
func New(cfg *Config) (*httpProxy, error) {
options := ziti.ListenOptions{
ConnectTimeout: 5 * time.Minute,
MaxConnections: 64,
}
zcfg, err := config.NewFromFile(cfg.IdentityPath)
if err != nil {
2022-08-09 19:57:45 +02:00
return nil, errors.Wrap(err, "error loading config")
}
2022-07-26 22:00:59 +02:00
listener, err := ziti.NewContextWithConfig(zcfg).ListenWithOptions(cfg.Service, &options)
if err != nil {
2022-08-09 19:57:45 +02:00
return nil, errors.Wrap(err, "error listening")
}
proxy, err := NewProxy(cfg.EndpointAddress)
2022-07-21 21:46:14 +02:00
if err != nil {
2022-08-09 19:57:45 +02:00
return nil, err
}
2022-08-09 19:57:45 +02:00
handler := util.NewProxyHandler(proxy)
return &httpProxy{
Requests: handler.Requests,
listener: listener,
handler: handler,
}, nil
}
func (p *httpProxy) Run() error {
if err := http.Serve(p.listener, p.handler); err != nil {
2022-07-21 21:46:14 +02:00
return err
}
2022-07-21 21:46:14 +02:00
return nil
}
2022-08-10 21:16:36 +02:00
func NewProxy(target string) (*httputil.ReverseProxy, error) {
targetURL, err := url.Parse(target)
if err != nil {
return nil, err
}
proxy := httputil.NewSingleHostReverseProxy(targetURL)
director := proxy.Director
proxy.Director = func(req *http.Request) {
director(req)
logrus.Debugf("-> %v", req.URL.String())
req.Header.Set("X-Proxy", "zrok")
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
logrus.Errorf("error proxying: %v", err)
}
return proxy, nil
}