获取最后一页 http 请求 golang

我正在做一个http request这样的:

resp, err := http.Get("http://example.com/")

然后我得到header link

link := resp.Header.Get("link")

这给了我这样的结果:

<page=3>; rel="next",<page=1>; rel="prev";<page=5>; rel="last"

问题

如何将其解析为更清晰的方式?我特别想获得的last页面,但firstnext页面应该有用。

我尝试过,SplitsRegular expressions没有成功。


Smart猫小萌
浏览 194回答 2
2回答

呼唤远方

你确定这是输出的格式吗?看起来其中之一;应该是,.&nbsp;具有多个值的单个 Link http 标头应采用以下格式(注意“prev”后的逗号)<page=3>;&nbsp;rel="next",<page=1>;&nbsp;rel="prev",<page=5>;&nbsp;rel="last"应该,为每个链接拆分订单。拆分每个链接以;获取值或键值对,然后如果它们的值匹配<(.*=.*)>,则丢弃尖括号并使用剩余的键和值。

繁星淼淼

这是如何匹配页码的解决方案。http://play.golang.org/p/kzurb38Fwxtext := `<page=3>; rel="next",<page=1>; rel="prev";<page=2>; rel="last"`re := regexp.MustCompile(`<page=([0-9]+)>; rel="next",<page=([0-9]+)>; rel="prev";<page=([0-9]+)>; rel="last"`)matches:= re.FindStringSubmatch(text)if matches != nil {&nbsp; &nbsp; next := matches[1]&nbsp; &nbsp; prev := matches[2]&nbsp; &nbsp; last := matches[3]&nbsp; &nbsp; fmt.Printf("next = %s, prev = %s, last = %s\n", next, prev, last)}稍后编辑:您可能也可以使用 xml 包来实现相同的结果,通过将该输出解析为 XML,但您需要稍微转换一下输出。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go