Where the Real Thinking Happens

Strip away the frameworks, the databases, the JSON, and the deployment pipelines, and every application is really just a pile of decisions. Can this person withdraw this much? Is this coupon still valid? May a trainee edit another trainee's record? That pile of decisions is the reason anyone built the software in the first place.

In a layered Go backend, those decisions live in one place: the service layer. If handlers are waiters and repositories are the pantry, services are the chef: the one who actually knows how to cook. This article is about making that kitchen a pleasant, testable place to work.

What belongs in a service

A service answers the question: "What should happen?"

It takes plain inputs, applies the rules of your business, coordinates the repositories it needs, and returns plain outputs or meaningful errors. Here's a quick sorting guide.

Belongs in a service:

  • Rules and policies ("orders over 5,000 qualify for free delivery")
  • Workflows that combine several steps ("register a user, create their profile, queue a welcome email")
  • Authorization decisions ("only the owner or an admin may delete this")
  • Orchestration across repositories and external clients
  • Deciding when something is an error, and which one

Doesn't belong in a service:

  • HTTP concerns (status codes, headers, gin.Context)
  • SQL or GORM calls
  • JSON field names and response formatting

A trick I like: imagine your app also needed a command-line interface tomorrow. Anything you'd have to rewrite for the CLI is in the wrong layer. Anything that would work unchanged belongs in the service.

A service worth reading

Let's build an OrderService. First, the dependencies it needs, expressed as small interfaces:

package service type OrderStore interface { Create(ctx context.Context, o *domain.Order) error FindByID(ctx context.Context, id uint) (*domain.Order, error) } type ProductStore interface { FindByIDs(ctx context.Context, ids []uint) ([]domain.Product, error) } type Mailer interface { SendOrderConfirmation(ctx context.Context, email string, orderID uint) error } 

Then the service itself:

type OrderService struct { orders OrderStore products ProductStore mailer Mailer clock func() time.Time } func NewOrderService(o OrderStore, p ProductStore, m Mailer) *OrderService { return &OrderService{ orders: o, products: p, mailer: m, clock: time.Now, } } 

Two small things to appreciate. Everything arrives through the constructor, so the service has no secret dependencies. And clock is a function, not a direct call to time.Now(). This looks fussy, but it means tests can freeze time, which is useful when your rules say things like "orders placed after 6 p.m. ship tomorrow." Code that depends on the real clock is a time traveler's nightmare to test.

The use-case method

Each public method on a service should map to one thing a user of your system can accomplish. We call these use cases: PlaceOrder, CancelOrder, ApplyCoupon. Here's PlaceOrder:

type PlaceOrderInput struct { UserID uint UserEmail string Items []OrderItemInput } type OrderItemInput struct { ProductID uint Quantity int } func (s *OrderService) PlaceOrder(ctx context.Context, in PlaceOrderInput) (*domain.Order, error) { if len(in.Items) == 0 { return nil, domain.ErrEmptyOrder } ids := make([]uint, len(in.Items)) for i, it := range in.Items { if it.Quantity <= 0 { return nil, domain.ErrInvalidQuantity } ids[i] = it.ProductID } products, err := s.products.FindByIDs(ctx, ids) if err != nil { return nil, fmt.Errorf("loading products: %w", err) } if len(products) != len(uniqueIDs(ids)) { return nil, domain.ErrProductNotFound } order := &domain.Order{ UserID: in.UserID, Status: domain.OrderPending, CreatedAt: s.clock(), } order.Items, order.Total = buildLines(products, in.Items) if order.Total >= freeDeliveryThreshold { order.DeliveryFee = 0 } else { order.DeliveryFee = standardDeliveryFee order.Total += standardDeliveryFee } if err := s.orders.Create(ctx, order); err != nil { return nil, fmt.Errorf("saving order: %w", err) } // Best effort: a failed email shouldn't undo a successful order. if err := s.mailer.SendOrderConfirmation(ctx, in.UserEmail, order.ID); err != nil { log.Printf("order %d: confirmation email failed: %v", order.ID, err) } return order, nil } 

Read it slowly. It's a story: validate the request, load what we need, build the order, apply the delivery rule, save it, notify the customer. Every step is a business decision or a call to a collaborator, and there isn't a single mention of HTTP or SQL.

Notice the input struct

PlaceOrderInput is a plain struct that belongs to the service. We don't pass the HTTP request struct down from the handler. Why? Because the request struct is shaped by JSON and the web, while the input struct is shaped by the use case. Two different audiences, two different shapes. The handler's job is to translate one into the other, which keeps the service callable from anywhere: a handler, a scheduled job, a test, or a CLI.

Notice the quiet judgment call at the end

The email failure is logged but not returned. That's a business decision, and it's exactly the kind of thing that belongs here. Should a failed confirmation email cancel the order? Most shops would say no: the customer paid, the order exists, retry the email later. Someone has to make that call, and the service is the right someone. Writing it down in a comment saves the next developer from "fixing" it into a bug.

Errors: the service speaks in meaning

A service shouldn't return raw database errors or HTTP codes. It should return errors that describe what went wrong in business terms:

var ( ErrEmptyOrder = errors.New("order has no items") ErrInvalidQuantity = errors.New("quantity must be positive") ErrProductNotFound = errors.New("product not found") ErrForbidden = errors.New("not allowed") ) 

The handler's job is then to translate meaning into status codes:

switch { case errors.Is(err, domain.ErrEmptyOrder), errors.Is(err, domain.ErrInvalidQuantity): c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) case errors.Is(err, domain.ErrProductNotFound): c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) case errors.Is(err, domain.ErrForbidden): c.JSON(http.StatusForbidden, gin.H{"error": "not allowed"}) default: c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"}) } 

