golang操作gitlab API:获取某个group下的所有仓库并写入文件 && 解决gitpab限制单次查询100条的限制

获取某个group下的仓库:
https://git.xxxxxx.com/api/v4/groups/group_id/projects

获取所有仓库:
https://git.xxxxxx.com/api/v4/projects

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math"
	"net/http"
	"os"
	"os/exec"
	"strconv"

	"github.com/bitly/go-simplejson"
)

const (
	PRIVATE_TOKEN  = "ThmspJQsBdf99nBYEo5Ns-wRxxx"
	GET_DMCCA_HEAD = "https://git.xxxxxx.com/api/v4/groups/group_id/projects"
	REPOS_FILE     = "gitlab-url.txt"
)

var (
	client *http.Client = &http.Client{}
	repos  string
)

func getTotal() {
	head, err := http.NewRequest("HEAD", GET_DMCCA_HEAD, nil)
	if err != nil {
		log.Panicln(err)
	}
	head.Header.Add("PRIVATE-TOKEN", PRIVATE_TOKEN)
	r, err := client.Do(head)
	if err != nil {
		log.Panicln(err)
	}
	defer r.Body.Close()
	totalNums, _ := strconv.Atoi(r.Header.Get("X-Total"))
	fmt.Printf("totalNums: %v\n", totalNums)
	page := int(math.Ceil(float64(totalNums) / 100))
	for i := 1; i <= page; i++ {
		getProjects(i)
	}
}

func getProjects(page int) {
	GET_DMCCA_PROJECTS := "https://git.xxxxxx.com/api/v4/groups/group_id/projects?per_page=100&page=" + strconv.Itoa(page) + "&simple=true"
	req, err := http.NewRequest("GET", GET_DMCCA_PROJECTS, nil)
	if err != nil {
		log.Panicln(err)
	}
	req.Header.Add("PRIVATE-TOKEN", PRIVATE_TOKEN)
	resp, err := client.Do(req)
	if err != nil {
		log.Panicln(err)
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Panicln(err)
	}
	var aa []map[string]interface{}
	json.Unmarshal(body, &aa)
	// http_url_to_repo
	fmt.Printf("len(aa): %v\n", len(aa))
	for _, project := range aa {
		byt, _ := json.Marshal(project)
		json, _ := simplejson.NewJson(byt)
		s, _ := json.Get("http_url_to_repo").Interface().(string)
		repos = s + "\n" + repos
	}
}

func WriteFile() {
	fmt.Printf("repos: %v\n", repos)
	file, err2 := os.OpenFile(REPOS_FILE, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
	defer file.Close()
	if err2 != nil {
		log.Panicln(err2)
	}
	w := bufio.NewWriter(file)
	w.WriteString(repos)
	w.Flush()
}

func main() {
	// 获取group_id group下所有代码仓库
	getTotal()
	// 将git仓库URL地址写入文件
	WriteFile()
	// 删除最后一行的空行
	sed := exec.Command("sed -i  ':n;/^\n*$/{$! N;;bn}' ", REPOS_FILE)
	sed.Run()

}

gitlab文档地址:
https://docs.gitlab.com/ee/api/groups.html#list-group-hooks

参考链接:
https://ranying666.github.io/2017/06/20/gitlab-api/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学亮编程手记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值