"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 'http.HandleFunc' 이외의 Go HTTP 라우팅에서 와일드카드 지원을 구현하는 방법은 무엇입니까?

'http.HandleFunc' 이외의 Go HTTP 라우팅에서 와일드카드 지원을 구현하는 방법은 무엇입니까?

2024년 12월 22일에 게시됨
검색:442

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

사용자 정의 핸들러를 사용하여 와일드카드를 사용한 고급 핸들러 패턴 일치

Go에서 라우팅 패턴을 정의하기 위해 http.HandleFunc를 사용할 때 내장된 메커니즘은 와일드카드 지원을 제공하지 마세요. 이는 동적 URL 구성 요소를 캡처하는 데 제한 요소가 될 수 있습니다.

정규 표현식 패턴 일치를 사용하는 사용자 정의 핸들러

이 제한을 극복하려면 다음을 수행하는 사용자 정의 핸들러를 생성하는 것이 가능합니다. 정규식을 사용하여 유연한 패턴 일치를 지원합니다. 예는 다음과 같습니다.

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)
}

사용법:

와일드카드 패턴으로 URL을 처리하기 위한 사용자 정의 처리기 사용 예:

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))
}

이 접근 방식을 사용하면 http.HandleFunc의 제한을 넘어서는 유연한 라우팅 패턴을 구축하는 동시에 사용자 정의 핸들러 내에서 경로 일치 논리에 대한 제어를 유지할 수 있습니다.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3