How Can I Use Regular Expressions to Route URLs in Go?

Barbara Streisand
Release: 2024-11-25 07:14:10
Original
116 people have browsed it

How Can I Use Regular Expressions to Route URLs in Go?

Using Regular Expressions for URL Pattern Matching in Go

Question:

How can I utilize regular expressions to determine the appropriate function for URL processing in a Go program?

Answer:

The provided code demonstrates the use of http.HandleFunc with a fixed path or rooted subtree. To use regular expressions for URL matching, register a handler to a rooted subtree and perform regexp matching within the handler.

Here's an example:

func main() {
    http.HandleFunc("/", route) // Match everything
    http.ListenAndServe(":8080", nil)
}

var rNum = regexp.MustCompile(`\d`)  // Has digit(s)
var rAbc = regexp.MustCompile(`abc`) // Contains "abc"

func route(w http.ResponseWriter, r *http.Request) {
    switch {
    case rNum.MatchString(r.URL.Path):
        digits(w, r)
    case rAbc.MatchString(r.URL.Path):
        abc(w, r)
    default:
        w.Write([]byte("Unknown Pattern"))
    }
}

func digits(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Has digits"))
}

func abc(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Has abc"))
}
Copy after login

Alternatively, consider using an external library such as Gorilla MUX for more flexibility in URL matching.

The above is the detailed content of How Can I Use Regular Expressions to Route URLs in Go?. 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