How to Access Path Parameters in Go's HTTP Request Handler?

DDD
Release: 2024-11-11 21:50:03
Original
559 people have browsed it

How to Access Path Parameters in Go's HTTP Request Handler?

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)
Copy after login

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
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template