在Go语言中,一直比较好奇如何进行跳转控制,最近正好看了下gocrawl的源码,结合GoDoc,解决了这个疑惑:
type Client struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport RoundTripper // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // first. If CheckRedirect returns an error, the Client's Get // method returns both the previous Response and // CheckRedirect's error (wrapped in a url.Error) instead of // issuing the Request req. // // If CheckRedirect is nil, the Client uses its default policy, // which is to stop after 10 consecutive requests. CheckRedirect func(req *Request, via []*Request) error // Jar specifies the cookie jar. // If Jar is nil, cookies are not sent in requests and ignored // in responses. Jar CookieJar }
具体案例如下:
func httpReq(url string) (int, string, error){ client := &http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error { return errors.New("Redirected!") }} resp, err := client.Get(url) defer resp.Body.Close() redir := "" if (resp.StatusCode > 300 && resp.StatusCode < 400) { redir = resp.Header.Get("Location") } return resp.StatusCode, redir, err }
如同上面提到的,GoDoc工具是Go语言中内置的一个文档查看工具,可以使用
godoc -http=:8080
在本地8080端口打开了一个和golang.org相似的网站,考虑到golang.org经常被墙的问题,这个还是蛮有用的。GoDoc优点是相对golang.org,godoc生成的文件还包含了自己安装的包文件的文档(前提是提供)。
当然也可以命令行下使用:
godoc fmt Println
这样就查看了fmt.Println的使用方法。