go
60 lines · 7 steps
A thread-safe config singleton in Go
Load application configuration from the environment exactly once, safely, using sync.Once.
Explained by
highlit
1package config
2
3import (
4 "fmt"
5 "os"
6 "strconv"
7 "sync"
8 "time"
9)
10
11type Config struct {
12 DatabaseURL string
13 HTTPPort int
14 RequestTimeout time.Duration
15 Debug bool
16}
17
18var (
19 instance *Config
20 once sync.Once
21 loadErr error
22)
23
24func Get() (*Config, error) {
25 once.Do(func() {
26 instance, loadErr = load()
27 })
28 return instance, loadErr
29}
30
31func load() (*Config, error) {
32 dbURL := os.Getenv("DATABASE_URL")
33 if dbURL == "" {
34 return nil, fmt.Errorf("DATABASE_URL is required")
35 }
36
37 port, err := strconv.Atoi(getEnv("HTTP_PORT", "8080"))
38 if err != nil {
39 return nil, fmt.Errorf("invalid HTTP_PORT: %w", err)
40 }
41
42 timeout, err := time.ParseDuration(getEnv("REQUEST_TIMEOUT", "30s"))
43 if err != nil {
44 return nil, fmt.Errorf("invalid REQUEST_TIMEOUT: %w", err)
45 }
46
47 return &Config{
48 DatabaseURL: dbURL,
49 HTTPPort: port,
50 RequestTimeout: timeout,
51 Debug: getEnv("DEBUG", "false") == "true",
52 }, nil
53}
54
55func getEnv(key, fallback string) string {
56 if v, ok := os.LookupEnv(key); ok {
57 return v
58 }
59 return fallback
60}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1sync.Once guarantees initialization runs exactly once even under concurrent access.
- 2Caching both the result and its error lets every caller see the same outcome without re-running the work.
- 3Validating and parsing environment variables at load time turns config mistakes into clear startup errors.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
python
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent
How a Django settings module is wired
configuration
environment-variables
middleware
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-thread-safe-config-singleton-in-go-explained-go-7f9a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.