To create a web server that prints the current date using a separate thread in Go, you can define a function that formats the date, create a handler function that calls this function in a separate thread, and register the handler with the server.
The following code demonstrates this approach:
main.go530 chars25 lines
In this code:
formatTime
function takes a time.Time
object and returns a string formatted as YYYY-MM-DD HH:MM:SS
.dateHandler
function is the HTTP handler that will be called when a request is made to the "/date" URL. This function starts a new Goroutine that calls formatTime
, passing the current date and time, and then writes the date string to the HTTP response.main
function, http.HandleFunc
is used to register the dateHandler
function with the server, and http.ListenAndServe
starts the server listening on port 8080.With this code, if you start the server and make a request to "http://localhost:8080/date", you will see the current date and time printed in your browser.
gistlibby LogSnag