Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexedwards/827bae50710c32ab7997 to your computer and use it in GitHub Desktop.
Save alexedwards/827bae50710c32ab7997 to your computer and use it in GitHub Desktop.
Examples of passing information to a handler via closures in Go
package main
import (
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) {
timeHandler(w, r, time.RFC1123)
})
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
func timeHandler(w http.ResponseWriter, r *http.Request, format string) {
tm := time.Now().Format(format)
w.Write([]byte("The time is: " + tm))
}
package main
import (
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/time", timeHandler(time.RFC1123))
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
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)
}
package main
import (
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/time", timeHandler(time.RFC1123))
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
func timeHandler(format string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tm := time.Now().Format(format)
w.Write([]byte("The time is: " + tm))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment