"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement Wildcard Support in Go HTTP Routing Beyond `http.HandleFunc`?

How to Implement Wildcard Support in Go HTTP Routing Beyond `http.HandleFunc`?

Published on 2024-12-22
Browse:639

How to Implement Wildcard Support in Go HTTP Routing Beyond `http.HandleFunc`?

Advanced Handler Pattern Matching with Wildcards using Custom Handlers

When using http.HandleFunc for defining routing patterns in Go, the built-in mechanisms don't offer wildcard support. This can be a limiting factor for capturing dynamic URL components.

Custom Handler with Regular Expression Pattern Matching

To overcome this limitation, it's feasible to create a custom handler that supports flexible pattern matching using regular expressions. Here's an example:

import (
    "net/http"
    "regexp"
)

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

type RegexpHandler struct {
    routes []*route
}

// Handler adds a route to the custom handler.
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
    h.routes = append(h.routes, &route{pattern, handler})
}

// HandleFunc adds a function-based route to the custom handler.
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
    h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}

// ServeHTTP iterates through registered routes and checks if any pattern matches the request. If a match is found, the corresponding handler is invoked.
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, return a 404 response.
    http.NotFound(w, r)
}

Usage:

Example usage of the custom handler to handle URLs with wildcard patterns:

import (
    "log"
    "net/http"
)

func main() {
    rh := &RegexpHandler{}

    // Define a regular expression for capturing any valid URL string.
    pattern := regexp.MustCompile(`/groups/.*/people`)
    rh.HandleFunc(pattern, peopleInGroupHandler)

    // Start the web server and use the custom handler.
    log.Fatal(http.ListenAndServe(":8080", rh))
}

This approach allows you to build flexible routing patterns beyond the limitations of http.HandleFunc while maintaining control over path matching logic within the custom handler.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3