Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
101: Dependency Injection Without a Framework in Go
Think about a professional coffee machine. If the manufacturer hard-wired the machine to only accept one specific brand of coffee beans from one specific farm in Ethiopia, the machine would be useless the moment that farm went out of business or you decided you preferred a Colombian roast. To make the machine flexible, the engineers gave it a hopper. The hopper doesn't care who grew the beans; it just cares that the beans are the right size and shape. By providing a "slot" for the beans, the machine is now decoupled from the source.
In Go, Dependency Injection (DI) is exactly that hopper. Instead of a struct creating its own dependencies (hard-wiring the beans), you design the struct to accept those dependencies from the outside (the hopper). When people talk about "DI Frameworks," they're usually talking about complex tools that automate this, but in Go, we generally don't need them. All you need is a constructor and an interface.
The Trap of the Hard-Coded Database
I've seen this mistake in almost every junior dev's first Go project. They create a service and instantiate the database client right inside the constructor. It looks like this:
type UserService struct {
db *PostgresClient
}
func NewUserService() *UserService {
// This is the "hard-wired" mistake.
// The service is now stuck with Postgres forever.
return &UserService{
db: NewPostgresClient("conn_string"),
}
}
The problem here is obvious: you can't test this UserService without a running Postgres database. Your tests will be slow, flaky, and require a Docker container just to check if a user's email is valid. You've tied your business logic to your infrastructure.
Defining the Contract
To fix this, we move from concrete types to interfaces. We define what the UserService needs, not what it is. This is our "bean specification."
// UserStore defines the behavior we need.
type UserStore interface {
GetUser(id string) (*User, error)
}
type UserService struct {
store UserStore // Note: we use the interface, not the concrete PostgresClient
}
// NewUserService now "injects" the dependency via the constructor.
func NewUserService(s UserStore) *UserService {
return &UserService{
store: s,
}
}
Now, UserService doesn't know or care if it's talking to Postgres, MongoDB, or a hard-coded map in memory. It just knows that whatever it was given has a GetUser method.
Swapping Implementations for Testing
This is where the magic happens. Since we're using an interface, we can create a "Mock" store for our tests. I personally find this to be the single biggest productivity boost in Go development because your unit tests can run in milliseconds.
type MockUserStore struct {
mockUser *User
}
func (m *MockUserStore) GetUser(id string) (*User, error) {
return m.mockUser, nil
}
func TestUserService_GetUserName(t *testing.T) {
// We inject the mock instead of a real database
mock := &MockUserStore{mockUser: &User{Name: "Jane Doe"}}
service := NewUserService(mock)
name, _ := service.GetUserName("123")
if name != "Jane Doe" {
t.Errorf("Expected Jane Doe, got %s", name)
}
}
In your main.go, you'll do the actual wiring. You create the real Postgres client and pass it into the service. You've effectively moved the "decision" of which database to use to the very top level of your application, leaving your business logic clean and agnostic.
📋 Practical Task
Refactoring the Notification Dispatcher
You've been handed a piece of code for a NotificationService that is currently hard-coded to use a specific SendGridEmailClient. This is making the tests fail because the CI environment doesn't have an API key for SendGrid.
Your Task:
- Create a
Notifierinterface that defines aSend(message string) errormethod. - Modify the
NotificationServicestruct to use theNotifierinterface instead of the concreteSendGridEmailClient. - Update the
NewNotificationServiceconstructor to accept aNotifieras an argument. - Implement a
MockNotifierstruct that simply records if a message was sent, and use it to write a test that verifies the service calls theSendmethod correctly without actually sending an email.
There are no comments for now.