An example from the Go documentation for net/http.
Here's a simple web server handling the path /hello:
package main
import (
"io"
"net/http"
"log"
)
// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", HelloServer)
log.Fatal(http.ListenAndServe(":12345", nil))
}
Do you notice that the function HelloServer is defined only to be passed to the call to http.HandleFunc on the first line of main? Using an anonymous function this could instead be written:
package main
import (
"io"
"net/http"
"log"
)
func main() {
http.HandleFunc("/hello", func (w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
})
log.Fatal(http.ListenAndServe(":12345", nil))
}
When a function only needs to be used at one place, it might be a good idea to use an anonymous function, especially when its body is small.
I'm new to the go language and functional programming.-- Go is not a functional language.