news.volyx.in

How I write HTTP services in Go after 13 years (grafana.com)

790 points by matryer · 921 days ago · 241 comments on HN

Article summary

The article discusses how the author writes HTTP services in Go after 13 years of experience, outlining best practices for structuring servers and handlers, testing, and dependency management. The author emphasizes the importance of keeping the main function simple and using a separate run function to handle the program's logic. The article also covers topics such as handling common work, optimizing for startup and shutdown, and using dependency injection. The author's approach has evolved over time, and they share their current practices and opinions on how to write effective HTTP services in Go.

Main themes

  • Go programming
  • HTTP services
  • dependency management
  • testing
  • code structure
  • error handling
  • dependency injection
  • functional options pattern

What commenters say

  • Passing dependencies as arguments to handlers is a good practice for testability and clarity.
  • Using a separate run function allows for easier testing and error handling.
  • Dependency injection can help solve the issue of unnecessary shared state, but may add complexity.
  • Some developers prefer to use a struct to hold dependencies, while others prefer separate arguments.
  • Automatic dependency injection can solve the problem of having to pass nil for unused dependencies.
  • The functional options pattern can be useful, but may be too clever and require too much boilerplate.
  • Using a dedicated options struct can help avoid the problem of too many arguments to the constructor.
  • Testing is a crucial aspect of writing effective HTTP services, and the approach outlined in the article can make testing easier.