Parse link header in golang

4

I want to make a request in Go to an API but the answers are paged so I have to go through them.

The pagination comes on the header in the element link , something like this:

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

I was trying to solve it with regular expressions and with Splits but in both cases I did not succeed.

The request I'm doing with the http library, like this:

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

and the Header.link I get it like this:

resp.Header.Get("link")

and the result is the string that I put above.

Question

How do I get the last page? And the others?

In the javascript world we have parse-link-header so maybe there is something similar in Go .

    
asked by Gepser 15.04.2016 в 02:58
source

2 answers

3

I found this little library linkheader to go, in any case you can see how it was implemented here main.go , they are only 120 lines but I see that they only use split since the structure of link header it's pretty simple. The regex always bring problems.

Example of use:

import (
    "fmt"

    "github.com/tomnomnom/linkheader"
)

func ExampleParse() {
    header := "<https://api.github.com/user/58276/repos?page=2>; rel=\"next\"," +
        "<https://api.github.com/user/58276/repos?page=2>; rel=\"last\""
    links := linkheader.Parse(header)

    for _, link := range links {
        fmt.Printf("URL: %s; Rel: %s\n", link.URL, link.Rel)
    }

    // Output:
    // URL: https://api.github.com/user/58276/repos?page=2; Rel: next
    // URL: https://api.github.com/user/58276/repos?page=2; Rel: last
}
    
answered by 15.04.2016 в 04:50
1

This I have solved using the standard library of go

var b strings.Builder
b.WriteString(urlERP)
b.WriteString(query)
b.WriteString(subQuery1)
b.WriteString(inicioQuery)
b.WriteString(subQuery2)
b.WriteString(finalQuery)
res, err := http.Get(url.QueryEscape(b.String()))

You need to use strings.Builder to be concatenated and since you have the string you code the URL using url.QueryEscape ()

    
answered by 12.09.2018 в 18:56