

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Server
incomplete
2: Content Length
incomplete
3: Response
incomplete
4: Other Common Headers
incomplete
5: Handler
incomplete
6: Code Review
incomplete
7: Refactor
incomplete
This lesson's interactive features are locked, please to keep using them
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:
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.
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:
[]byte to the response body, even in the event of an error.Content-Type to text/html).type Writer structfunc (w *Writer) WriteStatusLine(statusCode StatusCode) errorfunc (w *Writer) WriteHeaders(headers Headers) errorfunc (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.