Home  >  Article  >  Backend Development  >  How to Extract Path Parameters from HTTP Requests in Go Without Frameworks?

How to Extract Path Parameters from HTTP Requests in Go Without Frameworks?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 17:41:03988browse

How to Extract Path Parameters from HTTP Requests in Go Without Frameworks?

Retrieving Path Parameters from HTTP Requests in Go

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.

Path Mapping and Parameter Retrieval

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.

Example Code

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!

Statement:
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