Start learning free

LESSON 148 OF 173 · BACKEND: SHIPPING IT

Settings from the Environment

Practice

The shop's code is the same on your computer and on the server, but a few settings differ: the port it listens on, and where the database file is. Don't write them into the code. The server hands them to the program as environment variables: named text values that every program it starts can read.

In Go, os.Getenv(name) gives you a variable's text, or the empty string "" when it isn't set. cmp.Or(a, b) returns the first of its values that isn't empty, so it adds a default. The values are always text, so a number needs strconv.Atoi. For example, a program that reads how many times to retry and how to greet:

retries, _ := strconv.Atoi(cmp.Or(os.Getenv("RETRIES"), "3"))
greeting := cmp.Or(os.Getenv("GREETING"), "Hello")

Your file prints the settings the server would use. Then the check calls your loadSettings() three times, with different variables set, and prints the Settings it returns:

Port: 8000
Database: shop.db
Nothing set (your computer):
{Port:8000 DatabasePath:shop.db}
PORT=5000 and DATABASE_PATH=/data/shop.db (the server):
{Port:5000 DatabasePath:/data/shop.db}
Only PORT=10000:
{Port:10000 DatabasePath:shop.db}

Your task: the Settings type is already written. Write loadSettings(). It reads PORT as a number, with the default "8000", and DATABASE_PATH, with the default "shop.db", and returns a Settings with Port and DatabasePath set. In main, call it once and print the two settings after Port: and Database:.


Assignment
Follow the Coding Tutorial to read PORT and DATABASE_PATH from the environment with defaults, return them in a Settings, and print the settings the server would use.


Hint
os.Getenv gives "" for a variable that isn't set, and cmp.Or skips it for the default. Put the port inside strconv.Atoi( ) and ignore its error with _, but not the path: a path is text. Until the return is in, Go stops with missing return.


STEP 1 OF 7
    Ctrl + Enter to check