code improvements; http listener (#32)

This commit is contained in:
Michael Quigley 2022-08-18 16:57:38 -04:00
parent 04267936cf
commit 20aface112
No known key found for this signature in database
GPG Key ID: 9B60314A9DD20A62
3 changed files with 41 additions and 16 deletions

View File

@ -13,7 +13,14 @@ var proxyCmd = &cobra.Command{
Use: "proxy <configPath>",
Short: "Start a zrok proxy",
Run: func(_ *cobra.Command, args []string) {
if err := listen.Run(&listen.Config{IdentityPath: args[0], Address: "0.0.0.0:10111"}); err != nil {
httpListener, err := listen.NewHTTP(&listen.Config{
IdentityPath: args[0],
Address: "0.0.0.0:10111",
})
if err != nil {
panic(err)
}
if err := httpListener.Run(); err != nil {
panic(err)
}
},

View File

@ -20,6 +20,7 @@ type Config struct {
}
type httpBind struct {
cfg *Config
Requests func() int32
listener edge.Listener
handler http.Handler
@ -46,14 +47,15 @@ func NewHTTP(cfg *Config) (*httpBind, error) {
handler := util.NewProxyHandler(proxy)
return &httpBind{
cfg: cfg,
Requests: handler.Requests,
listener: listener,
handler: handler,
}, nil
}
func (p *httpBind) Run() error {
if err := http.Serve(p.listener, p.handler); err != nil {
func (self *httpBind) Run() error {
if err := http.Serve(self.listener, self.handler); err != nil {
return err
}
return nil

View File

@ -22,10 +22,16 @@ type Config struct {
Address string
}
func Run(cfg *Config) error {
type httpListen struct {
cfg *Config
zCtx ziti.Context
handler http.Handler
}
func NewHTTP(cfg *Config) (*httpListen, error) {
zCfg, err := config.NewFromFile(cfg.IdentityPath)
if err != nil {
return errors.Wrap(err, "error loading config")
return nil, errors.Wrap(err, "error loading config")
}
zCfg.ConfigTypes = []string{model.ZrokProxyConfig}
zCtx := ziti.NewContextWithConfig(zCfg)
@ -35,21 +41,20 @@ func Run(cfg *Config) error {
proxy, err := NewServiceProxy(zCtx, &resolver{})
if err != nil {
return err
return nil, err
}
proxy.Transport = zTransport
return http.ListenAndServe(cfg.Address, basicAuth(util.NewProxyHandler(proxy), "zrok", &resolver{}, zCtx))
handler := basicAuth(util.NewProxyHandler(proxy), "zrok", &resolver{}, zCtx)
return &httpListen{
cfg: cfg,
zCtx: zCtx,
handler: handler,
}, nil
}
type resolver struct{}
func (r *resolver) Service(host string) string {
logrus.Debugf("host = '%v'", host)
tokens := strings.Split(host, ".")
if len(tokens) > 0 {
return tokens[0]
}
return "zrok"
func (self *httpListen) Run() error {
return http.ListenAndServe(self.cfg.Address, self.handler)
}
type ZitiDialContext struct {
@ -236,3 +241,14 @@ func writeUnauthorizedResponse(w http.ResponseWriter, realm string) {
w.WriteHeader(401)
w.Write([]byte("No Authorization\n"))
}
type resolver struct{}
func (r *resolver) Service(host string) string {
logrus.Debugf("host = '%v'", host)
tokens := strings.Split(host, ".")
if len(tokens) > 0 {
return tokens[0]
}
return "zrok"
}