如何在Go语言中获取HTTP请求中的Links字段?

huangapple go评论76阅读模式
英文:

How to get Links field in http request GO

问题

我找到了这段代码片段:

import (
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

func getCommitsCount(ownerName string, repoName string) (int, error) {
	// 构建URL
	url := fmt.Sprintf("https://api.github.com/repos/%s/%s/commits?per_page=1", ownerName, repoName)

	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	// 获取响应头中的Link字段
	linkHeader := resp.Header.Get("Link")

	// 解析Link字段
	links := parseLinks(linkHeader)

	// 获取最后一页的页码
	lastPage, err := getLastPage(links)
	if err != nil {
		return 0, err
	}

	// 返回提交数量
	return lastPage, nil
}

func parseLinks(linkHeader string) map[string]string {
	links := make(map[string]string)

	// 按逗号分隔Link字段中的多个链接
	linkParts := strings.Split(linkHeader, ",")
	for _, linkPart := range linkParts {
		// 按分号分隔链接和参数
		parts := strings.Split(linkPart, ";")

		// 提取链接和关系类型
		link := strings.Trim(parts[0], " <>")
		rel := strings.Trim(parts[1], " ")

		// 提取关系类型中的引号内容
		rel = strings.Trim(rel, `"`)

		// 添加到links中
		links[rel] = link
	}

	return links
}

func getLastPage(links map[string]string) (int, error) {
	// 获取最后一页的链接
	lastLink, ok := links["last"]
	if !ok {
		return 0, fmt.Errorf("last link not found")
	}

	// 解析URL
	u, err := url.Parse(lastLink)
	if err != nil {
		return 0, err
	}

	// 获取最后一页的页码
	pageStr := u.Query().Get("page")
	lastPage, err := strconv.Atoi(pageStr)
	if err != nil {
		return 0, err
	}

	return lastPage, nil
}

这是一个用Go语言编写的等效代码。它使用net/http包发送HTTP请求,并解析响应头中的Link字段来获取最后一页的页码。parseLinks函数用于解析Link字段,getLastPage函数用于获取最后一页的页码。

希望对你有帮助!

英文:

I found this code snippet

import requests
from urllib.parse import parse_qs, urlparse
def get_commits_count(self, owner_name: str, repo_name: str) -&gt; int:
&quot;&quot;&quot;
Returns the number of commits to a GitHub repository.
&quot;&quot;&quot;
url = f&quot;https://api.github.com/repos/{owner_name}/{repo_name}/commits?per_page=1&quot;
r = requests.get(url)
links = r.links
rel_last_link_url = urlparse(links[&quot;last&quot;][&quot;url&quot;])
rel_last_link_url_args = parse_qs(rel_last_link_url.query)
rel_last_link_url_page_arg = rel_last_link_url_args[&quot;page&quot;][0]
commits_count = int(rel_last_link_url_page_arg)
return commits_count

And I need to do the same in Go. As it seems to me that I need to use something like "links" field (or whatever it is) in Go, but I can't find anything like this.

I'm stuck because I don't know what represents "links" in HTTP requests in Go.

答案1

得分: 0

所以,基本上我们需要通过response.Header["links"]来获取链接响应头。

links := resp.Header["Link"]
if len(links) == 0 {
return 0
}
var badlyParsedPageNumber = strings.Split(strings.Split(strings.Split(links[0], ", ")[1], "; ")[0],
"&page=")[1]
lastPage := badlyParsedPageNumber[0 : len(badlyParsedPageNumber)-1]

英文:

So, basically we need to take Link response header by doing response.Header["links"]

links := resp.Header[&quot;Link&quot;]
if len(links) == 0 {
return 0
}
var badlyParsedPageNumber = strings.Split(strings.Split(strings.Split(links[0], &quot;, &quot;)[1], &quot;; &quot;)[0],
&quot;&amp;page=&quot;)[1]
lastPage := badlyParsedPageNumber[0 : len(badlyParsedPageNumber)-1]

huangapple
  • 本文由 发表于 2022年10月10日 00:23:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/74006475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定