← blog
#7Coding guidelinesA7

Inside a feature/slice

Start your feature with one file. Add more files only when you actually need them.
Keep it simple and small.

The best way to explain this is from an example, say order processing:

  • order.go first: types, domain rules and validation.
  • service.go next: use cases and interfaces for external dependencies, like storage or payment API. No interface to wrap the service itself. Big no-no!
  • transport/http.go for HTTP related code: encoding, decoding, perhaps some handlers, calling the service. Many times it's for Frontend communication.
  • transport/client.go when another feature needs to call this one: specialized typed client to expose some functionalities of this feature. Mainly for feature-to-feature communication (service-to-service).
  • repository/postgres.go for persistent storage implementation. It implements the interface that service.go declared.
  • cmd/ wires it all together: build the repository, pass it to the service, map the rest. That's the only place they all meet.

File names are only examples, you can name them whatever you want.