Home > Article > Backend Development > How to Extract Path Parameters from HTTP Requests in Go Without Frameworks?
In Go, developing REST APIs without utilizing web frameworks involves manually handling path mappings and extracting path parameters from incoming HTTP requests. This article provides a solution using only the standard http package.
To map a path to a handler and retrieve the corresponding path parameter, perform the following steps:
1. Route the Path:
Use the http.HandleFunc function to associate a specified path with a handler function. For example, to map the /provisions/:id path, use:
http.HandleFunc("/provisions/", Provisions)
2. Extract the Parameter:
Within the handler function, split the request URL's path to extract the path parameter. For instance, to retrieve the id parameter in the /provisions/:id path:
id := strings.TrimPrefix(req.URL.Path, "/provisions/")
You can also utilize strings.Split or regular expressions for more complex path structures.
The provided code snippet illustrates how to implement these steps:
func main() { http.HandleFunc("/provisions/", Provisions) http.ListenAndServe(":8080", nil) } func Provisions(w http.ResponseWriter, r *http.Request) { // Retrieve "id" parameter id := strings.TrimPrefix(req.URL.Path, "/provisions/") // Handle the request using the extracted path parameter }
Utilizing this approach enables full control over path mapping and parameter retrieval without introducing external dependencies.
The above is the detailed content of How to Extract Path Parameters from HTTP Requests in Go Without Frameworks?. For more information, please follow other related articles on the PHP Chinese website!