英文:
Get last page http request golang
问题
我正在进行类似这样的http请求
:
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
页,但first
和next
页也应该有用。
我尝试过使用Split
和正则表达式
,但没有成功。
英文:
I am doing an http request
like this one:
resp, err := http.Get("http://example.com/")
Then I am getting the header link
:
link := resp.Header.Get("link")
Which gives me a result like this:
<page=3>; rel="next",<page=1>; rel="prev";<page=5>; rel="last"
Question
How can I parse this into a more legible way? I specifically trying to get the last
page but first
and next
page should useful as well.
I tried with Splits
and Regular expressions
without success.
答案1
得分: 1
以下是如何匹配页面编号的解决方案。
http://play.golang.org/p/kzurb38Fwx
text := `<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 {
next := matches[1]
prev := matches[2]
last := matches[3]
fmt.Printf("next = %s, prev = %s, last = %s\n", next, prev, last)
}
后续编辑:您可能还可以使用xml包以相同的结果,通过将输出解析为XML,但您需要稍微转换一下输出。
英文:
Here's a solution of how to match your page numbers.
http://play.golang.org/p/kzurb38Fwx
text := `<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 {
next := matches[1]
prev := matches[2]
last := matches[3]
fmt.Printf("next = %s, prev = %s, last = %s\n", next, prev, last)
}
Later Edit: you can probably also use the xml package to achieve the same result, by parsing that output as an XML, but you would need to transform your output a bit.
答案2
得分: 1
你确定这是输出的格式吗?看起来其中一个;
应该是,
。
一个带有多个值的单个链接的格式应该是这样的(注意在“prev”后面的逗号):
<page=3>; rel="next",<page=1>; rel="prev",<page=5>; rel="last"
应该按照,
拆分每个链接的顺序。对于每个链接,应该按照;
拆分值或键值对,然后如果值匹配<(.*=.*)>
,则丢弃尖括号并使用剩余的键和值。
英文:
Are you sure that is the format of the output? It looks like one of ;
should be a ,
.
A single Link http header with multiple values, should be of the format (notice the comma after "prev")
<page=3>; rel="next",<page=1>; rel="prev",<page=5>; rel="last"
The order should be split on ,
for each link. Split each link on ;
for values or key-value pairs, and then if they value matches <(.*=.*)>
, discard the angle brackets and use the remaining key and value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论