Skip to content

Instantly share code, notes, and snippets.

@schaternik
Last active May 19, 2025 12:44
Show Gist options
  • Select an option

  • Save schaternik/52d19c60f9f9d91930cb153629c7896f to your computer and use it in GitHub Desktop.

Select an option

Save schaternik/52d19c60f9f9d91930cb153629c7896f to your computer and use it in GitHub Desktop.
Golang HTTP handler
package main
import (
"log"
"net/http"
"time"
)
func timeHandler(w http.ResponseWriter, r *http.Request) {
tm := time.Now().Format(time.RFC1123)
w.Write([]byte("The time is: " + tm))
}
func main() {
mux := http.NewServeMux()
// Convert the timeHandler function to a http.HandlerFunc type.
th := http.HandlerFunc(timeHandler)
// And add it to the ServeMux.
mux.Handle("/time", th)
// or use `HandleFunc` directly
// mux.HandleFunc("/time", timeHandler)
log.Print("Listening...")
http.ListenAndServe(":3000", mux)
}
package main
import (
"log"
"net/http"
"time"
)
func timeHandler(format string) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
tm := time.Now().Format(format)
w.Write([]byte("The time is: " + tm))
}
return http.HandlerFunc(fn)
}
func main() {
mux := http.NewServeMux()
th := timeHandler(time.RFC1123)
mux.Handle("/time", th)
log.Print("Listening...")
http.ListenAndServe(":3000", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment