|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/gofiber/fiber/v2" |
| 6 | + zlog "github.com/rs/zerolog/log" |
| 7 | + "github.com/spf13/cobra" |
| 8 | + "github.com/spf13/viper" |
| 9 | + "github.com/zackijack/go-project/internal/config" |
| 10 | + "github.com/zackijack/go-project/internal/helpers" |
| 11 | +) |
| 12 | + |
| 13 | +const startDesc = ` |
| 14 | +Start application on the HTTP-server. |
| 15 | +By default the HTTP-server will listen to host 0.0.0.0 & port 8080. |
| 16 | +However if you want to specify what host & port to use, just set via: |
| 17 | +
|
| 18 | + - argument: |
| 19 | +
|
| 20 | + $ go-project start --host localhost --port 80 |
| 21 | +
|
| 22 | + - env variable: |
| 23 | +
|
| 24 | + $ export APP_HOST=localhost |
| 25 | + $ export APP_PORT=80 |
| 26 | +` |
| 27 | + |
| 28 | +var startCmd = &cobra.Command{ |
| 29 | + Use: "start", |
| 30 | + Aliases: []string{"run", "serve", "server"}, |
| 31 | + Short: "Start the application", |
| 32 | + Long: startDesc, |
| 33 | + Run: func(cmd *cobra.Command, args []string) { |
| 34 | + cfg, err := config.Load() |
| 35 | + if err != nil { |
| 36 | + zlog.Error().Err(err).Msg(helpers.ErrMsg("config")) |
| 37 | + } |
| 38 | + |
| 39 | + start(cfg) |
| 40 | + }, |
| 41 | +} |
| 42 | + |
| 43 | +func init() { |
| 44 | + startCmd.Flags().StringP("host", "H", "0.0.0.0", "host address to serve the application on") |
| 45 | + startCmd.Flags().IntP("port", "P", 8080, "port to serve the application on") |
| 46 | + |
| 47 | + // Bind to config. |
| 48 | + helpers.CheckErr(viper.BindPFlag("APP_HOST", startCmd.Flags().Lookup("host")), helpers.ErrMsg("config flag: host"), false) |
| 49 | + helpers.CheckErr(viper.BindPFlag("APP_PORT", startCmd.Flags().Lookup("port")), helpers.ErrMsg("config flag: port"), false) |
| 50 | + |
| 51 | + rootCmd.AddCommand(startCmd) |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +func start(cfg *config.Config) { |
| 56 | + addr := fmt.Sprintf("%s:%d", cfg.AppHost, cfg.AppPort) |
| 57 | + |
| 58 | + app := fiber.New() |
| 59 | + |
| 60 | + // Get /johnny. |
| 61 | + app.Get("/:name", func(c *fiber.Ctx) error { |
| 62 | + msg := fmt.Sprintf("Hello, %s 👋! from %s with ❤️", c.Params("name"), cfg.AppName) |
| 63 | + return c.SendString(msg) // => Hello, johnny 👋! from go-project with ❤️ |
| 64 | + }) |
| 65 | + |
| 66 | + zlog.Fatal().Err(app.Listen(addr)).Msg(helpers.ErrMsg("server")) |
| 67 | +} |
0 commit comments