Home  >  Article  >  Backend Development  >  How to Extract URL Path Parameters Using Gorilla/Mux in Go?

How to Extract URL Path Parameters Using Gorilla/Mux in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 08:52:30909browse

How to Extract URL Path Parameters Using Gorilla/Mux in Go?

Reading URL Path Parameters in Go

You are developing a web application in Go that requires handling specific URL paths. In particular, you want to read and display a portion of a URL path in the format example.com/person/(any_name), where (any_name) represents a variable parameter.

To accomplish this, the gorilla/mux package is highly recommended for route handling.

Using gorilla/mux

The gorilla/mux package is a powerful router for Go. It provides a straightforward way to define and manage routes, including the ability to capture parameters from URLs.

Here's how you can use gorilla/mux to read and print the (any_name) parameter:

<code class="go">package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func PersonHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    name := vars["name"]
    fmt.Fprintf(w, "Hello, %s!", name)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/person/{name}", PersonHandler).Methods(http.MethodGet)

    if err := http.ListenAndServe(":8080", r); err != nil {
        log.Fatal(err)
    }
}</code>

In this script, we:

  1. Import the necessary packages, including gorilla/mux.
  2. Define a handler function, PersonHandler, which will handle requests to the /person/{name} path.
  3. Use gorilla/mux's Vars function to extract the {name} parameter from the request.
  4. Write the captured parameter value (the person's name) to the response writer.
  5. Register the route with the router, specifying the HTTP method is GET.
  6. Start a web server on port 8080 and listen for incoming requests.

When a request is made to example.com/person/John, the PersonHandler function will be invoked with the parameter name set to John. The function will then print "Hello, John!" to the response.

The above is the detailed content of How to Extract URL Path Parameters Using Gorilla/Mux in Go?. 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