How Can I Match Wildcards in URL Patterns for HTTP Handlers?

Barbara Streisand
Release: 2024-11-12 19:38:02
Original
318 people have browsed it

How Can I Match Wildcards in URL Patterns for HTTP Handlers?

Specifying Wildcards in Patterns for HTTP Handlers

When creating handlers using http.Handler or http.HandleFunc, you may want to specify wildcards in the pattern to match a range of URLs. Unfortunately, the patterns for these functions are not regular expressions and do not support wildcards by default.

Instead, you can create your own custom handler that supports pattern matching using regular expressions or any other desired pattern. Here's an example using regular expressions:

import (
    "net/http"
    "regexp"
)

type route struct {
    pattern *regexp.Regexp
    handler http.Handler
}

type RegexpHandler struct {
    routes []*route
}

func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
    h.routes = append(h.routes, &route{pattern, handler})
}

func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
    h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}

func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    for _, route := range h.routes {
        if route.pattern.MatchString(r.URL.Path) {
            route.handler.ServeHTTP(w, r)
            return
        }
    }
    // No pattern matched; send 404 response
    http.NotFound(w, r)
}
Copy after login

By implementing your own custom handler, you gain the flexibility to define your own pattern matching logic and handle different types of URLs as needed.

The above is the detailed content of How Can I Match Wildcards in URL Patterns for HTTP Handlers?. 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