7 Designing an HTTP Server

 

This chapter covers

  • Structuring, writing, running, and testing an idiomatic HTTP server.
  • Using middleware and handler chaining patterns to minimize repetitive code and add extra functionality to HTTP handlers without changing their code.
  • Receiving and responding with the JSON format.

Imagine you're about to embark on an exciting journey at Bite, a start-up with ambitions to transform the world of link management. Your first project at Bite is a URL shortener HTTP server that shortens long URLs based on a user-specified short key. When a user requests the shortened URL, the server redirects the user to the long URL. For example, users might use the short key "go" to go to "https://go.dev".

This chapter explores how to write an idiomatic, maintainable, and testable JSON API from scratch using the Go Standard Library. And it guides you through in building the URL shortener JSON API using Go's net/http package, following your introduction to handlers, requests, and responses in the last chapter.

Note

You can find the source code for this chapter at https://github.com/inancgumus/effective-go/tree/main/ch07.

Getting a preview

7.1 Writing an HTTP server

 

7.1.1 Learning about the core concepts

 
 

7.1.2 Running the server

 
 
 

7.1.3 Hardening the server

 
 

7.1.4 Serving with multiple handlers

 
 
 
 

7.1.5 Wrap up

 
 

7.2 Implementing the service

 
 
 
 

7.2.1 Defining the business rules

 
 

7.2.2 Making handlers smarter

 
 
 
 

7.2.3 Wrap up

 
 

7.3 Encoding and Decoding JSON

 
 
 

7.4 Middleware: Functional Composition

 
 

7.4.1 Implementing the logging middleware

 
 

7.4.2 Handler chaining pattern

 
 

7.4.3 Leaky internal errors

 

7.4.4 Replying with JSON

 
 

7.4.5 Wrap up

 
 
 
 

7.5 Testing

 
 

7.6 Exercises

 
 

7.7 Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest