8 Structuring packages and services

 

This chapter covers

  • Effectively organizing and structuring packages to avoid import cycles
  • Simplifying the use of types by making their zero value useful
  • Protecting against unsafe concurrent use of shared state with mutexes
  • Implementing and testing HTTP servers with the http and httptest packages
  • Recording HTTP responses with custom test helpers to streamline testing

Representational State Transfer (REST) is an API design approach that enables programs to communicate, typically over HTTP, using methods like GET and POST. This chapter and the next two chapters explain how to structure maintainable packages and avoid import cycles, showcasing a microservice that serves clients over HTTP with a REST API. Our project will touch on many Go philosophies and patterns for writing maintainable code. Each chapter focuses on a specific set of packages and patterns to explain each in depth:

  • This chapter dives into our service’s core logic and REST API.
  • Chapters 9 explores functional composition patterns.
  • Chapter 10 dives into persistence, integration testing, and interfaces.

Because structuring and organizing multiple packages is a common hurdle for most gophers, we’ll explore how to structure a service after we see an overview of our project. Then we’ll work on the core business logic. After that, we’ll begin implementing the REST API using the standard library’s http package. Finally, we’ll test the API using the httptest package.

8.1 Organizing and structuring packages

8.1.1 Avoiding import cycles

8.1.2 Structuring packages in practice

8.2 Core

8.2.1 Errors

8.2.2 Core

8.2.3 Service

8.2.4 Mutex

8.3 HTTP

8.3.1 Health check

8.3.2 Serving HTTP

8.3.3 HTTP server

8.4 HTTP handlers

8.4.1 Handler closures

8.4.2 Redirecting

8.4.3 HTTP status codes