在golang中,使用net / http时如何调用带有或不带有后括号的函数
In the main function, I have a gorilla mux router, and a function to handle the route.
var router = mux.NewRouter()
func main() {
router.HandleFunc("/", ParseSlash)
http.Handle("/", router)
http.ListenAndServe(":8000", nil)
}
and ParseSlash looks like
const slash = `<h1>Login</h1>
<form method="post" action="/login">
<label for="name">User name</label>
<input type="text" id="name" name="name">
<label for="password">Password</label>
<input type="password" id="password" name="password">
<button type="submit">Login</button>
</form>`
func ParseSlash(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, slash)
}
However, in main, we are not calling the function as ParseSlash()
, but ParseSlash
inside router.HandleFunc()
. Where do the function get the parameters from, if we are not providing explicitely? What is this way of calling a function termed as?
Thank you.
You are not "calling" the function from main, you are providing it as a argument to HandleFunc
, registering it to be called for the path "/" in the mux.Router
. This pattern of providing a function to be called later is typically known as a "callback".
Your ParseSlash
function is of the type http.HandlerFunc
type HandlerFunc func(ResponseWriter, *Request)
Your function is eventually called by the http.Server
via its ServeHTTP
method (here, via the mux.Router
), passing the arguments shown. When the function is called, the http.ResponseWriter
and *http.Request
arguments are for the individual http request being handled.
It is a simple callback. You need that, when you want to call some function in the future, but now you don't have enough information to do it. Look - http.ListenAndServe create a server and waits for client.
You cannot call function ParseSlash, because it make sense after client will connect and will send address "/". When it happened router would have enough information to call your code back with arguments http.ResponseWriter and *http.Request.
Now you should learn how closures works - https://tour.golang.org/moretypes/25 . And you will done let's return back to http server https://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/ .