Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Gin Modes, Configuration and Environment

Understand Gin's debug, release and test modes, GIN_MODE, PORT and trusted proxies, how to load configuration from environment variables, and how to log to a file.

A web service behaves differently on your laptop and in production. On your laptop you want chatty logs and detailed errors. In production you want quiet logs, hidden internals, and settings that come from the environment rather than from the source code. Gin has a built-in notion of modes for the first part, and ordinary Go (os.Getenv) covers the second. This lesson covers both. It builds on Your First Gin App.

The three modes

Gin runs in one of three modes, stored in a package-level variable:

Mode Constant What changes
Debug (the default) gin.DebugMode Prints every registered route at startup, prints warnings and debug lines, templates can be reloaded
Release gin.ReleaseMode No debug output. Faster startup logs, quieter terminal
Test gin.TestMode Used in automated tests to keep output clean

You choose the mode in one of two ways. The environment variable is preferred because you do not need to recompile:

Terminal
GIN_MODE=release go run .

or in code, before you create the engine:

Go
func main() {
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	// ...
}

gin.Mode() returns the current mode as a string, which is handy for your own logic. In debug mode you will see warnings like [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. That message is Gin reminding you to set GIN_MODE=release when you deploy.

Debug mode does not change what your handlers return. It only changes Gin's own console output and a few developer conveniences. Whether your API reveals error details is your decision, as shown below.

Making your own code mode-aware

A common pattern is to show detailed errors in development and a generic message in production. The stand-in below reproduces Gin's mode switch with a small package-level variable, then uses it to decide how much an error response reveals.

Go Stand-in: a mode switch controlling error detail

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In release mode the database error text never reaches the client. That detail would help an attacker, so keep it in your server logs only. The chapter on authentication and security returns to hardening.

Configuration from the environment

Hard-coded ports and passwords do not belong in source code. The widely used approach for services (the "twelve-factor" style) is to read settings from environment variables, with sensible defaults for local work. Gin itself reads only GIN_MODE and PORT; everything else is up to you.

Go
type Config struct {
	Addr        string
	DatabaseURL string
	Mode        string
}

func loadConfig() Config {
	return Config{
		Addr:        getenv("ADDR", ":8080"),
		DatabaseURL: getenv("DATABASE_URL", "app.db"),
		Mode:        getenv("GIN_MODE", gin.DebugMode),
	}
}

func getenv(key, fallback string) string {
	if v, ok := os.LookupEnv(key); ok && v != "" {
		return v
	}
	return fallback
}

os.LookupEnv tells you whether the variable exists at all, which lets you distinguish "unset" from "set to an empty string". Here is that exact pattern, runnable:

Go Loading a config struct from environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Two habits pay off here. First, parse and validate at startup and fail fast with a clear message: a service that crashes immediately with MAX_BODY_BYTES: invalid syntax is easier to debug than one that misbehaves an hour later. Second, never commit secrets. Locally you can keep a .env file (ignored by git) and load it with a library such as godotenv, or simply export variables in your shell.

The port and address

r.Run() looks at the PORT variable when you pass no argument. Many hosting platforms set PORT for you, so r.Run() just works there. If you prefer your own variable name, pass the address explicitly:

Go
if err := r.Run(cfg.Addr); err != nil {
	log.Fatal(err)
}

Binding to 127.0.0.1:8080 accepts only local connections, which is useful behind a reverse proxy on the same machine. :8080 listens on all interfaces.

Trusted proxies

Behind a load balancer or a reverse proxy such as nginx or Cloudflare, the TCP connection comes from the proxy, not from the user. Gin's c.ClientIP() reads headers like X-Forwarded-For, but it only believes them when the connection comes from a trusted proxy. Out of the box Gin trusts all proxies and prints a warning about it. Set the list explicitly:

Go
r := gin.Default()
if err := r.SetTrustedProxies([]string{"10.0.0.0/8", "192.168.1.5"}); err != nil {
	log.Fatal(err)
}

Pass nil to trust none, which makes ClientIP() return the direct peer address. Getting this right matters for rate limiting and audit logs, because otherwise anyone can fake their IP by sending an X-Forwarded-For header.

Where the logs go

By default gin.Default() writes request logs to standard output and errors to standard error. You can redirect them, for example to a file and the console at the same time. Set the writers before calling gin.Default():

Go
f, _ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
gin.DefaultErrorWriter = io.MultiWriter(f, os.Stderr)

gin.DisableConsoleColor() // no ANSI colors when writing to files
r := gin.Default()

In containers it is better to log to standard output only and let the platform collect it. Logger and Recovery shows how to customize the format.

Customizing the route table print

In debug mode Gin prints each route when it is registered. You can change that output with gin.DebugPrintRouteFunc, for example to print JSON, or silence it by switching to release mode. This stand-in prints a route table in the same spirit:

Go Stand-in: printing a route table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Real Gin offers r.Routes(), which returns the same information as a slice of gin.RouteInfo (Method, Path, Handler), and the CLI-style output looks like [GIN-debug] GET /users/:id --> main.getUser (3 handlers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you switch Gin to release mode without recompiling?

    Gin reads GIN_MODE at startup. gin.SetMode(gin.ReleaseMode) does the same in code, but must run before the engine is created.
  2. 2. What does debug mode change?

    Mode affects Gin's logging and developer conveniences. Your handlers behave the same unless you write code that checks the mode.
  3. 3. Why is it risky to leave trusted proxies at the default behind a public load balancer?

    Gin only believes forwarding headers from trusted proxies. Trusting everyone lets any client spoof ClientIP().
  4. 4. What is the advantage of os.LookupEnv over os.Getenv?

    LookupEnv returns a second boolean that distinguishes an unset variable from one set to an empty string.

Summary

  • Gin has debug, release and test modes; set them with GIN_MODE or gin.SetMode before creating the engine.
  • Use release mode in production; it silences Gin's debug output.
  • Read configuration from environment variables with defaults, validate it at startup, and keep secrets out of source control.
  • r.Run() uses PORT when no address is given; pass an address for explicit control.
  • Configure SetTrustedProxies when you run behind a proxy so ClientIP() can be trusted.
  • Redirect gin.DefaultWriter before gin.Default() to log to a file; in containers prefer standard output.

Next: Structuring a Gin Project shows how to organize handlers, services and configuration as your app grows.