Home > Article > Backend Development > How to Retrieve Path Parameters in Go Using Only the HTTP Package?
Introduction:
When creating a REST API with Go, retrieving path parameters from incoming HTTP requests is crucial for routing and extracting relevant data. Let's delve into how to achieve this using only the Go's native HTTP package.
Path Parameters with Custom Routing:
If you prefer not to use pre-built routing frameworks, you can define your own path mappings. To do this:
http.HandleFunc("/provisions/:id", Provisions) // Map the "/provisions/:id" path to the Provisions handler
Here, ":id" is a placeholder for the path parameter.
Extracting the Path Parameter:
Within your handler function, you can retrieve the path parameter value using string parsing techniques:
func Provisions(w http.ResponseWriter, r *http.Request) { id := strings.TrimPrefix(r.URL.Path, "/provisions/") // Remove the prefix to extract only the "id" value }
This approach gives you full control over the path parsing, allowing for more complex routing scenarios. However, it requires more manual labor compared to using a dedicated routing library.
The above is the detailed content of How to Retrieve Path Parameters in Go Using Only the HTTP Package?. For more information, please follow other related articles on the PHP Chinese website!