zrok/endpoints/proxy/webBackend.go

83 lines
1.9 KiB
Go
Raw Normal View History

2023-04-18 19:44:58 +02:00
package proxy
2022-12-13 18:51:04 +01:00
import (
"fmt"
2022-12-13 18:51:04 +01:00
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/edge"
"github.com/openziti/zrok/endpoints"
2022-12-13 18:51:04 +01:00
"github.com/pkg/errors"
2023-05-25 20:59:39 +02:00
"net/http"
"time"
2022-12-13 18:51:04 +01:00
)
2023-04-18 19:44:58 +02:00
type WebBackendConfig struct {
2022-12-13 18:51:04 +01:00
IdentityPath string
WebRoot string
2023-01-04 20:42:58 +01:00
ShrToken string
2023-01-10 23:40:20 +01:00
RequestsChan chan *endpoints.Request
2022-12-13 18:51:04 +01:00
}
2023-04-18 19:44:58 +02:00
type WebBackend struct {
cfg *WebBackendConfig
2022-12-13 18:51:04 +01:00
listener edge.Listener
handler http.Handler
}
2023-04-18 19:44:58 +02:00
func NewWebBackend(cfg *WebBackendConfig) (*WebBackend, error) {
2022-12-13 18:51:04 +01:00
options := ziti.ListenOptions{
ConnectTimeout: 5 * time.Minute,
MaxConnections: 64,
}
2023-05-25 17:50:38 +02:00
zcfg, err := ziti.NewConfigFromFile(cfg.IdentityPath)
2022-12-13 18:51:04 +01:00
if err != nil {
return nil, errors.Wrap(err, "error loading config")
}
2023-05-25 17:50:38 +02:00
zctx, err := ziti.NewContext(zcfg)
if err != nil {
return nil, errors.Wrap(err, "error loading ziti context")
}
listener, err := zctx.ListenWithOptions(cfg.ShrToken, &options)
2022-12-13 18:51:04 +01:00
if err != nil {
return nil, errors.Wrap(err, "error listening")
}
2023-04-18 19:44:58 +02:00
be := &WebBackend{
2022-12-13 18:51:04 +01:00
cfg: cfg,
listener: listener,
2023-01-10 20:52:28 +01:00
}
if cfg.RequestsChan != nil {
be.handler = &requestGrabber{requests: cfg.RequestsChan, handler: http.FileServer(http.Dir(cfg.WebRoot))}
} else {
be.handler = http.FileServer(http.Dir(cfg.WebRoot))
}
return be, nil
2022-12-13 18:51:04 +01:00
}
2023-04-18 19:44:58 +02:00
func (self *WebBackend) Run() error {
2022-12-13 18:51:04 +01:00
if err := http.Serve(self.listener, self.handler); err != nil {
return err
}
return nil
}
2023-04-18 19:44:58 +02:00
func (self *WebBackend) Requests() func() int32 {
2022-12-13 18:51:04 +01:00
return func() int32 { return 0 }
}
2023-01-10 20:52:28 +01:00
type requestGrabber struct {
2023-01-10 23:40:20 +01:00
requests chan *endpoints.Request
2023-01-10 20:52:28 +01:00
handler http.Handler
}
2023-01-10 20:52:28 +01:00
func (rl *requestGrabber) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if rl.requests != nil {
2023-01-10 23:40:20 +01:00
rl.requests <- &endpoints.Request{
2023-01-10 20:52:28 +01:00
Stamp: time.Now(),
RemoteAddr: fmt.Sprintf("%v", req.Header["X-Real-Ip"]),
Method: req.Method,
Path: req.URL.String(),
}
}
rl.handler.ServeHTTP(resp, req)
}