This code implements a server that responds to GET requests on the path "/ping" by returning a "pong" message along with the hostname of the server. The server also periodically reads a configuration file that contains a list of host-port combinations and sends GET requests to each of these combinations, logging the response from each server.
The main
function is the entry point of the server application. It does the following:
- Defines the path "/ping" and its corresponding handler function, which returns a "pong" response along with the hostname of the server.
- Starts the server on port 8080 using
http.ListenAndServe
. - Creates a channel
configUpdateCh
to receive configuration update signals. - Starts a goroutine to periodically check for configuration updates by calling the
watchConfigUpdates
function. - Enters an infinite loop where it reads the configuration, sends GET requests based on the current configuration, and waits for a configuration update signal.
The sendPingRequests
function is responsible for sending GET requests to the host-port combinations specified in the configuration. It performs the following steps:
- Splits the host-port configuration into individual lines.
- Iterates over each line, trimming any leading or trailing whitespace.
- If the line is not empty, splits it into host and port components.
- Sends a GET request to the specified host and port by constructing the URL.
- Reads the response body and logs the response along with the hostname of the server that handled the request.
The readConfig
function reads the host-port configuration from the file specified by configFilePath
. It performs the following steps:
- Reads the contents of the configuration file using
ioutil.ReadFile
. - Converts the read data to a string.
- Returns the host-port configuration string.
The watchConfigUpdates
function watches for changes in the configuration file and sends an update signal through the configUpdateCh
channel when a modification is detected. It operates as follows:
- Starts a goroutine to periodically check the last modified time of the configuration file.
- Compares the last modified time with the previously recorded time.
- If the file has been modified, sends an update signal through the
configUpdateCh
channel. - Sleeps for a short interval before checking again.
Make sure to replace configFilePath
with the actual path to your configuration file before running the server.