在使用 FastHTTP 时遇到 Redirect 问题,在 client
端与 server
端都存在,都有比较好的解决方法。
客户端 client
定义一个 fasthttp.Client
去读取某个页面,如 http://www.google.com
会出现301或302重定向,这时 fasthttp.Client 的 response 往往得到一个空的内容。为了解决这个问题,该库特别的添加了一个函数 DoRedirects
1
2
3
4
5
6
// It is recommended obtaining req and resp via AcquireRequest
// and AcquireResponse in performance-critical code.
func (c *Client) DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error {
_, _, err := doRequestFollowRedirects(req, resp, req.URI().String(), maxRedirectsCount, c)
return err
}
这个函数还可以定义最大重定向次数 maxRedirectsCount
。
一般我是这样定义一个客户端:
1
2
3
4
5
6
7
8
9
10
11
fastHttpClient = &fasthttp.Client{
TLSConfig: &tls.Config{InsecureSkipVerify: true},
NoDefaultUserAgentHeader: true, // Don't send: User-Agent: fasthttp
MaxConnsPerHost: 10000,
ReadBufferSize: 4096, // Make sure to set this big enough that your whole request can be read at once.
WriteBufferSize: 4096, // Same but for your response.
ReadTimeout: time.Second,
WriteTimeout: time.Second,
MaxIdleConnDuration: time.Minute,
DisableHeaderNamesNormalizing: true, // If you set the case on your headers correctly you can enable this.
}
请求:
1
2
3
4
err := fastHttpClient.DoRedirects(req, res, 5)
if err != nil {
fmt.Println("fastHttpClient.Do", err)
}
服务器端
经常在 handle 里使用这样的重定向
1
ctx.Redirect("/admin/login", 302)
如果是裸跑 go web 应用,结果正常,但前面架个代理,如 nginx 或 caddy :
1
proxy http://127.0.0.1:8182
这就会重定向到 http://127.0.0.1:8182
,而不是对外使用的域名,解决这问题只能在程序里指定固定域名,把域名全路径都写在 ctx.Redirect
里:
1
2
var mainDomain = "http://ijd8.com"
ctx.Redirect(mainDomain+"/admin/login", 302)
Over !