Last active
August 29, 2015 14:04
-
-
Save alexedwards/827bae50710c32ab7997 to your computer and use it in GitHub Desktop.
Examples of passing information to a handler via closures in Go
This file contains 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 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)) | |
} |
This file contains 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 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) | |
} |
This file contains 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 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