这里只介绍一些api的使用方式 不一定全面

一 背景介绍

gitlabv3 api地址https://gitlab.com/gitlab-org/gitlab-foss/-/blob/8-16-stable/doc/api/groups.md
gitlab的api分为v3 和v4 godoc的一些包 只支持v4 但是v3的不支持
所以自己写了一些简单的调用 还需要继续封装
gitlab api地址https://docs.gitlab.com/ee/api/

//获取项目列表
//main.go
package main

import (

	"fmt"
	"log"
	. "ali/gitlab/v4"
)
func main() {
	method := "GET"
	g := []Project{}
	url := GetUrl("project")
	//这里是分页获取 每次获取100个
	url = url + "?per_page=100"
	err := Req(method,url,&g)
	if err != nil {
		log.Println(err)
		return
	}
	for _,v := range g {
		fmt.Printf("%#v\n",v)
	}
}
package v4

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"
)


var Url = "http://gitlab地址/api/v4/"

func GetUrl(t string) string {
	switch  t {
	case "group":
		return Url+"groups"
	case "project":
	//这里 groups/项目id/projects
		return  Url+ "groups/35/projects"
	}
	return  ""

}

type Group struct {
	ID int `json:"id"`
	Name string `json:"name"`
	Path string `json:"path"`
	Description string `json:"description"`
	AvatarURL interface{} `json:"avatar_url"`
	WebURL string `json:"web_url"`
}


