23
loading...
This website collects cookies to deliver better user experience
source .env
every time we restart our machine or shell session, which can become a bit tedious. To make our lives easier, we will create bash scripts for starting and stopping server. While at it, we will also separate deploy for dev
and prod
environments. Let's start by creating new directory internal/cli/
and file cli.go
inside of it with following content:package cli
import (
"flag"
"fmt"
"os"
)
func usage() {
fmt.Print(`This program runs RGB backend server.
Usage:
rgb [arguments]
Supported arguments:
`)
flag.PrintDefaults()
os.Exit(1)
}
func Parse() {
flag.Usage = usage
env := flag.String("env", "dev", `Sets run environment. Possible values are "dev" and "prod"`)
flag.Parse()
fmt.Println(*env)
}
-env
option. Finally, parse all CLI flags with flag.Parse()
. For the moment we don't do anything smart with that value, we are only printing it. But that will change latter when we add logging. For now let's use this by updating cmd/rgb/main.go
file:package main
import (
"rgb/internal/cli"
"rgb/internal/conf"
"rgb/internal/server"
)
func main() {
cli.Parse()
server.Start(conf.NewConfig())
}
scripts/
. Inside of it we will add our first script, deploy.sh
:#! /bin/bash
# default ENV is dev
env=dev
while test $# -gt 0; do
case "$1" in
-env)
shift
if test $# -gt 0; then
env=$1
fi
# shift
;;
*)
break
;;
esac
done
cd ../../rgb
source .env
go build -o cmd/rgb/rgb cmd/rgb/main.go
cmd/rgb/rgb -env $env &
env=dev
which means that dev environment will be selected by default. After that we are reading arguments passed to this script, and if we found -env
argument, we will set env
variable to passed value of that argument. This is done inside of while loop. When env
variable is set, change directory to project root, source ENV variables and then run go build -o cmd/rgb/rgb cmd/rgb/main.go
. This will create executable file named cmd/rgb/rgb
which we can run to start our server. When app is built, we are starting server with cmd/rgb/rgb -env $env &
which passes value of env
variable as -env
flag to our server and then starts it in background because of $
flag.stop.sh
script, also inside of scripts/
directory:#! /bin/bash
kill $(pidof rgb)
rgb
app and then kills that process.chmod +x deploy.sh
chmod +x stop.sh
scripts/
directory and running:./deploy.sh
./stop.sh