start.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package cli
  2. import (
  3. "net"
  4. "net/http"
  5. "github.com/annybs/ezdb"
  6. "github.com/annybs/shorty/internal/api"
  7. "github.com/annybs/shorty/internal/types"
  8. )
  9. type StartCmd struct {
  10. AllPath string `help:"All-path (SHORTY_ALL_PATH)" default:"${all_path}"`
  11. DatabasePath string `short:"d" help:"Database path (SHORTY_DATABASE_PATH)" default:"${database_path}"`
  12. Host string `short:"h" help:"HTTP bind host (SHORTY_HOST)" default:"${host}"`
  13. Port string `short:"p" help:"HTTP port (SHORTY_PORT)" default:"${port}"`
  14. Token string `short:"t" help:"Bearer token (SHORTY_TOKEN)" default:"${token}"`
  15. }
  16. func (c *StartCmd) Run(ctx *Context) error {
  17. errc := make(chan error)
  18. marshaler := ezdb.JSON[*types.Redirect](func() *types.Redirect {
  19. return &types.Redirect{}
  20. })
  21. db := ezdb.Memory(
  22. ezdb.LevelDB(c.DatabasePath, marshaler, nil),
  23. )
  24. if err := db.Open(); err != nil {
  25. return err
  26. }
  27. a := &api.API{
  28. DB: db,
  29. Log: ctx.Log,
  30. AllPath: c.AllPath,
  31. Token: c.Token,
  32. }
  33. addr := net.JoinHostPort(c.Host, c.Port)
  34. go func() {
  35. errc <- http.ListenAndServe(addr, a)
  36. }()
  37. ctx.Log.Info().Msgf("Listening at %s", addr)
  38. return <-errc
  39. }