Skip to content

Commit

Permalink
✨ feat: CLI support
Browse files Browse the repository at this point in the history
  • Loading branch information
shurco committed Jul 25, 2023
1 parent d1c4e0b commit e8609f1
Show file tree
Hide file tree
Showing 6 changed files with 123 additions and 115 deletions.
2 changes: 1 addition & 1 deletion .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ brews:
name: homebrew-tap
token: "{{ .Env.TAP_GITHUB_TOKEN }}"
homepage: https://github.com/shurco/litecart
description: "LiteCart - a very easy cart for selling digital products with Stripe payment."
description: "LiteCart - Open Source realtime cart in 1 file"
license: "MIT"

upx:
Expand Down
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd",
"args": ["-s"]
"args": ["serve"]
},
]
}
73 changes: 38 additions & 35 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package main

import (
"log"
"fmt"
"os"

"github.com/spf13/cobra"

app "github.com/shurco/litecart/internal"
)

Expand All @@ -14,42 +16,43 @@ var (
)

func main() {
flags := app.Flags{
Serve: true,
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Starts the web server (default to 127.0.0.1:8080)",
Run: func(cmd *cobra.Command, args []string) {
if err := app.NewApp(); err != nil {
os.Exit(1)
}
},
}

var versionCmd = &cobra.Command{
Use: "version",
Short: "Version of litecart",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("LiteCart v%s (%s) from %s", version, gitCommit, buildDate)
},
}

if err := app.NewApp(flags); err != nil {
log.Printf("%+v", err)
os.Exit(1)
var rootCmd = &cobra.Command{
Use: "litecart",
Short: "LiteCart CLI",
Long: "Open Source realtime cart in 1 file",
FParseErrWhitelist: cobra.FParseErrWhitelist{
UnknownFlags: true,
},
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
},
}
rootCmd.SetHelpCommand(&cobra.Command{
Use: "no-help",
Hidden: true,
})

rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
rootCmd.PersistentFlags().Lookup("help").Hidden = true

