Environment Variables
The following example introduces the utilization of environment variables. First we check if the environment variable is set, is it hasn't then a default will be defined.
main.go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
)
func main() {
// Check if the environment variables exist and if not set a default
if len(os.Getenv("GO_APP_HOST")) == 0 {
os.Setenv("GO_APP_HOST", "0.0.0.0")
}
if len(os.Getenv("GO_APP_PORT")) == 0 {
os.Setenv("GO_APP_PORT", "8080")
}
// Set the variables using environment variables
serverHost := os.Getenv("GO_APP_HOST")
serverPort := os.Getenv("GO_APP_PORT")
// Define router
router := mux.NewRouter()
router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
})
// Configure HTTP server
srv := &http.Server{
Handler: router,
Addr: serverHost + ":" + serverPort,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
// Run HTTP server
log.Print("Starting server on " + serverHost + ":" + serverPort)
log.Fatal(srv.ListenAndServe())
}
With this code, you can now export an environment variable in your shell, for example:
And run the application:
Now it should start up on port 8000:
Unset it:
The application will fall back to the default port of 8080.
Refactor Project
I like to keep things organized, we can move the logic for defining variables from environment variables.
Create a new file called settings.go and define two functions, moving the logic from main.go, for example:
settings.go
package main
import (
"os"
)
func getServerHostVar() (serverHost string) {
if len(os.Getenv("GO_APP_HOST")) == 0 {
os.Setenv("GO_APP_HOST", "0.0.0.0")
}
serverHost = os.Getenv("GO_APP_HOST")
return
}
func getServerPortVar() (serverPort string) {
if len(os.Getenv("GO_APP_PORT")) == 0 {
os.Setenv("GO_APP_PORT", "8080")
}
serverPort = os.Getenv("GO_APP_PORT")
return
}
Then update main.go to utilise these functions for setting serverHost and serverPort:
main.go
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func main() {
// Set variables from environment variables
serverHost := getServerHostVar()
serverPort := getServerPortVar()
// Define router
router := mux.NewRouter()
router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
})
// Configure HTTP server
srv := &http.Server{
Handler: router,
Addr: serverHost + ":" + serverPort,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
// Run HTTP server
log.Print("Starting server on " + serverHost + ":" + serverPort)
log.Fatal(srv.ListenAndServe())
}