Implementing a Custom HTTP Handler in Go
This challenge will test your understanding of Go's net/http package by requiring you to implement a custom http.Handler interface. This is a fundamental concept for building web services and APIs in Go, allowing you to define how your application responds to incoming HTTP requests.
Problem Description
Your task is to create a Go program that defines and registers a custom HTTP handler. This handler should be capable of responding to requests with a specific message and status code. You'll need to understand how to define a type that satisfies the http.Handler interface and how to integrate it with Go's built-in HTTP server.
Key Requirements:
- Define a Go struct that implements the
http.Handlerinterface. - The
ServeHTTPmethod of your handler should:- Write a custom message to the response body.
- Set a specific HTTP status code.
- Register an instance of your custom handler to a particular URL path.
- Start an HTTP server that listens on a specified port.
Expected Behavior:
When a client makes an HTTP GET request to the registered URL path on your running server, the server should respond with the defined custom message and the specified status code.
Edge Cases to Consider:
- What happens if the server fails to start?
- How would you handle requests to other, unregistered paths? (For this challenge, a default response is acceptable).
Examples
Example 1:
Input:
- Handler message: "Hello, Custom Handler!"
- Status code: http.StatusOK (200)
- Server port: ":8080"
- URL path to register handler: "/greet"
Output (from client perspective when making a GET request to http://localhost:8080/greet):
HTTP Status: 200 OK
Response Body: "Hello, Custom Handler!"
Example 2:
Input:
- Handler message: "Internal Server Error Occurred"
- Status code: http.StatusInternalServerError (500)
- Server port: ":9000"
- URL path to register handler: "/error"
Output (from client perspective when making a GET request to http://localhost:9000/error):
HTTP Status: 500 Internal Server Error
Response Body: "Internal Server Error Occurred"
Constraints
- Your solution must use Go's standard
net/httppackage. - The server should listen on a port between 8000 and 9999 (inclusive).
- The custom message can be any string.
- The status code must be a valid
http.StatusCode(e.g.,http.StatusOK,http.StatusNotFound,http.StatusInternalServerError). - The solution should be a single, runnable Go program.
Notes
- Recall that the
http.Handlerinterface has a single method:ServeHTTP(http.ResponseWriter, *http.Request). - You'll need to use
http.HandleFuncorhttp.Handleto register your custom handler. - Use
http.ListenAndServeto start the HTTP server. - Consider how to handle potential errors during server startup.
- For paths that are not explicitly handled by your custom handler, the default
net/httpbehavior will apply (often a 404 Not Found). This is acceptable for this challenge.