function with thread web server to print the date in go

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.go
package main

import (
    "fmt"
    "net/http"
    "time"
)

func formatTime(now time.Time) string {
    return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
}

func dateHandler(w http.ResponseWriter, r *http.Request) {
    go func() {
        now := time.Now()
        dateStr := formatTime(now)
        fmt.Fprintf(w, "Current date: %s", dateStr)
    }()
}

func main() {
    http.HandleFunc("/date", dateHandler)
    http.ListenAndServe(":8080", nil)
}
530 chars
25 lines

In this code:

  • The formatTime function takes a time.Time object and returns a string formatted as YYYY-MM-DD HH:MM:SS.
  • The 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.
  • In the 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