如何在Go主方法中重定向URL? [英] How to redirect URL in Go main method?

查看:711
本文介绍了如何在Go主方法中重定向URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Go中设置了一个GorrilaMux,如果在浏览器中输入特定的URL,将会进行API调用。如果URL是作为命令行参数提供的,我想在我的主要方法中进行相同的API调用。但是,似乎可以执行此操作的http.redirect()方法需要HTTP ResponseWriter和一个* HTTPRequest变量作为函数参数。我不知道如何在主要方法中生成这些变量。如何做到这一点,或者,有没有更好的方法来使用Golang中的URL进行API调用?

I have a GorrilaMux set up in Go that will make an API call if type in a specific URL in a browser. I want to make the same API call in my main method in go if the URL is given as a command line argument. However, the http.redirect() method which seems to be able to do this, requires a HTTP ResponseWriter and a *HTTPRequest variables as function parameters. I do not know how to produce these variables within a main method. How do I do this, OR, is there a better way to make the API call from the URL in Golang?

设置路由器的代码

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(????)

 }


推荐答案

HTTP重定向是对客户端的响应,应该从调用处理程序调用。 http.redirect(w http.ResponseWriter,r * http.Request)函数在主函数的上下文中没有意义。

An HTTP redirect is a response to a client and should be called from an invocation of a handler. The http.redirect(w http.ResponseWriter, r *http.Request) function has no meaning in the context of the main function.

您可以为给定路线注册一个处理程序,如下所示:

You can register a handler for the given route like so:

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是合乎逻辑的。

This adds a path to the router and invokes the simple http.Handlerfunc which contains a call to http.Redirect(...). Here this makes sense because we are handling a response to a client connection. It is logical to return a 301 status code and the URL for the target of the redirect.

这篇关于如何在Go主方法中重定向URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