zrok/endpoints/bind/http.go

81 lines
1.8 KiB
Go
Raw Normal View History

2022-08-17 19:21:07 +02:00
package bind
2022-07-20 19:18:40 +02:00
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-17 19:21:07 +02:00
type httpBind struct {
2022-08-09 19:57:45 +02:00
Requests func() int32
listener edge.Listener
handler http.Handler
}
2022-08-17 19:21:07 +02:00
func NewHTTP(cfg *Config) (*httpBind, 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")
}
2022-08-17 19:21:07 +02:00
proxy, err := newReverseProxy(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)
2022-08-17 19:21:07 +02:00
return &httpBind{
2022-08-09 19:57:45 +02:00
Requests: handler.Requests,
listener: listener,
handler: handler,
}, nil
}
2022-08-17 19:21:07 +02:00
func (p *httpBind) Run() error {
2022-08-09 19:57:45 +02:00
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
2022-08-17 19:21:07 +02:00
func newReverseProxy(target string) (*httputil.ReverseProxy, error) {
2022-08-10 21:16:36 +02:00
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
}