/*
rootCmd := &cobra.Command{
Use: "litecart",
Short: "Lightweight online store powered by stripe",
Long: "Lightweight online store powered by stripe",
Args: cobra.ArbitraryArgs,
Version: fmt.Sprintf("%s (%s), %s", version, gitCommit, buildDate),
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 {
if err := cmd.Usage(); err != nil {
log.Fatal(err)
}
return
}
if err := app.NewApp(flags); err != nil {
log.Printf("%+v", err)
os.Exit(1)
}
},
}
pf := rootCmd.PersistentFlags()
pf.BoolVarP(&flags.Serve, "serve", "s", false, "starts the web server (default to 127.0.0.1:8080)")
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
*/
rootCmd.AddCommand(serveCmd, versionCmd)
rootCmd.Execute()
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/google/uuid v1.3.0
github.com/pressly/goose/v3 v3.13.4
github.com/rs/zerolog v1.29.1
github.com/spf13/cobra v1.7.0
github.com/stripe/stripe-go/v74 v74.27.0
golang.org/x/crypto v0.11.0
modernc.org/sqlite v1.24.0
Expand All @@ -27,6 +28,7 @@ require (
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gofiber/template v1.8.2 // indirect
github.com/gofiber/utils v1.1.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/klauspost/compress v1.16.7 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
Expand All @@ -36,6 +38,7 @@ require (
github.com/mattn/go-sqlite3 v1.14.17 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.48.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
Expand Down
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHG
github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a h1:AP/vsCIvJZ129pdm9Ek7bH7yutN3hByqsMoNrWAxRQc=
github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -38,6 +39,8 @@ github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=
Expand Down Expand Up @@ -68,6 +71,11 @@ github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc=
github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
Expand Down
150 changes: 72 additions & 78 deletions internal/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,97 +28,91 @@ var (
MainDomain string
)

type Flags struct {
Serve bool
}

// NewApp is ...
func NewApp(flags Flags) error {
func NewApp() error {
DevMode = true
log := zerolog.New(os.Stderr).With().Timestamp().Logger()

if flags.Serve {
if err := fsutil.MkDirs(0775, "./uploads"); err != nil {
log.Err(err).Send()
return err
}
if err := fsutil.MkDirs(0775, "./uploads"); err != nil {
log.Err(err).Send()
return err
}

if err := queries.InitQueries(embedMigrations); err != nil {
log.Err(err).Send()
return err
}
db := queries.DB()

// web web server
var views *html.Engine
if DevMode {
views = html.New("../web/views", ".html")
views.Reload(true)
} else {
views = html.NewFileSystem(http.Dir("../web/views"), ".html")
}
views.Delims("{#", "#}")
views.AddFunc(
"arr", func(els ...any) []any {
return els
},
)

app := fiber.New(fiber.Config{
DisableStartupMessage: true,
Views: views,
})

app.Use(fiberzerolog.New(fiberzerolog.Config{
Logger: &log,
}))

app.Static("/", "../web/public")
app.Static("/uploads", "./uploads")

app.Use(func(c *fiber.Ctx) error {
// init install
mainPath := strings.Split(c.Path(), "/")[1]
if !db.IsInstalled() {
if c.Path() != "/_/install" && mainPath != "api" {
return c.Redirect("/_/install")
}
} else if c.Path() == "/_/install" {
return c.Redirect("/_")
if err := queries.InitQueries(embedMigrations); err != nil {
log.Err(err).Send()
return err
}
db := queries.DB()

// web web server
var views *html.Engine
if DevMode {
views = html.New("../web/views", ".html")
views.Reload(true)
} else {
views = html.NewFileSystem(http.Dir("../web/views"), ".html")
}
views.Delims("{#", "#}")
views.AddFunc(
"arr", func(els ...any) []any {
return els
},
)

app := fiber.New(fiber.Config{
DisableStartupMessage: true,
Views: views,
})

app.Use(fiberzerolog.New(fiberzerolog.Config{
Logger: &log,
}))

app.Static("/", "../web/public")
app.Static("/uploads", "./uploads")

app.Use(func(c *fiber.Ctx) error {
// init install
mainPath := strings.Split(c.Path(), "/")[1]
if !db.IsInstalled() {
if c.Path() != "/_/install" && mainPath != "api" {
return c.Redirect("/_/install")
}
} else if c.Path() == "/_/install" {
return c.Redirect("/_")
}

// init main domain
if MainDomain == "" {
hostname := strings.Split(c.Hostname(), ".")
if len(hostname) > 2 {
hostname = hostname[1:]
}
MainDomain = strings.Join(hostname, ".")
// init main domain
if MainDomain == "" {
hostname := strings.Split(c.Hostname(), ".")
if len(hostname) > 2 {
hostname = hostname[1:]
}
MainDomain = strings.Join(hostname, ".")
}

// check subdomain
if len(c.Subdomains()) > 0 {
if !db.CheckSubdomain(c.Subdomains()[0]) && !DevMode {
return c.Redirect(fmt.Sprintf("%s://%s", c.Protocol(), MainDomain), fiber.StatusMovedPermanently)
}
// check subdomain
if len(c.Subdomains()) > 0 {
if !db.CheckSubdomain(c.Subdomains()[0]) && !DevMode {
return c.Redirect(fmt.Sprintf("%s://%s", c.Protocol(), MainDomain), fiber.StatusMovedPermanently)
}
}

return c.Next()
})
return c.Next()
})

routes.SiteRoutes(app)
routes.AdminRoutes(app)
routes.ApiRoutes(app)
routes.NotFoundRoute(app)
routes.SiteRoutes(app)
routes.AdminRoutes(app)
routes.ApiRoutes(app)
routes.NotFoundRoute(app)

ln, err := net.Listen("tcp", fmt.Sprintf(":%d", 8080))
if err != nil {
log.Err(err).Send()
}
proxyListener := &proxyproto.Listener{Listener: ln}
if err := app.Listener(proxyListener); err != nil {
log.Err(err).Send()
}
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", 8080))
if err != nil {
log.Err(err).Send()
}
proxyListener := &proxyproto.Listener{Listener: ln}
if err := app.Listener(proxyListener); err != nil {
log.Err(err).Send()
}

return nil
Expand Down

0 comments on commit e8609f1

Please sign in to comment.