http.HandleFunc
tells the router to
route requests for the given path to a handler which is
implemented as an anonymous function. An alternative is to
implement the http.Handler
interface.
func main() {
router := http.NewServeMux()
- router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "Hello, World!")
- })
+ router.Handle("/", &greeter{})
err := http.ListenAndServe(":8080", router)
if err != nil {
log.Print(err)
os.Exit(1)
}
}
+
+type greeter struct{}
+
+func (h *greeter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "Hello, World!")
+}