HTTP handlers with closures

Closures are also commonly used as middleware in Go HTTP calls. You can wrap normal HTTP function calls around a closure in order to add additional information to your calls when you need to and reuse middleware for different functions.

In our example, we'll set up an HTTP server with four separate routes:

  • /: This serves the following:
    • An HTTP response with an HTTP 418 status code (derived from the newStatusCode middleware).
    • A Foo:Bar header (derived from the addHeader middleware).
    • A Hello PerfGo! response (derived from the writeResponse middleware).
  • /onlyHeader: Serves an HTTP response with only the Foo:Bar header added.
  • /onlyStatus: Serves an HTTP response with only the status code changed.
  • /admin: Checks ...

Get Hands-On High Performance with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.