This division of labor is a gift. The service doesn't care whether it's called from a REST API or a gRPC server or a tired intern at a terminal. Meanwhile the handler is free to decide that "forbidden" is a 403 on the web and some other code elsewhere.

Wrap errors with %w as you go (fmt.Errorf("saving order: %w", err)) so the original cause survives and logs tell a story: saving order: creating order: connection refused. That reads like a breadcrumb trail, and when production is on fire, breadcrumbs are precious.

Authorization lives here, too

"Can this user do this?" is a business rule, not a web rule. Don't leave it only in middleware.

Middleware can answer coarse questions: "Is this person logged in? Do they have the admin role?" But the fine-grained ones depend on data: "Is this their order?" For that you need the order, which means you need the service.

func (s *OrderService) CancelOrder(ctx context.Context, actor domain.Actor, orderID uint) error { order, err := s.orders.FindByID(ctx, orderID) if err != nil { return err } if order.UserID != actor.ID && !actor.IsAdmin { return domain.ErrForbidden } if order.Status != domain.OrderPending { return domain.ErrCannotCancel } order.Status = domain.OrderCancelled return s.orders.Update(ctx, order) } 

The handler pulls the actor out of the Gin context (set earlier by auth middleware) and passes it in as a plain struct. The service enforces the rule. If you only check ownership in the handler, the day someone adds a second entry point, such as an admin tool or a background job, the check is gone, and so is your safety. Put the rule where the data and the decision meet.

Keep services focused

A common failure mode is the god service: UserService with 45 methods covering registration, login, profile photos, password resets, newsletter subscriptions, and, for reasons lost to history, tax calculation. Every change touches it, every test needs a dozen fakes, and nobody wants to open the file.

Split by what changes together. AuthService handles credentials and tokens. ProfileService handles profile data. NotificationService handles messaging. If a service's constructor takes seven dependencies, that's your smoke alarm.

At the same time, don't swing too far and create a service for every single method. The goal is cohesion, things that change for the same reasons living together, not an army of one-function structs.

Testing services: where it gets fun

Because services depend on interfaces, testing them is a pleasure. No server, no database, no Docker. Just fakes and assertions.

type fakeMailer struct { sent []uint err error } func (f *fakeMailer) SendOrderConfirmation(_ context.Context, _ string, id uint) error { if f.err != nil { return f.err } f.sent = append(f.sent, id) return nil } func TestPlaceOrder_EmailFailureDoesNotFailOrder(t *testing.T) { orders := newFakeOrderStore() products := newFakeProductStore(domain.Product{ID: 1, Price: 1500}) mailer := &fakeMailer{err: errors.New("smtp down")} svc := NewOrderService(orders, products, mailer) order, err := svc.PlaceOrder(context.Background(), PlaceOrderInput{ UserID: 7, UserEmail: "a@b.com", Items: []OrderItemInput{{ProductID: 1, Quantity: 2}}, }) if err != nil { t.Fatalf("expected success, got %v", err) } if order.Total == 0 { t.Fatal("expected a non-zero total") } } 

That test captures a business rule in executable form: a broken mail server must not break an order. Months later, when someone refactors and accidentally returns the mail error, the test fails and protects the rule. Good service tests are living documentation of your policies.

A few testing tips:

  • Use table-driven tests for rules with many cases (discount thresholds, status transitions).
  • Test the sad paths as hard as the happy ones. Empty input, missing records, forbidden actors.
  • Freeze the clock by setting svc.clock in tests that depend on time.
  • Prefer hand-written fakes for small interfaces. A fake with a map and three methods is clearer than a mocking framework's configuration language.

Common mistakes

Anemic services. Every method just forwards to the repository. If your service is a pass-through, the real logic is probably hiding in handlers. Pull it down.

Importing Gin or GORM. The moment a service file mentions gin.Context or gorm.DB, a boundary is cracked.

Hidden globals. Reading config from environment variables inside a method, grabbing a global database handle, calling time.Now() directly in rule-heavy code. Inject these instead.

Returning HTTP-flavored errors. errors.New("404") is a handler's problem pretending to be a service's.

Doing everything inside one transaction by default. Wrap only what truly needs to be atomic. Long transactions hold locks and slow everyone down.

Skipping input validation because "the handler already checked." The handler checks the shape (is this valid JSON, is the email formatted correctly). The service checks the meaning (is the quantity sensible, does this product exist). Different checks, both necessary.

Quick recap

  • Services hold the rules and workflows that make your app your app.
  • Each public method is a use case with its own plain input and output types.
  • Dependencies arrive through the constructor as small interfaces, including things like the clock.
  • Return domain errors that describe meaning, and let handlers translate them to HTTP.
  • Enforce fine-grained authorization in the service, where the data lives.
  • Keep services cohesive, test them with hand-written fakes, and test the sad paths.