使用 httputil.ReverseProxy 时 mux.Vars 为空

我正在尝试同时使用 gorilla mux 和 httputil.ReverseProxy,但是在尝试获取 mux.Vars 时它是空的。根据https://golang.org/src/net/http/httputil/reverseproxy.go?s=2744:2819#L93似乎 http.Request 指针是原始请求的浅表副本,它应该仍然有效.


有任何想法吗?


https://play.golang.org/p/JpjNvEMIFB


package main


import (

    "github.com/gorilla/mux"

    "log"

    "net/http"

    "net/http/httputil"

    "net/url"

)


type route struct {

    match string

    base  string

}


var routes = []route{

    // proxy http://localhost:3000/api/foo/bar => https://api.bar.com/5/foo/bar

    route{match: "/api/{path}", base: "https://api.bar.com/5"},

    route{match: "/sales/{path}", base: "https://sales.bar.com/3"},

}


func NewProxy(r *route) http.Handler {

    director := func(req *http.Request) {

        out, _ := url.Parse(r.base)


        req.URL.Scheme = out.Scheme

        req.URL.Host = out.Host

        req.URL.Path = out.Path + "/" + mux.Vars(req)["path"] // mux Vars are empty here

    }

    return &httputil.ReverseProxy{Director: director}

}


func main() {

    for _, route := range routes {

        http.Handle(route.match, NewProxy(&route))

    }


    log.Println("Listening on port 8080")

    http.ListenAndServe(":8080", nil)

}



慕少森
浏览 255回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go