We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Refactor

I'm not very happy with our current implementation. It constrains the user of our library (our main package for now, but hey, TheStartup™ is gonna monetize it eventually) in a few ways:

  • Errors are always handled as plain text responses
  • Headers are always the same

Let's fix that! We're going to need a more flexible function signature for custom handlers. Instead of this:

type Handler func(w io.Writer, req *request.Request) *HandlerError

I'm thinking something more like this:

type Handler func(w *response.Writer, req *request.Request)

We'll create a new response.Writer struct that will allow the user to modify the headers, status code, and body of the response as they see fit. This will give them control to respond to HTTP requests in any way they want, while still encapsulating some of the boilerplate logic.

Assignment

The goal here is to change our handler in the httpserver's main package to respond with HTML instead of plain text. To do this, we'll need to:

  • Ensure that the handler function can write a raw []byte to the response body, even in the event of an error.
  • Give the handler function control over response headers (to set Content-Type to text/html).
    • type Writer struct
    • func (w *Writer) WriteStatusLine(statusCode StatusCode) error
    • func (w *Writer) WriteHeaders(headers Headers) error
    • func (w *Writer) WriteBody(p []byte) (int, error)
<html>
  <head>
    <title>400 Bad Request</title>
  </head>
  <body>
    <h1>Bad Request</h1>
    <p>Your request honestly kinda sucked.</p>
  </body>
</html>
<html>
  <head>
    <title>500 Internal Server Error</title>
  </head>
  <body>
    <h1>Internal Server Error</h1>
    <p>Okay, you know what? This one is on me.</p>
  </body>
</html>
<html>
  <head>
    <title>200 OK</title>
  </head>
  <body>
    <h1>Success!</h1>
    <p>Your request was an absolute banger.</p>
  </body>
</html>

You might need to expose a new method from your headers package so that you can override the default headers for a key instead of adding to them.

Run and submit the CLI tests.