Building a Simple HTTP Handler in Go
This challenge focuses on implementing the http.Handler interface in Go. Understanding and implementing handlers is fundamental to building web applications and APIs with Go's standard library. You'll create a handler that responds to requests with a specific status code and body based on the request path.
Problem Description
You are tasked with creating a custom http.Handler that responds to HTTP requests. The handler should behave as follows:
/path: Respond with a status code of 200 OK and the body "Hello, World!"./hellopath: Respond with a status code of 200 OK and the body "Hello, Go!".- Any other path: Respond with a status code of 404 Not Found and the body "Not Found".
Your handler must implement the http.Handler interface, which requires a single method: ServeHTTP(w http.ResponseWriter, r *http.Request). This method receives an http.ResponseWriter to write the response and an *http.Request containing the request details.
Key Requirements:
- Implement the
http.Handlerinterface correctly. - Handle the specified paths and return the correct status codes and bodies.
- Handle all other paths gracefully with a 404 Not Found response.
- Use the
http.ResponseWriterto set the status code and write the response body.
Examples
Example 1:
Input: Request to "/"
Output: Status Code: 200 OK, Body: "Hello, World!"
Explanation: The handler recognizes the "/" path and returns the default greeting.
Example 2:
Input: Request to "/hello"
Output: Status Code: 200 OK, Body: "Hello, Go!"
Explanation: The handler recognizes the "/hello" path and returns the Go-specific greeting.
Example 3:
Input: Request to "/unknown"
Output: Status Code: 404 Not Found, Body: "Not Found"
Explanation: The handler does not recognize the "/unknown" path and returns a 404 error.
Constraints
- The handler must be implemented in Go.
- The response body should be a string.
- The handler should be efficient enough to handle a reasonable number of concurrent requests (no specific performance metrics are required for this challenge, but avoid unnecessary allocations).
- The code should be well-structured and readable.
Notes
- You can use
http.ResponseWriter.WriteHeader(statusCode)to set the HTTP status code. - You can use
http.ResponseWriter.Write([]byte(body))to write the response body. Remember to convert the string to a byte slice. - Consider using
http.Request.URL.Pathto extract the request path. - This challenge focuses on the core logic of the handler. You don't need to create a full-fledged HTTP server. The goal is to implement the
http.Handlerinterface itself. - Think about how you'll structure your code to handle the different paths efficiently. A simple
if/elseorswitchstatement is perfectly acceptable.