ministream/main.go

77 lines
1.4 KiB
Go
Raw Normal View History

2023-11-30 18:32:38 +00:00
package main
import (
"context"
2023-12-04 23:46:04 +00:00
"errors"
2023-11-30 18:32:38 +00:00
"fmt"
2023-12-05 00:25:17 +00:00
"log/slog"
2023-12-04 23:46:04 +00:00
"net/http"
2023-11-30 18:32:38 +00:00
"os"
"git.t-juice.club/torjus/ministream/server"
"github.com/urfave/cli/v2"
)
2023-11-30 22:56:33 +00:00
const Version = "v0.1.1"
2023-11-30 18:32:38 +00:00
2023-12-04 23:46:04 +00:00
type ctxKey string
const (
ctxKeyConfig ctxKey = "config"
)
2023-11-30 18:32:38 +00:00
func main() {
app := cli.App{
Name: "ministream",
Usage: "Small livestreaming platform.",
Commands: []*cli.Command{
{
2023-12-04 23:46:04 +00:00
Name: "serve",
Usage: "Start livestreaming server.",
Before: loadConfig,
Action: func(c *cli.Context) error {
cfg := configFromCtx(c.Context)
srv := server.NewServer(cfg)
2023-12-05 00:15:09 +00:00
srv.Addr = cfg.HTTP.ListenAddr
2023-12-05 00:25:17 +00:00
slog.Info("Starting HTTP-server", "addr", srv.Addr, "cfg", cfg)
2023-12-04 23:46:04 +00:00
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
2023-11-30 18:32:38 +00:00
return nil
},
},
},
Version: Version,
}
err := app.RunContext(context.Background(), os.Args)
if err != nil {
fmt.Println(err)
}
}
2023-12-04 23:46:04 +00:00
func loadConfig(c *cli.Context) error {
cfg, err := server.ConfigFromDefault()
if err != nil {
return err
}
c.Context = context.WithValue(c.Context, ctxKeyConfig, cfg)
return nil
}
func configFromCtx(ctx context.Context) *server.Config {
value := ctx.Value(ctxKeyConfig)
if value == nil {
panic("unable to load config")
}
config, ok := value.(*server.Config)
if !ok {
panic("config type assertion failed")
}
return config
}