Accessing Path Parameters in Go's HTTP Request Handler
When developing a REST API in Go without using web frameworks, retrieving path parameters from HTTP requests requires manual parsing. Let's delve into the implementation:
Mapping Path Variables
The first step is to map the desired path variable, in this case "id," to the corresponding handler. This is done using http.HandleFunc:
http.HandleFunc("/provisions/:id", Provisions)
The :id portion in the path indicates that it's a placeholder for a dynamic parameter.
Retrieving Path Parameters from Request
Within the Provisions handler function, we can extract the "id" parameter from the request object r:
func Provisions(w http.ResponseWriter, r *http.Request) { id := strings.TrimPrefix(r.URL.Path, "/provisions/") // Process the id parameter as needed }
The strings.TrimPrefix method removes the "/provisions/" prefix from the path, leaving only the "id" parameter value. This approach provides a simple and versatile way to handle path parameters without the overhead of web frameworks.
The above is the detailed content of How to Access Path Parameters in Go's HTTP Request Handler?. For more information, please follow other related articles on the PHP Chinese website!