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 serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 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.