我在Go中设置了一个GorrilaMux,如果在浏览器中键入特定的URL,它将进行API调用。如果URL作为命令行参数给出,我想在我的main方法中进行相同的API调用。但是,似乎能够执行此操作的http.redirect()方法需要HTTP ResponseWriter和* HTTPRequest变量作为函数参数。我不知道如何在main方法中生成这些变量。我该怎么做,或者,有没有更好的方法从Golang中的URL进行API调用?
设置路由器的代码
func main(){
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes { //Sets up predefined routes
router.
Path(route.Path).
Name(route.Name).
Handler(route.HandlerFunc)
}
URL:="localhost:8080/whatever" //URL I want to redirect, route would be "/whatever"
http.redirect(????)
}
答案 0 :(得分:1)
HTTP重定向是对客户端的响应,应该从处理程序的调用中调用。 http.redirect(w http.ResponseWriter, r *http.Request)
函数在main函数的上下文中没有意义。
您可以像这样注册给定路线的处理程序:
router.Path("/whatever").Handler(func(writer http.ResponseWriter, req *http.Request) {
http.Redirect(writer, req, "localhost:8080/whatever", http.StatusMovedPermanently)
))
这会添加路由器的路径,并调用包含对http.Handlerfunc
的调用的简单http.Redirect(...)
。这有意义,因为我们正在处理对客户端连接的响应。返回301状态代码和重定向目标的URL是合乎逻辑的。