2022-12-14 20:40:45 +01:00
|
|
|
package webBackend
|
2022-12-13 18:51:04 +01:00
|
|
|
|
|
|
|
import (
|
2023-01-09 23:24:35 +01:00
|
|
|
"fmt"
|
2022-12-13 18:51:04 +01:00
|
|
|
"github.com/openziti/sdk-golang/ziti"
|
|
|
|
"github.com/openziti/sdk-golang/ziti/config"
|
|
|
|
"github.com/openziti/sdk-golang/ziti/edge"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
IdentityPath string
|
|
|
|
WebRoot string
|
2023-01-04 20:42:58 +01:00
|
|
|
ShrToken string
|
2022-12-13 18:51:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type backend struct {
|
|
|
|
cfg *Config
|
|
|
|
listener edge.Listener
|
|
|
|
handler http.Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewBackend(cfg *Config) (*backend, error) {
|
|
|
|
options := ziti.ListenOptions{
|
|
|
|
ConnectTimeout: 5 * time.Minute,
|
|
|
|
MaxConnections: 64,
|
|
|
|
}
|
|
|
|
zcfg, err := config.NewFromFile(cfg.IdentityPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "error loading config")
|
|
|
|
}
|
2023-01-04 20:42:58 +01:00
|
|
|
listener, err := ziti.NewContextWithConfig(zcfg).ListenWithOptions(cfg.ShrToken, &options)
|
2022-12-13 18:51:04 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "error listening")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &backend{
|
|
|
|
cfg: cfg,
|
|
|
|
listener: listener,
|
2023-01-09 23:24:35 +01:00
|
|
|
handler: &requestLogger{handler: http.FileServer(http.Dir(cfg.WebRoot))},
|
2022-12-13 18:51:04 +01:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *backend) Run() error {
|
|
|
|
if err := http.Serve(self.listener, self.handler); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *backend) Requests() func() int32 {
|
|
|
|
return func() int32 { return 0 }
|
|
|
|
}
|
2023-01-09 23:24:35 +01:00
|
|
|
|
|
|
|
type requestLogger struct {
|
|
|
|
handler http.Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rl *requestLogger) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
fmt.Printf("web <= %v %v <= %v\n", req.Method, req.URL.String(), req.Header["X-Real-Ip"])
|
|
|
|
rl.handler.ServeHTTP(resp, req)
|
|
|
|
}
|