Files
creator-hub/cmd/control-plane/main.go
T

150 lines
4.1 KiB
Go

package main
import (
"errors"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type config struct {
listenAddr string
gateway *url.URL
webDir string
logLevel logrus.Level
}
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
if err := newCommand().Execute(); err != nil {
logrus.WithField("service", "control-plane").WithError(err).Error("service stopped")
os.Exit(1)
}
}
func newCommand() *cobra.Command {
command := &cobra.Command{
Use: "control-plane",
Short: "Run the CreatorHub control plane",
Args: cobra.NoArgs,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(command *cobra.Command, _ []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
logrus.SetLevel(cfg.logLevel)
logrus.WithFields(logrus.Fields{
"service": "control-plane",
"listen_addr": cfg.listenAddr,
"docker_gateway": cfg.gateway.String(),
}).Info("service starting")
return newHandler(cfg.gateway, cfg.webDir).Listen(cfg.listenAddr, fiber.ListenConfig{
GracefulContext: command.Context(),
DisableStartupMessage: true,
})
},
}
return command
}
func loadConfig() (config, error) {
v := viper.New()
v.SetDefault("listen_addr", ":8080")
v.SetDefault("docker_gateway_url", "http://127.0.0.1:8081")
v.SetDefault("web_dir", "web/dist")
v.SetDefault("log_level", "info")
_ = v.BindEnv("listen_addr", "LISTEN_ADDR")
_ = v.BindEnv("docker_gateway_url", "DOCKER_GATEWAY_URL")
_ = v.BindEnv("web_dir", "WEB_DIR")
_ = v.BindEnv("log_level", "LOG_LEVEL")
gateway, err := url.Parse(v.GetString("docker_gateway_url"))
if err != nil || gateway.Host == "" || (gateway.Scheme != "http" && gateway.Scheme != "https") {
return config{}, errors.New("DOCKER_GATEWAY_URL must be an http(s) URL with a host")
}
level, err := logrus.ParseLevel(v.GetString("log_level"))
if err != nil {
return config{}, errors.New("LOG_LEVEL must be panic, fatal, error, warn, info, debug, or trace")
}
cfg := config{
listenAddr: strings.TrimSpace(v.GetString("listen_addr")),
gateway: gateway,
webDir: strings.TrimSpace(v.GetString("web_dir")),
logLevel: level,
}
if cfg.listenAddr == "" {
return config{}, errors.New("LISTEN_ADDR must not be empty")
}
if err := validateListenAddr(cfg.listenAddr); err != nil {
return config{}, err
}
if cfg.webDir == "" {
return config{}, errors.New("WEB_DIR must not be empty")
}
return cfg, nil
}
func validateListenAddr(addr string) error {
_, port, err := net.SplitHostPort(addr)
if err != nil {
return errors.New("LISTEN_ADDR must be a host:port address")
}
number, err := strconv.Atoi(port)
if err != nil || number < 1 || number > 65535 {
return errors.New("LISTEN_ADDR port must be 1..65535")
}
return nil
}
func newHandler(gateway *url.URL, webDirectory string) *fiber.App {
proxy := httputil.NewSingleHostReverseProxy(gateway)
originalDirector := proxy.Director
proxy.Director = func(request *http.Request) {
originalDirector(request)
request.URL.Path = "/v1/browsers" + strings.TrimPrefix(request.URL.Path, "/api/browsers")
request.Host = gateway.Host
}
proxyHandler := adaptor.HTTPHandler(proxy)
app := fiber.New(fiber.Config{
AppName: "CreatorHub control plane",
ReadTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
})
app.Get("/healthz", func(c fiber.Ctx) error {
c.Status(fiber.StatusNoContent)
return nil
})
app.All("/api/browsers", proxyHandler)
app.All("/api/browsers/*", proxyHandler)
app.Get("/*", spaHandler(webDirectory))
return app
}
func spaHandler(directory string) fiber.Handler {
return func(c fiber.Ctx) error {
path := filepath.Clean(strings.TrimPrefix(c.Path(), "/"))
if filepath.IsLocal(path) {
name := filepath.Join(directory, path)
if info, err := os.Stat(name); err == nil && !info.IsDir() {
return c.SendFile(name)
}
}
return c.SendFile(filepath.Join(directory, "index.html"))
}
}