type Project struct {
	ID int `json:"id"`
	Description string `json:"description"`
	Name string `json:"name"`
	NameWithNamespace string `json:"name_with_namespace"`
	Path string `json:"path"`
	PathWithNamespace string `json:"path_with_namespace"`
	CreatedAt time.Time `json:"created_at"`
	DefaultBranch string `json:"default_branch"`
	TagList []interface{} `json:"tag_list"`
	SSHURLToRepo string `json:"ssh_url_to_repo"`
	HTTPURLToRepo string `json:"http_url_to_repo"`
	WebURL string `json:"web_url"`
	ReadmeURL string `json:"readme_url"`
	AvatarURL interface{} `json:"avatar_url"`
	ForksCount int `json:"forks_count"`
	StarCount int `json:"star_count"`
	LastActivityAt time.Time `json:"last_activity_at"`
	Namespace Namespace `json:"namespace"`
	Links Links `json:"_links"`
	PackagesEnabled interface{} `json:"packages_enabled"`
	EmptyRepo bool `json:"empty_repo"`
	Archived bool `json:"archived"`
	Visibility string `json:"visibility"`
	ResolveOutdatedDiffDiscussions bool `json:"resolve_outdated_diff_discussions"`
	ContainerRegistryEnabled bool `json:"container_registry_enabled"`
	ContainerExpirationPolicy ContainerExpirationPolicy `json:"container_expiration_policy"`
	IssuesEnabled bool `json:"issues_enabled"`
	MergeRequestsEnabled bool `json:"merge_requests_enabled"`
	WikiEnabled bool `json:"wiki_enabled"`
	JobsEnabled bool `json:"jobs_enabled"`
	SnippetsEnabled bool `json:"snippets_enabled"`
	ServiceDeskEnabled bool `json:"service_desk_enabled"`
	ServiceDeskAddress interface{} `json:"service_desk_address"`
	CanCreateMergeRequestIn bool `json:"can_create_merge_request_in"`
	IssuesAccessLevel string `json:"issues_access_level"`
	RepositoryAccessLevel string `json:"repository_access_level"`
	MergeRequestsAccessLevel string `json:"merge_requests_access_level"`
	ForkingAccessLevel string `json:"forking_access_level"`
	WikiAccessLevel string `json:"wiki_access_level"`
	BuildsAccessLevel string `json:"builds_access_level"`
	SnippetsAccessLevel string `json:"snippets_access_level"`
	PagesAccessLevel string `json:"pages_access_level"`
	EmailsDisabled interface{} `json:"emails_disabled"`
	SharedRunnersEnabled bool `json:"shared_runners_enabled"`
	LfsEnabled bool `json:"lfs_enabled"`
	CreatorID int `json:"creator_id"`
	ImportStatus string `json:"import_status"`
	OpenIssuesCount int `json:"open_issues_count"`
	CiDefaultGitDepth int `json:"ci_default_git_depth"`
	PublicJobs bool `json:"public_jobs"`
	BuildTimeout int `json:"build_timeout"`
	AutoCancelPendingPipelines string `json:"auto_cancel_pending_pipelines"`
	BuildCoverageRegex interface{} `json:"build_coverage_regex"`
	CiConfigPath interface{} `json:"ci_config_path"`
	SharedWithGroups []interface{} `json:"shared_with_groups"`
	OnlyAllowMergeIfPipelineSucceeds bool `json:"only_allow_merge_if_pipeline_succeeds"`
	AllowMergeOnSkippedPipeline interface{} `json:"allow_merge_on_skipped_pipeline"`
	RequestAccessEnabled bool `json:"request_access_enabled"`
	OnlyAllowMergeIfAllDiscussionsAreResolved bool `json:"only_allow_merge_if_all_discussions_are_resolved"`
	RemoveSourceBranchAfterMerge bool `json:"remove_source_branch_after_merge"`
	PrintingMergeRequestLinkEnabled bool `json:"printing_merge_request_link_enabled"`
	MergeMethod string `json:"merge_method"`
	SuggestionCommitMessage interface{} `json:"suggestion_commit_message"`
	AutoDevopsEnabled bool `json:"auto_devops_enabled"`
	AutoDevopsDeployStrategy string `json:"auto_devops_deploy_strategy"`
	AutocloseReferencedIssues bool `json:"autoclose_referenced_issues"`
	RepositoryStorage string `json:"repository_storage"`
}
type Namespace struct {
	ID int `json:"id"`
	Name string `json:"name"`
	Path string `json:"path"`
	Kind string `json:"kind"`
	FullPath string `json:"full_path"`
	ParentID interface{} `json:"parent_id"`
	AvatarURL interface{} `json:"avatar_url"`
	WebURL string `json:"web_url"`
}
type Links struct {
	Self string `json:"self"`
	Issues string `json:"issues"`
	MergeRequests string `json:"merge_requests"`
	RepoBranches string `json:"repo_branches"`
	Labels string `json:"labels"`
	Events string `json:"events"`
	Members string `json:"members"`
}
type ContainerExpirationPolicy struct {
	Cadence string `json:"cadence"`
	Enabled bool `json:"enabled"`
	KeepN int `json:"keep_n"`
	OlderThan string `json:"older_than"`
	NameRegex interface{} `json:"name_regex"`
	NameRegexKeep interface{} `json:"name_regex_keep"`
	NextRunAt time.Time `json:"next_run_at"`
}


func Req(method ,url string,d interface{}) error{
	client := &http.Client {}
	req, err := http.NewRequest(method, url, nil)
	if err != nil {return err}
	req.Header.Add("PRIVATE-TOKEN", "token")
	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err
	}
	err  = json.Unmarshal(body,d)
	if err != nil {
		return err
	}
	return  nil
}

二 创建项目

//create_project.go
package v3

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
)
var (
	token = "token"
	url = "http://gitlab_url/api/v3/projects/"
	method = "POST"
	id = "所在的group id"
)
func Create_Porject(name ,desc string) (*string,error) {
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	_ = writer.WriteField("path", name)
	_ = writer.WriteField("description", desc)
	_ = writer.WriteField("visibility", "Private")
	_ = writer.WriteField("name", name)
	_ = writer.WriteField("namespace_id", id)
	err := writer.Close()
	if err != nil {
		fmt.Println(err)
	}
	client := &http.Client {
	}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
	}
	req.Header.Add("PRIVATE-TOKEN", token)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	g := &Group{}
	err = json.Unmarshal(body,g)
	if err != nil {
		return nil,err
	}
	return &g.SSHURLToRepo,nil
}
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