Columns › 2. Writing a service › Part 6
Layered Architecture and Dependency Injection in Go
分層架構與依賴注入
Split the order service into handler, service and repository layers: consumer-defined interfaces, constructor injection and a single composition root in main give you testable, swappable Go code without any DI framework.
In this article
- What this article solves
- Step 1: Separate the three responsibilities
- Step 2: Directories and packages
- Step 3: The consumer defines the interface
- Step 4: Constructor injection
- Step 5: Connect the three layers, keeping errors intact across them
- Step 6: Wire everything up in main
- Step 7: The payoff: swappable implementations and unit tests
- Common pitfalls
- Key takeaways
- Next
In the previous article, “net/http and Middleware in Go”, we used the standard library to give the order service routing, middleware and server timeouts. This article deals with the handler that keeps getting fatter: we split it into three layers with clear responsibilities and wire them together in the plainest way possible.
What this article solves
The order service from the previous article works, but everything is crammed into the handler: parsing JSON, checking fields, calculating the total, deciding the order status and writing data into a map, all in one function. With only two endpoints that is bearable, but as requirements grow, the problems arrive one after another:
- You cannot test the business rules. To verify "total calculation" or "an empty item list must be rejected", you first have to build an HTTP request and then dig the result out of the JSON response. The rules themselves are welded to HTTP.
- You cannot swap the storage. The data lives in a map; when the next article switches to a database, every handler has to be combed through.
- Rules are scattered everywhere. The same validation logic is copied into order creation, order updates and the back-office import; change one and forget the other two.
- Error semantics are muddled. The database's
sql.ErrNoRowsleaks all the way up to the handler, which then has to know which kind of database sits underneath before it can decide to return 404.
Layered architecture and dependency injection exist to solve exactly these problems. The terms sound heavyweight, but in Go they can be very light: no framework required, just three habits: split by responsibility, let the consumer define the interface, and pass dependencies in through the constructor. This article reshapes the order service step by step and explains the reasoning behind each decision.
Step 1: Separate the three responsibilities
If you take apart what happens between a request coming in and a response going out, there are really three kinds of work of completely different nature:
| Layer | Responsible for | Should not know |
|---|---|---|
| handler (transport) | Parsing path parameters and JSON, checking format, calling the service, translating results or errors into HTTP status codes | How the total is calculated, where data is stored |
| service (business rules) | The order rules: total calculation, status transitions from pending to paid or cancelled, which data must succeed or fail together | Whether the request is HTTP or gRPC, which database |
| repository (storage) | Saving and loading domain objects; translating low-level errors into domain errors | Why it is being saved, what happens afterwards |
There is also something every layer uses: the domain types, that is Order, Item, the order statuses, and domain errors such as ErrNotFound and ErrInvalid. They are pure data and pure functions; they depend on no layer, and every layer may depend on them.
Figure: Dependencies only point downwards; each layer knows only the interfaces it needs, and the domain types are shared by all layers.
The benefit of this split is that each layer changes for a different reason. If the API's field naming changes, only the handler moves; if the discount rules change, only the service moves; if you switch from memory to a database, only the repository moves. What software design calls the "single responsibility principle" means something concrete here: a file changes for only one reason.
Note that more layers are not better. Some tutorials add a DTO mapping layer, a use case layer and a domain service layer on top of the three; for a service with a handful of endpoints, those extra layers just make every change cross more files. Three layers is a sensible starting point; when one layer genuinely becomes complex, it is not too late to split it further.
Step 2: Directories and packages
Following the plan from “Go Project Layout and Go Modules”, the module is example.com/shop, each executable service has its own entry point under cmd/, and the business code lives in internal/ so that code outside the module cannot import it:
shop/
├── go.mod # module example.com/shop
├── cmd/
│ └── order/
│ └── main.go # composition root: builds every object, starts the server
└── internal/
├── order/
│ ├── order.go # domain types: Order, Item, statuses, domain errors
│ ├── handler.go # HTTP transport layer
│ ├── service.go # business rules, plus the Repository interface it needs
│ └── repository.go # storage implementations (in-memory, database)
└── platform/
└── httpx/ # shared middleware: RequestID, Logging, RecoverThis deliberately uses packages by domain rather than packages by technical role. Many projects coming from other languages create directories like controllers/, services/, models/ and repositories/, putting every domain's handlers together and every service together. In Go this is usually a bad idea, for three reasons:
- Package names lose their meaning. Callers end up writing
services.OrderServiceandmodels.Order, where the package name tells you nothing;order.Serviceandorder.Orderread more naturally. - Import cycles come easily. Go does not allow packages to import each other; once
servicesusesmodelsandmodelswants to call a helper inservices, you are stuck. With packages by domain, everything for one domain lives in one package, so there is nothing to import cyclically. - Changing one feature touches four directories. Split by domain, nearly all order-related changes are concentrated in the single
internal/order/directory.
Isn't it crowded to put three layers in one package? As long as files are split by responsibility, five or six files in a domain package is perfectly normal. When a domain grows to need finer division, or when “When to Split: Service Boundaries and Decomposition Strategies” later decides to turn it into a separate service, moving it out is cheap because it has always been a package with clear boundaries.
Step 3: The consumer defines the interface
This is the habit where Go differs most from many languages, and the most important one. In Java or C#, the common approach is for the storage layer to declare an IOrderRepository interface first, then write a class that explicitly implements it, and consumers reference that interface. Go interfaces are implemented implicitly: as long as a type has all the methods an interface requires, it satisfies that interface automatically, without any declaration.
This language feature leads to a design principle: an interface belongs with the code that uses it, and lists only the methods that code actually needs. The service needs two capabilities, "save an order" and "load an order", so it declares an interface with just those two methods in its own file:
// Snippet: internal/order/service.go
package order
import (
"context"
"fmt"
"time"
)
// Repository is the storage capability the service needs: defined by the
// consumer (the service), listing only the methods it actually calls.
type Repository interface {
Create(ctx context.Context, o *Order) error
Get(ctx context.Context, id int64) (Order, error)
}
type Service struct {
repo Repository
now func() time.Time
}
func NewService(repo Repository, now func() time.Time) *Service {
if repo == nil || now == nil {
panic("order.NewService: nil dependency")
}
return &Service{repo: repo, now: now}
}
func (s *Service) Place(ctx context.Context, userID int64, items []Item) (Order, error) {
total, err := Total(items)
if err != nil {
return Order{}, err
}
o := Order{UserID: userID, Items: items, Total: total, Status: StatusPending, CreatedAt: s.now()}
if err := s.repo.Create(ctx, &o); err != nil {
return Order{}, fmt.Errorf("place order: %w", err)
}
return o, nil
}This has several practical benefits:
- The interface is small. The concrete storage type might have a dozen methods (listing, pagination, statistics, bulk updates for the back office), but the service depends only on the two it uses. The smaller the interface, the easier it is to write a test double, and the less likely you are to be forced into changes because the storage layer gained a new method.
- The dependency points the right way. The service does not import the storage package; instead the storage layer "fits" the shape the service defines. This matters especially when the storage implementation lives in another package (for example a shared
internal/platform/postgres): the business rules are not recompiled when the database package changes, and they do not indirectly depend on a database driver. - Different consumers can have different interfaces. Back-office reporting needs "list orders in a date range"; it can define another interface with only that method in its own package, and the same concrete type satisfies both.
This is what the Go community means by "accept interfaces, return structs": function parameters take interfaces so callers can pass any implementation that fits; constructors return concrete types so consumers get the full method set and decide for themselves whether to use it as some interface. That is why NewService returns *Service and not some OrderService interface.
Tip: Don't give every type an interface up front just because "we might swap it one day". If there is only one implementation and no test needs to replace it, use the concrete type directly. When a second use case actually appears, extract the interface on the consumer side; in Go that is a very cheap refactor, because the implementation does not have to change at all.
Step 4: Constructor injection
The term "dependency injection" really means something simple: whatever an object needs is handed to it from outside, rather than the object creating it itself or fetching it from a global variable. In Go the most direct way is constructor parameters:
NewService(repo Repository, now func() time.Time): the service needs storage and "what time it is now", both provided by the caller.NewHandler(svc orderService, logger *slog.Logger): the handler needs the service and a logger, likewise passed in from outside.
Note the now func() time.Time parameter. The order's creation time could just call time.Now() directly, but then a test could never verify that "the creation time is set correctly", because the time differs on every run. Treat "get the current time" as a dependency too and inject it: production passes time.Now, tests pass a function that returns a fixed time, and the problem is solved. The same idea applies to random numbers, ID generators and external API clients: anything that makes results unpredictable is worth injecting.
Compared with other ways of injecting:
| Approach | How | Problem |
|---|---|---|
| Global variable | var DB *sql.DB, everyone uses it | Tests cannot replace it, execution order hides dependencies, parallel tests interfere |
Package init() creates it | Connects to the database on import | Importing the package has side effects; tests and tools are forced to connect |
| Setter injection | Create the object, then SetRepo(r) | The object is incomplete until configured; forget to set it and you get a nil panic at runtime |
| Constructor injection | NewService(repo, now) | The constructor gets long with many parameters, but anything missing shows up at compile time |
The biggest advantage of constructor injection is that an object is complete and usable the moment it is created. There is no "created but not yet configured" intermediate state. The NewService above does one more thing: it panics if a parameter is nil. That exposes wiring mistakes at startup, which beats crashing on a nil pointer when the first request arrives.
When a constructor's parameter list grows long (say more than five or six), it usually means one of two things: the object has too many responsibilities and should be split, or some of the parameters are "optional settings" rather than "required dependencies". Split in the first case; in the second, gather the optional settings into a Config struct or use the functional options pattern. Either way, required dependencies should remain mandatory constructor parameters; don't hide them in options.
Step 5: Connect the three layers, keeping errors intact across them
Putting the previous steps together, here is a complete version you can run directly. So that it compiles as a single file, the three layers temporarily sit in one file, with comments marking which file each belongs to in a real project; in an actual project they are the order.go, service.go, repository.go, handler.go and cmd/order/main.go from the directory in Step 2.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"strconv"
"sync"
"time"
)
// ===== Domain: pure data and errors, depends on nothing =====
type Item struct {
ProductID int64 `json:"product_id"`
Qty int `json:"qty"`
Price int64 `json:"price"` // unit: cents
}
type Order struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Items []Item `json:"items"`
Total int64 `json:"total"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
const (
StatusPending = "pending"
StatusPaid = "paid"
StatusCancelled = "cancelled"
)
var (
ErrNotFound = errors.New("order not found")
ErrInvalid = errors.New("invalid order")
)
// ===== Service: business rules; whatever it needs, it declares as an interface here =====
// OrderRepository is defined by the consumer (the service) and lists only the methods it actually uses.
type OrderRepository interface {
Create(ctx context.Context, o *Order) error
Get(ctx context.Context, id int64) (Order, error)
}
type OrderService struct {
repo OrderRepository
now func() time.Time
}
func NewOrderService(repo OrderRepository, now func() time.Time) *OrderService {
return &OrderService{repo: repo, now: now}
}
func (s *OrderService) Place(ctx context.Context, userID int64, items []Item) (Order, error) {
if userID <= 0 {
return Order{}, fmt.Errorf("%w: user_id is required", ErrInvalid)
}
if len(items) == 0 {
return Order{}, fmt.Errorf("%w: at least one item", ErrInvalid)
}
var total int64
for _, it := range items {
if it.Qty <= 0 || it.Price < 0 {
return Order{}, fmt.Errorf("%w: bad item %d", ErrInvalid, it.ProductID)
}
total += it.Price * int64(it.Qty)
}
o := Order{UserID: userID, Items: items, Total: total, Status: StatusPending, CreatedAt: s.now()}
if err := s.repo.Create(ctx, &o); err != nil {
return Order{}, fmt.Errorf("place order: %w", err)
}
return o, nil
}
func (s *OrderService) Get(ctx context.Context, id int64) (Order, error) {
return s.repo.Get(ctx, id)
}
// ===== Repository: an in-memory implementation for now; the next article switches to a database =====
type MemoryRepo struct {
mu sync.Mutex
nextID int64
data map[int64]Order
}
func NewMemoryRepo() *MemoryRepo { return &MemoryRepo{data: make(map[int64]Order)} }
func (m *MemoryRepo) Create(_ context.Context, o *Order) error {
m.mu.Lock()
defer m.mu.Unlock()
m.nextID++
o.ID = m.nextID
m.data[o.ID] = *o
return nil
}
func (m *MemoryRepo) Get(_ context.Context, id int64) (Order, error) {
m.mu.Lock()
defer m.mu.Unlock()
o, ok := m.data[id]
if !ok {
return Order{}, ErrNotFound
}
return o, nil
}
// ===== Transport (handler): HTTP in and out, status code mapping =====
type orderService interface {
Place(ctx context.Context, userID int64, items []Item) (Order, error)
Get(ctx context.Context, id int64) (Order, error)
}
type OrderHandler struct {
svc orderService
logger *slog.Logger
}
func NewOrderHandler(svc orderService, logger *slog.Logger) *OrderHandler {
return &OrderHandler{svc: svc, logger: logger}
}
func (h *OrderHandler) Register(mux *http.ServeMux) {
mux.HandleFunc("POST /orders", h.create)
mux.HandleFunc("GET /orders/{id}", h.get)
}
func (h *OrderHandler) create(w http.ResponseWriter, r *http.Request) {
var in struct {
UserID int64 `json:"user_id"`
Items []Item `json:"items"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
o, err := h.svc.Place(r.Context(), in.UserID, in.Items)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusCreated, o)
}
func (h *OrderHandler) get(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "id must be a number", http.StatusBadRequest)
return
}
o, err := h.svc.Get(r.Context(), id)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, o)
}
// fail is the only place where domain errors are translated into HTTP status codes.
func (h *OrderHandler) fail(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, ErrInvalid):
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
case errors.Is(err, ErrNotFound):
http.Error(w, "order not found", http.StatusNotFound)
default:
h.logger.ErrorContext(r.Context(), "request failed", slog.Any("err", err))
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// ===== Wiring (composition root): the only place that knows every concrete type =====
func main() {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
repo := NewMemoryRepo()
svc := NewOrderService(repo, time.Now)
h := NewOrderHandler(svc, logger)
mux := http.NewServeMux()
h.Register(mux)
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
logger.Info("listening", slog.String("addr", srv.Addr))
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("server stopped", slog.Any("err", err))
os.Exit(1)
}
}How errors cross layers
The part of this program most worth studying is how errors flow between the three layers. It applies the techniques from “Error Handling in Go: Wrapping, Sentinels and Custom Types” directly:
- Domain errors are defined next to the domain types.
ErrNotFoundandErrInvalidare sentinel errors belonging to the order domain, not to any layer. - The repository translates low-level errors. When the in-memory version cannot find the data it returns
ErrNotFound; when the database version in the next article hitssql.ErrNoRows, it must translate that into the sameErrNotFound. That way the service and handler never need to know thatdatabase/sqlexists. - The service adds context with
%w.fmt.Errorf("%w: user_id is required", ErrInvalid)makes the message more specific while keeping an identity thaterrors.Iscan check. - The handler is the only place that translates errors into HTTP. The
failmethod handles it centrally:ErrInvalidmaps to 422,ErrNotFoundto 404, and any other unexpected error is logged and answered with 500, without sending the internal error message to the client, so implementation details do not leak.
With this arrangement, if the same service later also has to be exposed over gRPC (which “gRPC and Protocol Buffers in Go” does), you only need to write a gRPC transport layer that translates the same domain errors into gRPC status codes; not a single line of the service or repository changes.
The handler depends only on an interface too
The orderService interface in the handler starts with a lowercase letter and is unexported. It belongs to the handler alone and expresses "I need something that can place and look up orders". In production a *OrderService is passed in; in tests you can pass a fake implementation and control exactly which result or error the service returns, to verify that the handler's status code mapping is correct. This is precisely the technique “Testing in Go: Table-Driven Tests, httptest and Integration Tests” demonstrates.
Step 6: Wire everything up in main
Every object receives its dependencies through its constructor, so there has to be one place that actually "builds them and connects them". That place is called the composition root, and in a Go service it is cmd/order/main.go.
Figure: The composition root creates the repository, service and handler in order, then hands them to http.Server; it is the only place that knows every concrete type.
Once split into several packages, the composition root looks like this:
// Snippet: cmd/order/main.go
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"time"
"example.com/shop/internal/order"
"example.com/shop/internal/platform/httpx"
)
func main() {
if err := run(context.Background(), os.Getenv); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// run is the composition root: every concrete type is created and connected here.
func run(ctx context.Context, getenv func(string) string) error {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
repo := order.NewMemoryRepository()
svc := order.NewService(repo, time.Now)
h := order.NewHandler(svc, logger)
mux := http.NewServeMux()
h.Register(mux)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
addr := getenv("ORDER_ADDR")
if addr == "" {
addr = ":8080"
}
srv := &http.Server{
Addr: addr,
Handler: httpx.Chain(mux, httpx.RequestID, httpx.Logging(logger), httpx.Recover(logger)),
ReadHeaderTimeout: 5 * time.Second,
}
logger.InfoContext(ctx, "order service listening", slog.String("addr", addr))
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("serve: %w", err)
}
return nil
}There is a common little trick here: main only calls run and handles the exit code, while the real wiring logic lives in run, which returns an error. The benefit is that run can safely use defer (os.Exit skips every defer), and tests can call run directly with a fake environment-variable lookup function instead of actually changing the process's environment. How configuration is read and how the service exits after receiving a shutdown signal are covered fully in “Configuration and Graceful Shutdown in Go”.
Why not use a DI framework
The Go ecosystem does have dependency injection tools, which fall roughly into two groups: tools that generate the wiring code at compile time (such as Google's Wire), and containers that resolve dependencies automatically with reflection at runtime (such as Uber's fx and dig).
For most Go services, a hand-written composition root is enough, and it has several advantages a framework cannot give you:
- It is readable. A new team member opens
main.go, reads it top to bottom and knows where every object comes from, without learning a framework's rules. - Errors appear at compile time. A missing argument or a type mismatch, and
go buildtells you; wiring errors in a runtime container only show up when the program starts. - No magic. You never get "some constructor was called automatically, but nobody knows what triggered it".
Only when the composition root grows to hundreds of lines and every new dependency means changes in many places is it worth evaluating a compile-time code generator. Even then, what it generates is still ordinary Go code, conceptually identical to a hand-written composition root.
Step 7: The payoff: swappable implementations and unit tests
With all this done, the most direct reward is that you can test the service alone, and the tests are fast and stable. No HTTP server and no database are needed, only a double implementing the Repository interface and a function that returns a fixed time:
// Snippet: internal/order/service_test.go
package order
import (
"context"
"errors"
"testing"
"time"
)
// stubRepo just remembers the order it was given, or returns a preset error.
type stubRepo struct {
saved *Order
err error
}
func (s *stubRepo) Create(_ context.Context, o *Order) error {
if s.err != nil {
return s.err
}
o.ID = 1
s.saved = o
return nil
}
func (s *stubRepo) Get(context.Context, int64) (Order, error) { return Order{}, nil }
func TestPlace(t *testing.T) {
fixed := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
repo := &stubRepo{}
svc := NewService(repo, func() time.Time { return fixed })
o, err := svc.Place(context.Background(), 7, []Item{{ProductID: 1, Qty: 2, Price: 600}})
if err != nil {
t.Fatalf("Place() error = %v", err)
}
if o.Total != 1200 || o.Status != StatusPending || !o.CreatedAt.Equal(fixed) {
t.Errorf("Place() = %+v", o)
}
if repo.saved == nil {
t.Fatal("order was not saved")
}
_, err = svc.Place(context.Background(), 7, nil)
if !errors.Is(err, ErrInvalid) {
t.Errorf("empty items: error = %v, want ErrInvalid", err)
}
}This test verifies three things precisely: whether the total is calculated correctly, whether a new order's status is pending, and whether the creation time comes from the injected clock. It runs in milliseconds and never flakes because of the machine's time zone or when it happens to run.
Swappable implementations pay off beyond tests, too. When the next article moves the data into a database, you only write a new repository type and swap NewMemoryRepository() for the database version in main; the service and handler do not change at all. Later, if you want a cache in front of the read path, you can write a "caching wrapper" that also satisfies the Repository interface and holds the real repository inside. That is the same "wrapping" idea as the middleware in “net/http and Middleware in Go”, just applied to the storage layer.
Tip: Test doubles don't have to be generated with a mock package. A hand-written stub or fake of a few lines is often clearer, and when interfaces are small enough (following the principle in Step 3), hand-written doubles cost very little. If a double is painful to write, the interface is usually too big.
Common pitfalls
- Defining big interfaces on the implementation side. Declaring an
OrderRepositoryinterface with every method in the repository package and having the service reference it is carrying Java habits into Go: the service is forced to depend on methods it never uses, and doubles become hard to write. - Constructors that return interfaces.
func NewService(...) OrderServicehides the concrete type, so consumers cannot reach its other methods, and it makes inlining harder for the compiler; unless you have a clear reason, return the concrete type. - Passing HTTP types into the service. Once
*http.Requestorhttp.ResponseWriterappears in a service method signature, the business rules are tied to the transport layer again. The service accepts only a context and domain types. - Letting
sql.ErrNoRowsleak out of the repository. Once upper layers start checking database errors, switching storage means changes everywhere. - Quietly calling
time.Now()or reading globals. These are hidden dependencies that make tests unpredictable; inject everything that varies through the constructor. - Using context as a container for dependencies. Pulling a database connection or logger out of
ctx.Valuehides the dependencies, and the compiler cannot help you. Context holds only request-scoped data. - Layering for the sake of layering. If every function passes through five or six conversion layers that merely copy data from one struct to another, that is over-engineering. Let real complexity decide the number of layers.
- Packages by technical role. A
controllers/,services/,models/structure invites import cycles and spreads a single feature's changes across several directories.
Key takeaways
- Split into handler, service and repository layers, each changing for only one reason; domain types and domain errors are shared by every layer and depend on none.
- Organise packages by domain (
internal/order/) rather than by technical role, avoiding meaningless package names and import cycles. - Go interfaces are implemented implicitly, so an interface should be defined by the consumer and list only the methods it really needs.
- "Accept interfaces, return structs": parameters take interfaces, constructors return concrete types.
- In Go, dependency injection is just constructor parameters; things that make results unpredictable, such as time, randomness and external clients, should be injected too.
- Errors are translated into domain errors in the repository and into HTTP status codes in the handler, with
%wanderrors.Ispreserving their identity in between. - Wire everything up in
cmd/order/main.go, withmainonly calling arunthat returns an error; for most services a hand-written composition root is enough, no DI framework needed. - With small interfaces and injectable dependencies, unit tests can use hand-written doubles of a few lines and stay fast and stable.
Next
Orders still live only in memory, so they all vanish when the service restarts, and there is no guarantee that "deduct stock" and "create the order" succeed or fail together. “database/sql, Transactions and Connection Pools in Go” writes the database version of the repository and explains how to use transactions and the connection pool correctly.