How to Extract Path Parameters in Go's HTTP Request Handling?

Linda Hamilton
Release: 2024-11-13 11:59:02
Original
689 people have browsed it

How to Extract Path Parameters in Go's HTTP Request Handling?

Path Parameter Extraction in Go's HTTP Request Handling

In Go, when developing REST APIs using the native http package instead of frameworks, retrieving path parameters requires manual parsing and mapping.

Path Mapping

To associate a path with a specific request handler, use http.HandleFunc():

http.HandleFunc("/provisions/:id", Provisions)
Copy after login

Here, the :id syntax denotes a variable part in the path that can be retrieved.

Path Parameter Retrieval

Within the handler function, you can extract the parameter using string manipulation. Consider the following example:

func Provisions(w http.ResponseWriter, r *http.Request) {
    // Use string.TrimPrefix to remove the fixed part of the path, leaving only the ID.
    id := strings.TrimPrefix(r.URL.Path, "/provisions/")
    // You can now use the 'id' variable for further processing.
}
Copy after login

This approach enables you to extract path parameters without the need for third-party routing packages. However, it may require more manual labor and error handling compared to using a framework that provides built-in parameter mapping capabilities.

The above is the detailed content of How to Extract Path Parameters in Go's HTTP Request Handling?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template