<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Wilburn on Medium]]></title>
        <description><![CDATA[Stories by Michael Wilburn on Medium]]></description>
        <link>https://medium.com/@michaelwilburn?source=rss-5719595b7588------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*89LU8pUZz--cV27L7mjoQw.jpeg</url>
            <title>Stories by Michael Wilburn on Medium</title>
            <link>https://medium.com/@michaelwilburn?source=rss-5719595b7588------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:30:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaelwilburn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Practical Guide to Configuration in Go: Flags, Files, and Environment Variables]]></title>
            <link>https://medium.com/@michaelwilburn/a-practical-guide-to-configuration-in-go-flags-files-and-environment-variables-4d3f1924a912?source=rss-5719595b7588------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d3f1924a912</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Michael Wilburn]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 20:33:00 GMT</pubDate>
            <atom:updated>2025-10-13T20:33:00.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsrdIE76iTh_oN-LEuOfRg.jpeg" /></figure><h3><strong>Introducción</strong></h3><p>Every serious Go application needs a reliable way to manage configuration values that change depending on where and how the program runs. These include database credentials, server ports, rate limits, API keys, and more.<br>Hardcoding such settings directly in the source code might work for early experiments, but it quickly becomes a problem as your project evolves.</p><blockquote>Configuration is the foundation upon which an application is built.</blockquote><p>It defines how your program behaves in development, staging, and production environments, and provides the flexibility needed for scaling, debugging, or deploying in the cloud.</p><p>In Go, there are several idiomatic ways to provide configuration to an application:</p><ul><li><strong>Command-line flags</strong> — convenient for quick customization at startup.</li><li><strong>Configuration files</strong> — structured data in formats such as JSON, YAML, or INI.</li><li><strong>Environment variables</strong> — a lightweight, portable, and secure way to configure applications in production, following the twelve-factor app methodology.</li></ul><p>Each method has its own strengths and trade-offs. In this guide, we’ll explore the three approaches mentioned earlier — starting from the simplest (command-line flags) to the most cloud-friendly (environment variables) — and walk through practical examples of how to implement them in Go.<br>By the end of the article, we’ll combine both flags and environment variables to build a more flexible and robust configuration system for Go applications.</p><h3><strong>Command-Line Flags</strong></h3><p>Command-line flags are one of the simplest and most idiomatic ways to pass configuration to a Go program.<br> They’re perfect for web servers or command-line tools that need quick, flexible setup — for example, choosing which network address the server should listen on.</p><p>Let’s look at a minimal web server that reads its port number and environment from command-line flags:</p><pre>touch main.go</pre><pre>package main<br><br>import (<br>   &quot;flag&quot;<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>)<br><br>// config holds the application configuration settings.<br>// These values are read from command-line flags.<br>type config struct {<br>   port int<br>   env  string<br>}<br><br>// application holds the dependencies for our web application.<br>type application struct {<br>   config config<br>   logger *log.Logger<br>}<br><br>func main() {<br>   var cfg config<br>  <br>   // Define command-line flags and link them to the config fields.<br>   flag.IntVar(&amp;cfg.port, &quot;port&quot;, 4000, &quot;API server port&quot;)<br>   flag.StringVar(&amp;cfg.env, &quot;env&quot;, &quot;development&quot;, &quot;Environment (development|staging|production)&quot;)<br>  <br>   // Parse the command-line flags.<br>   flag.Parse()<br>  <br>   // Initialize a logger to write log messages to standard output.<br>   logger := log.New(os.Stdout, &quot;&quot;, log.Ldate|log.Ltime)<br>  <br>   // Create an instance of the application struct, which holds our dependencies.<br>   app := &amp;application{<br>    config: cfg,<br>    logger: logger,<br>   }<br><br>   // Create a new HTTP request multiplexer (router).<br>   mux := http.NewServeMux()<br>  <br>   // Register the home handler for the root URL path.<br>   mux.HandleFunc(&quot;/&quot;, app.home)<br>  <br>   // Initialize and configure the HTTP server.<br>   srv := &amp;http.Server{<br>    Addr:    fmt.Sprintf(&quot;:%d&quot;, cfg.port),<br>    Handler: mux,<br>   }<br>  <br>   // Log a message to indicate that the server is starting.<br>   logger.Printf(&quot;starting %s server on %s&quot;, cfg.env, srv.Addr)<br>  <br>   // Start the HTTP server.<br>   // If ListenAndServe() returns an error, log it and exit.<br>   err := srv.ListenAndServe()<br>   logger.Fatal(err)<br>}<br><br>// home is a simple handler that writes a response to the client.<br>func (app *application) home(w http.ResponseWriter, r *http.Request) {<br>   w.Write([]byte(&quot;This is my home page&quot;))<br>}</pre><p>If we don’t specify any flags when running the application, it will use the default values declared in the flag definitions:<br> port 4000 and environment &quot;development&quot;.</p><pre>$ go run main.go<br>2025/10/10 10:11:38 starting development server on :4000</pre><p>On the other hand, if we provide flag values explicitly, the output will reflect those:</p><pre>$ go run main.go -port=3000 -env=production<br>2025/10/10 10:11:38 starting production server on :3000</pre><p>In Go, the flag package from the standard library makes it easy to define and parse options from the command line.</p><p>In the example above, we define two flags:</p><ul><li>port — which specifies the port number where the server will listen</li><li>env— which defines the current environment.</li></ul><p>After parsing the flags with flag.Parse(), we store their values in a config struct and inject that configuration into an application struct, along with a logger.<br> This pattern makes the application easier to configure, test, and maintain as it grows.</p><h3><strong>Configuration Files</strong></h3><p>While command-line flags are great for small projects or simple services, they can quickly become cumbersome as the number of configuration options grows.<br> For larger applications, <strong>configuration files</strong> offer a more structured and maintainable way to manage settings.</p><p>Configuration files make it easy to:</p><ul><li>Group related configuration values together.</li><li>Keep environment-specific settings outside the code.</li><li>Version-control and share configuration templates safely.</li></ul><p>Go doesn’t enforce a specific configuration format — you can choose <strong>JSON</strong>, <strong>YAML</strong>, <strong>TOML</strong>, or even <strong>INI</strong> depending on your preference and ecosystem.</p><h4>Reading Configuration from JSON</h4><p>Let’s start with a simple example using <strong>JSON</strong>, one of the most common formats.</p><p>In another folder.</p><pre>touch config.json main.go</pre><pre>{<br>    &quot;port&quot;: 4000,<br>    &quot;env&quot;: &quot;development&quot;<br>}</pre><pre>package main<br><br>import (<br>   &quot;encoding/json&quot;<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>)<br><br>// config holds the application configuration settings.<br>// These values are loaded from a JSON file.<br>type config struct {<br>   Port int    `json:&quot;port&quot;`<br>   Env  string `json:&quot;env&quot;`<br>}<br><br>// application holds the dependencies for our web application.<br>type application struct {<br> config config<br> logger *log.Logger<br>}<br><br>func main() {<br>   var Cfg config<br><br>   // Open the configuration file.<br>   file, err := os.Open(&quot;config.json&quot;)<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br>   defer file.Close()<br><br>   // Decode the JSON configuration into the config struct.<br>   decoder := json.NewDecoder(file)<br>   err = decoder.Decode(&amp;Cfg)<br>   if err != nil {<br>      fmt.Println(&quot;Error decoding JSON:&quot;, err)<br>      return<br>   }<br>  <br>   // Initialize a logger to write log messages to standard output.<br>   logger := log.New(os.Stdout, &quot;&quot;, log.Ldate|log.Ltime)<br>  <br>   // Create an instance of the application struct to hold our dependencies.<br>   app := &amp;application{<br>      config: Cfg,<br>      logger: logger,<br>   }<br>  <br>   // Create a new HTTP request multiplexer (router).<br>   mux := http.NewServeMux()<br>  <br>   // Register the home handler for the root URL path.<br>   mux.HandleFunc(&quot;/&quot;, app.home)<br>  <br>   // Initialize and configure the HTTP server.<br>   srv := &amp;http.Server{<br>      Addr:    fmt.Sprintf(&quot;:%d&quot;, Cfg.Port),<br>      Handler: mux,<br>   }<br>  <br>   // Log a message to indicate that the server is starting.<br>   logger.Printf(&quot;starting %s server on %s&quot;, Cfg.Env, srv.Addr)<br>  <br>   // Start the HTTP server.<br>   // If ListenAndServe() returns an error, log it and exit.<br>   err = srv.ListenAndServe()<br>   logger.Fatal(err)<br>}<br><br>// home is a simple handler that writes a response to the client.<br>func (app *application) home(w http.ResponseWriter, r *http.Request) {<br>   w.Write([]byte(&quot;This is my home page&quot;))<br>}</pre><pre>$ go run main.go<br>2025/10/10 10:11:38 starting development server on :4000</pre><h4><em>Explanation</em></h4><p>The configuration file is opened and parsed with Go’s standard encoding/json package.<br>Struct field tags like `json:&quot;port&quot;` tell the decoder how to map JSON keys to struct fields.<br>This approach allows you to easily switch configuration files between environments — for example:</p><ul><li>config.development.json</li><li>config.staging.json</li><li>config.production.json</li></ul><p>One <strong>drawback</strong> of JSON is that it strictly enforces its syntax, so you can’t add inline comments or annotations in configuration files which makes it less convenient for large or frequently edited setups.</p><h4><strong>Reading Configuration from YAML</strong></h4><p>YAML files are a very popular choice for configuration because they are <strong>human-readable</strong>, support <strong>comments</strong>, and handle <strong>nested structures</strong> gracefully — something that JSON doesn’t do as well.</p><p>In Go, the gopkg.in/yaml.v3 package makes it straightforward to decode YAML directly into Go structs, keeping your configuration <strong>type-safe, human-friendly, and easy to maintain</strong>.</p><p>Let’s create another folder and code the next example.</p><pre>touch config.yaml main.go</pre><pre># A comment line<br>port: 4000<br>env: development</pre><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>  <br>   &quot;gopkg.in/yaml.v3&quot;<br>)<br><br>// config holds the application configuration settings.<br>// These values are loaded from a YAML file.<br>type config struct {<br>   Port int    `yaml:&quot;port&quot;`<br>   Env  string `yaml:&quot;env&quot;`<br>}<br><br>// application holds the dependencies for our web application.<br>type application struct {<br>   config config<br>   logger *log.Logger<br>}<br><br>func main() {<br>   var cfg config<br>  <br>   // Open the YAML configuration file.<br>   file, err := os.Open(&quot;config.yaml&quot;)<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br>   defer file.Close()<br>  <br>   // Decode YAML content into the config struct.<br>   decoder := yaml.NewDecoder(file)<br>   err = decoder.Decode(&amp;cfg)<br>   if err != nil {<br>      log.Fatalf(&quot;Error decoding YAML: %v&quot;, err)<br>   }<br>  <br>   // Initialize a logger to write log messages to standard output.<br>   logger := log.New(os.Stdout, &quot;&quot;, log.Ldate|log.Ltime)<br>  <br>   // Create an instance of the application struct with the loaded config and logger.<br>   app := &amp;application{<br>      config: cfg,<br>      logger: logger,<br>   }<br>  <br>   // Create a new HTTP multiplexer (router).<br>   mux := http.NewServeMux()<br>  <br>   // Register the home handler for the root URL path.<br>   mux.HandleFunc(&quot;/&quot;, app.home)<br>  <br>   // Initialize and configure the HTTP server.<br>   srv := &amp;http.Server{<br>      Addr:    fmt.Sprintf(&quot;:%d&quot;, cfg.Port),<br>      Handler: mux,<br>   }<br>  <br>   // Log a message to indicate that the server is starting.<br>   logger.Printf(&quot;starting %s server on %s&quot;, cfg.Env, srv.Addr)<br>  <br>   // Start the HTTP server and log any errors.<br>   err = srv.ListenAndServe()<br>   logger.Fatal(err)<br>}<br><br>// home is a simple handler that writes a response to the client.<br>func (app *application) home(w http.ResponseWriter, r *http.Request) {<br>   w.Write([]byte(&quot;This is my home page&quot;))<br>}</pre><pre>$ go run main.go<br>2025/10/10 10:11:38 starting development server on :4000</pre><p>Configuration files give your Go applications structure and clarity.<br> Whether you choose JSON or YAML depends on your team’s preferences and deployment setup — but both allow you to keep your configuration organized, versioned, and separate from your codebase.</p><h4>Reading Configuration from INI Files</h4><p>Before YAML and JSON became popular, many applications — especially system utilities and older software — used the <strong>INI format</strong> for configuration.<br> It’s simple, lightweight, and easy to read, though less structured and type-safe compared to YAML or JSON.</p><p>At last, let’s look at one more classic way to manage configurations in Go using .ini files.</p><p>While Go doesn’t include native support for this format, several community packages make it easy to parse.<br> A reliable and actively maintained option is <a href="https://pkg.go.dev/gopkg.in/ini.v1">gopkg.in/ini.v1</a>.</p><p>In another folder. Let’s create a small example:</p><pre>touch config.ini main.go</pre><pre>; A comment line<br>[server]<br>port = 4000<br>env = development  ; another comment<br><br>[db]<br>dsn = postgres://user:password@localhost/dbname?sslmode=disable</pre><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br><br>   &quot;gopkg.in/gcfg.v1&quot;<br>)<br><br>// config holds the application configuration settings.<br>// These values are loaded from a .ini file.<br>// Note: Sections in the .ini file map to nested structs.<br>type config struct {<br>   Server struct {<br>      Port int<br>      Env  string<br>   }<br>   DB struct {<br>      DSN string<br>   }<br>}<br><br>// application holds the dependencies for our web application.<br>type application struct {<br>   config config<br>   logger *log.Logger<br>}<br><br>func main() {<br>   var cfg config<br><br>   // Read configuration values from the .ini file into the cfg struct.<br>   err := gcfg.ReadFileInto(&amp;cfg, &quot;config.ini&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to parse config file: %v&quot;, err)<br>   }<br><br>   // Initialize a logger to write log messages to standard output.<br>   logger := log.New(os.Stdout, &quot;&quot;, log.Ldate|log.Ltime)<br><br>   // Create an instance of the application struct with the loaded config and logger.<br>   app := &amp;application{<br>      config: cfg,<br>      logger: logger,<br>   }<br><br>   // Create a new HTTP multiplexer (router).<br>   mux := http.NewServeMux()<br><br>   // Register the home handler for the root URL path.<br>   mux.HandleFunc(&quot;/&quot;, app.home)<br><br>   // Initialize and configure the HTTP server.<br>   srv := &amp;http.Server{<br>      Addr:    fmt.Sprintf(&quot;:%d&quot;, cfg.Server.Port),<br>      Handler: mux,<br>   }<br><br>   // Log information about the running server.<br>   logger.Printf(&quot;starting %s server on %s&quot;, cfg.Server.Env, srv.Addr)<br>   logger.Printf(&quot;connecting to database with DSN: %s (never log credentials in production!)&quot;, cfg.DB.DSN)<br><br>   // Start the HTTP server and log any errors.<br>   err = srv.ListenAndServe()<br>   logger.Fatal(err)<br>}<br><br>// home is a simple handler that writes a response to the client.<br>func (app *application) home(w http.ResponseWriter, r *http.Request) {<br>   w.Write([]byte(&quot;This is my home page&quot;))<br>}</pre><pre>$ go run main.go<br>2025/10/10 10:11:38 starting development server on :4000</pre><h4>Explanation</h4><p>The .ini format organizes settings into <strong>sections</strong>, making it intuitive and compact.<br> In this example, the [server] section holds web server configuration, and the [db] section contains database connection details.</p><p>The gopkg.in/gcfg.v1 package maps these sections directly into nested Go structs, preserving type safety and readability.<br> However, .ini files are best suited for smaller applications or legacy systems — for modern and cloud-oriented setups, YAML or environment variables tend to scale better.</p><h3>Loading Environment Variables from a .env File</h3><p>When working locally, exporting environment variables manually can quickly become tedious.<br> A common practice — especially inspired by the Node.js and Python ecosystems — is to use a .env file to store environment variables in key-value format.</p><p>To load these values automatically in Go, we can use the github.com/joho/godotenv package.</p><p>A common and clean way to configure Go applications is through <strong>environment variables</strong>. This approach is simple, portable, and fits well with both development and production environments.</p><pre>touch .env main.go</pre><pre>PORT=4000<br>ENV=development</pre><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>   &quot;strconv&quot;<br>  <br>   &quot;github.com/joho/godotenv&quot;<br>)<br><br>// config holds the application configuration settings.<br>// These values are loaded from environment variables or a .env file.<br>type config struct {<br>   Port int<br>   Env  string<br>}<br><br>// application holds the dependencies for our web application.<br>type application struct {<br>   config config<br>   logger *log.Logger<br>}<br><br>func main() {<br>   var cfg config<br>  <br>   // Load environment variables from the .env file.<br>   // If the file is missing or unreadable, we fail immediately.<br>   err := godotenv.Load()<br>   if err != nil {<br>    log.Fatalf(&quot;Failed to load .env file: %v&quot;, err)<br>   }<br>  <br>   // Read the PORT variable from the environment and convert it to an integer.<br>   portStr := os.Getenv(&quot;PORT&quot;)<br>   cfg.Port, err = strconv.Atoi(portStr)<br>   if err != nil {<br>    log.Fatalf(&quot;Invalid PORT value: %v&quot;, err)<br>   }<br>  <br>   // Read the ENV variable to determine the environment type.<br>   cfg.Env = os.Getenv(&quot;ENV&quot;)<br>  <br>   // Initialize a logger that writes log messages to the standard output.<br>   logger := log.New(os.Stdout, &quot;&quot;, log.Ldate|log.Ltime)<br>  <br>   // Create an instance of the application struct with the loaded config and logger.<br>   app := &amp;application{<br>    config: cfg,<br>    logger: logger,<br>   }<br>  <br>   // Create a new HTTP multiplexer (router).<br>   mux := http.NewServeMux()<br><br>   // Register the home handler for the root URL path.<br>   mux.HandleFunc(&quot;/&quot;, app.home)<br>  <br>   // Initialize and configure the HTTP server.<br>   srv := &amp;http.Server{<br>    Addr:    fmt.Sprintf(&quot;:%d&quot;, cfg.Port),<br>    Handler: mux,<br>   }<br>  <br>   // Log information about the running server.<br>   logger.Printf(&quot;starting %s server on %s&quot;, cfg.Env, srv.Addr)<br>  <br>   // Start the HTTP server and log any fatal errors.<br>   err = srv.ListenAndServe()<br>   logger.Fatal(err)<br>}<br><br>// home is a simple handler that writes a response to the client.<br>func (app *application) home(w http.ResponseWriter, r *http.Request) {<br>   w.Write([]byte(&quot;This is my home page&quot;))<br>}</pre><pre>$ go run main.go<br>2025/10/10 10:11:38 starting development server on :4000</pre><h3>Explanation</h3><p><strong>godotenv.Load() </strong>— Reads variables from the .env file and injects them into the environment.</p><p>If the file doesn’t exist, the application fails fast — this helps detect configuration issues early.</p><p><strong>os.Getenv()</strong> — Fetches the value of an environment variable. If not found, returns an empty string (&quot;&quot;).</p><p><strong>strconv.Atoi()</strong> — Converts the port string into an integer.</p><p>Using log.Fatalf() ensures the program stops immediately if the value is invalid.</p><p><strong>Strict configuration</strong><br>Notice there are no default fallbacks (if conditions). This enforces discipline: the app won’t run unless all required variables are properly set.</p><h3>Reading Configuration from Environment Variables</h3><p>In production environments (like servers, Docker containers, or CI/CD pipelines), configuration is usually provided through <strong>environment variables</strong>.<br> This keeps sensitive data (like credentials) outside your code and makes your application portable across different environments.</p><p>Let’s see how to configure our Go app directly from environment variables — without any .env file</p><p>If you’re working on a remote server or a deployed environment, it’s common to define these variables permanently in your shell’s profile file, such as <strong>~/.zprofile</strong> or <strong>~/.bash_profile</strong>.<br> This ensures that the variables are automatically loaded in every new terminal session.</p><pre># Export environment variables<br>export PORT=4000<br>export ENV=production</pre><p>You can verify they were set correctly by running:</p><pre>echo $PORT<br>echo $ENV</pre><blockquote>💡 <strong>Note:</strong><br> When deploying to cloud platforms like <strong>Render</strong>, <strong>Railway</strong>, <strong>Fly.io</strong>, <strong>Vercel</strong>, or <strong>Cloudflare Workers</strong>, you don’t need to export variables manually.<br> These platforms provide a <strong>web dashboard</strong> or <strong>deployment settings form</strong> where you can define environment variables.<br> At runtime, your Go application can access them the same way — through os.Getenv</blockquote><h3>Combining Environment Variables and Flags</h3><p>Now let’s see the best of both worlds — combining <strong>environment variables</strong> with <strong>command-line flags</strong>.<br> This pattern lets you define sane defaults, override them via env vars, and still have the option to change them quickly from the terminal.</p><p>In another folder, create a new file:</p><pre>touch main.go</pre><pre>package main<br><br>import (<br>   &quot;flag&quot;<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>)<br><br>// config holds the application configuration settings.<br>// These values are read from command-line flags.<br>type config struct {<br>   port string<br>   env  string<br>}<br><br>// application holds the dependencies for our web application.<br>type application struct {<br>   config config<br>   logger *log.Logger<br>}<br><br>func main() {<br>   var cfg config<br>  <br>   // Read env vars (if any)<br>   defaultPort := os.Getenv(&quot;PORT&quot;)<br>   if defaultPort == &quot;&quot; {<br>      defaultPort = &quot;4000&quot;<br>   }<br>  <br>   defaultEnv := os.Getenv(&quot;ENV&quot;)<br>   if defaultEnv == &quot;&quot; {<br>      defaultEnv = &quot;development&quot;<br>   }<br>  <br>   // Define flags, using env vars as defaults<br>   flag.StringVar(&amp;cfg.port, &quot;port&quot;, defaultPort, &quot;API server port&quot;)<br>   flag.StringVar(&amp;cfg.env, &quot;env&quot;, defaultEnv, &quot;Environment (development|staging|production)&quot;)<br>   flag.Parse()<br>  <br>   // Parse the command-line flags.<br>   flag.Parse()<br>  <br>   // Initialize a logger to write log messages to standard output.<br>   logger := log.New(os.Stdout, &quot;&quot;, log.Ldate|log.Ltime)<br>  <br>   // Create an instance of the application struct, which holds our dependencies.<br>   app := &amp;application{<br>      config: cfg,<br>      logger: logger,<br>   }<br>  <br>   // Create a new HTTP request multiplexer (router).<br>   mux := http.NewServeMux()<br>  <br>   // Register the home handler for the root URL path.<br>   mux.HandleFunc(&quot;/&quot;, app.home)<br>  <br>   // Initialize and configure the HTTP server.<br>   srv := &amp;http.Server{<br>      Addr:    fmt.Sprintf(&quot;:%s&quot;, cfg.port),<br>      Handler: mux,<br>   }<br>  <br>   // Log a message to indicate that the server is starting.<br>   logger.Printf(&quot;starting %s server on %s&quot;, cfg.env, srv.Addr)<br>  <br>   // Start the HTTP server.<br>   // If ListenAndServe() returns an error, log it and exit.<br>   err := srv.ListenAndServe()<br>   logger.Fatal(err)<br>}<br><br>// home is a simple handler that writes a response to the client.<br>func (app *application) home(w http.ResponseWriter, r *http.Request) {<br>   w.Write([]byte(&quot;This is my home page&quot;))<br>}</pre><h4>Running the Application</h4><p>With the default environment values:</p><pre>$ go run main.go<br>2025/10/10 10:11:38 starting development server on :4000</pre><p>Or, if you want to define specific values directly via flags:</p><pre>$ go run main.go -port 3000 -env production<br>2025/10/10 10:11:38 starting production server on :3000</pre><h3>Conclusion</h3><p>Using both <strong>environment variables</strong> and <strong>command-line flags</strong> gives you flexible, production-grade configuration. <br>You can store persistent values in the environment (for CI/CD or Docker) and override them temporarily using flags — perfect for local testing, staging deployments, or quick experiments.</p><p>This layered configuration approach — Flags → Files → Environment — is idiomatic Go and scales gracefully from small CLIs to large web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d3f1924a912" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>