如何在黄HandleFunc中使用函数参数?

如何在黄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:

  1. Save the code in a file named handler.go.
  2. Run the program using the following command:
go run handler.go

Visiting the endpoint:

  1. Open a web browser and navigate to localhost:8080/hello.
  2. You should see the following response:
Hello, world!

Explanation:

  • The handler function is a closure that captures the param variable from the request.
  • The req.URL.Query() method is used to retrieve the value of the param 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 the http.Request object.
  • The ResponseWriter parameter is a pointer to the ResponseWriter object.
相似内容
更多>