Move host and port to environment variables

This commit is contained in:
Jacob Gunther
2022-03-10 20:18:41 -06:00
parent 1a22b02cc6
commit 16d5c9689e
5 changed files with 26 additions and 6 deletions

View File

@@ -1,5 +1,3 @@
host: 0.0.0.0
port: 3001
redis:
uri: 127.0.0.1:6379
database: 0

1
go.mod
View File

@@ -5,6 +5,7 @@ go 1.17
require (
github.com/buaazp/fasthttprouter v0.1.1
github.com/go-redis/redis/v8 v8.11.4
github.com/joho/godotenv v1.4.0
github.com/valyala/fasthttp v1.34.0
golang.org/x/image v0.0.0-20220302094943-723b81ca9867
gopkg.in/yaml.v2 v2.4.0

2
go.sum
View File

@@ -29,6 +29,8 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.15.0 h1:xqfchp4whNFxn5A4XFyyYtitiWI8Hy5EW59jEwcyL6U=
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=

View File

@@ -7,8 +7,6 @@ import (
)
type Configuration struct {
Host string `yaml:"host"`
Port uint16 `yaml:"port"`
Redis struct {
URI string `yaml:"uri"`
Database int `yaml:"database"`

View File

@@ -5,13 +5,18 @@ import (
"log"
"main/src/redis"
"main/src/routes"
"os"
"strconv"
"time"
"github.com/buaazp/fasthttprouter"
"github.com/joho/godotenv"
"github.com/valyala/fasthttp"
)
var (
host string = "127.0.0.1"
port uint16 = 3000
config *Configuration = &Configuration{}
r *redis.Redis = &redis.Redis{}
)
@@ -19,6 +24,8 @@ var (
func init() {
var err error
godotenv.Load()
if err = config.ReadFile("config.yml"); err != nil {
log.Fatal(err)
}
@@ -31,6 +38,20 @@ func init() {
log.Printf("Successfully connected to Redis (%s)\n", time.Since(start))
if value, ok := os.LookupEnv("HOST"); ok {
host = value
}
if value, ok := os.LookupEnv("PORT"); ok {
parsedValue, err := strconv.ParseUint(value, 10, 16)
if err != nil {
log.Fatal(err)
}
port = uint16(parsedValue)
}
routes.InitRoutes(r)
}
@@ -50,7 +71,7 @@ func main() {
router.GET("/body/left/:user", routes.LeftBodyHandler)
router.GET("/body/right/:user", routes.RightBodyHandler)
log.Printf("Listening on %s:%d\n", config.Host, config.Port)
log.Printf("Listening on %s:%d\n", host, port)
log.Fatal(fasthttp.ListenAndServe(fmt.Sprintf("%s:%d", config.Host, config.Port), router.Handler))
log.Fatal(fasthttp.ListenAndServe(fmt.Sprintf("%s:%d", host, port), router.Handler))
}