How to call/open a URL within Go method?

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年10月27日 03:32:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/33354077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定