Last active
May 19, 2025 12:44
-
-
Save schaternik/52d19c60f9f9d91930cb153629c7896f to your computer and use it in GitHub Desktop.
Golang HTTP handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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