如何在黄HandleFunc中使用函数参数?
import (
"fmt"
"net/http"
)
func main() {
// Create a handler function.
handler := func(ResponseWriter, req *http.Request) {
// Get the function parameter.
param := req.URL.Query("param")
// Write a response.
ResponseWriter.Write([]byte("Hello, world!"))
}
// Handle HTTP GET requests.
http.HandleFunc("/hello", handler)
// Start the HTTP server.
fmt.Println("Server listening on port 8080...")
http.ListenAndServe(":8080", nil)
}
Running the program:
- Save the code in a file named
handler.go
. - Run the program using the following command:
go run handler.go
Visiting the endpoint:
- Open a web browser and navigate to
localhost:8080/hello
. - You should see the following response:
Hello, world!
Explanation:
- The
handler
function is a closure that captures theparam
variable from the request. - The
req.URL.Query()
method is used to retrieve the value of theparam
query parameter. - The
ResponseWriter.Write()
method is used to send a response back to the client. - The
http.HandleFunc()
function is used to register the handler function for HTTP GET requests to the endpoint/hello
. - The
http.ListenAndServe()
function starts an HTTP server on port 8080 and listens for requests on the specified path.
Note:
- The
param
query parameter value can be obtained from the request URL or from the request body. - The
req.URL.Query()
method is case-sensitive. - The
req
parameter is a pointer to thehttp.Request
object. - The
ResponseWriter
parameter is a pointer to theResponseWriter
object.