英文:
How to call/open a URL within Go method?
问题
你可以使用http.NewRequest
函数创建一个新的请求对象,然后将URL作为请求的URL。然后,你可以使用router.ServeHTTP
方法将该请求传递给你的路由器,以便调用相应的处理函数。
以下是一个示例代码片段,展示了如何在命令行中传递URL并将其路由到处理函数:
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"github.com/gorilla/mux"
)
func main() {
u, err := url.Parse(os.Args[1])
if err != nil {
fmt.Println(err.Error())
return
}
router := mux.NewRouter()
router.HandleFunc("/example", exampleHandler)
// 创建一个新的请求对象
req := http.NewRequest("GET", u.String(), nil)
// 将请求传递给路由器
router.ServeHTTP(nil, req)
}
func exampleHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
在上面的示例中,我们使用mux.NewRouter
创建了一个新的路由器,并使用router.HandleFunc
将/example
路径与exampleHandler
函数关联起来。然后,我们使用http.NewRequest
创建一个新的请求对象,并将命令行中传递的URL作为请求的URL。最后,我们使用router.ServeHTTP
将请求传递给路由器,以便调用相应的处理函数。
请注意,上述示例中的代码片段仅用于演示目的,你可能需要根据你的实际情况进行适当的修改。
英文:
I have a Gorilla Mux router set up in Go. I have routes set up within that router, as well as function handlers associated with those routes. The router works perfectly, if you open a browser window and enter specific URLs. However, the problem I'm running into is what to do if the URL is entered on the command line. I know how to store the URL from the command line arguments, but I don't know how to forward the URL, stored as a URL variable in Go, to the router. Like, how do you call a route's function handler if the URL is given on the command line INSTEAD of entered via browser window?
Code:
u, err := url.Parse(os.Args[1])
if err != nil {
fmt.Println(err.Error())
}
host, port, _ := net.SplitHostPort(u.Host)
s := []string{":", port};
router := ANewRouter()
log.Fatal(http.ListenAndServe(strings.Join(s, ""), router))
//Route URL to router, somehow
答案1
得分: 1
如果你想在Go中进行HTTP请求,标准库中有一些易于使用的方法,可以在https://golang.org/pkg/net/http/找到。
正如JimB在评论中指出的那样,你可以使用类似curl
的工具,完全不使用Go。在我看来,从Go中启动curl
并没有太多意义,因为你可以直接使用resp, err := http.Get(urlArg)
来获得相同的结果。还有其他HTTP动词的方法,如果你需要更精细地控制请求,可以使用Do
方法和创建Request
对象来设置头部等操作。
英文:
If you're trying to make an HTTP request in Go there are easy to use methods for that purpose in the standard library at; https://golang.org/pkg/net/http/
As JimB pointed out in comment you could use something like curl
and just forgo using Go altogether. Launching curl
from Go doesn't make a whole lot of sense to me when you can just do resp, err := http.Get(urlArg)
and get the same result. There are also methods for other HTTP verbs and if you need more fine tuned control of the request you can use the Do
method and create Request
object to do things like set headers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论