Go:将用户名添加到URL

时间:2014-08-30 07:58:29

标签: go

如何将当前用户或其他变量的用户名添加到Go中URL路径的末尾?

我尝试使用http.Redirect(w,“/ home /”+ user,http.StatusFound),但这会创建一个无限重定向循环。

去:

func homeHandler(w http.ResponseWriter, r *http.Request) {
    randIndex = rand.Intn(len(cityLibrary))
    ImageDisplay()
    WeatherDisplay()
    dispdata = AllApiData{Images: imagesArray, Weather: &WeatherData{Temp: celsiusNum, City: cityLibrary[randIndex], RainShine: rainOrShine}}

    //http.Redirect(w, "/"+cityLibrary[randIndex], http.StatusFound) --> infinite redirect loop

    renderTemplate(w, "home", dispdata)
    }

func main() {
    http.HandleFunc("/", homeHandler)

    http.Handle("/layout/", http.StripPrefix("/layout/", http.FileServer(http.Dir("layout"))))

    http.ListenAndServe(":8000", nil)
}

在这段代码中,我试图将“City”的值附加到根URL的末尾。我应该使用正则表达式吗?

1 个答案:

答案 0 :(得分:3)

似乎这种情况正在发生,因为您没有/{city}/处理程序,而/处理程序正在匹配重定向到城市的所有请求:

  

模式名称是固定的,有根的路径,例如" /favicon.ico"或根管子树,例如" / images /" (注意斜杠)。较长的模式优先于较短的模式,因此如果有两个处理程序注册了" / images /"和" / images / thumbnails /",后面的处理程序将被调用路径开始" / images / thumbnails /"前者将接收" / images /"中任何其他路径的请求;子树。

     

请注意,由于以斜杠结尾的模式命名为有根的子树,因此模式" /"匹配所有与其他注册模式不匹配的路径,而不仅仅是带有Path ==" /"的网址。

您需要做的是放入城市网址处理程序,如果您需要处理RegEx模式,请查看this,或者您可以使用更强大的路由器,如gorilla's mux


  

什么只是使用没有大猩猩的Go?我知道如何在大猩猩中做到这一点,但我只是想知道它是如何在Go中完成的。

您可以使用前面提到的答案中提到的自定义处理程序: https://stackoverflow.com/a/6565407/220710

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

要使用此功能,您可以执行以下操作:

import regexp

...

rex := RegexpHandler{}
rex.HandlerFunc(regexp.MustCompile("^/(\w+?)/?"), cityHandler) // cityHandler is your regular handler function
rex.HandlerFunc(regexp.MustCompile("^/"), homeHandler)
http.Handle("/", &rex)
http.ListenAndServe(":8000", nil)