[golang]-golang呼叫gitlab api增加刪除使用者

爺來辣發表於2020-12-11

導語:使用golang將使用者中文轉換成英文並建立使用者,並根據中文名刪除使用者。自己做個筆記備忘。判斷之類目前還不是很完善。

主要程式碼

package admin

import (
	"DEVOPS/models"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	// "reflect"
	"strings"

	"github.com/astaxie/beego"
	"github.com/yalp/jsonpath"
)

type GitlabController struct {
	BaseController
}

type Person struct { // 用於獲取gitlab使用者的id
	Id int
	// Name     string
	Username string
}

func (c *GitlabController) Add() {
	c.TplName = "admin/gitlab/add.html"
	// c.Ctx.WriteString("ADD")

}

func (c *GitlabController) DoAdd() {
	infra_access_token := beego.AppConfig.String("infra_access_token")
	infra_gitlab_url := beego.AppConfig.String("infra_gitlab_url")

	chinesename := strings.Trim(c.GetString("chinesename"), " ")
	beego.Info(chinesename)
	username := models.ChineseTo(chinesename)
	beego.Info(username)
	// 預設密碼Welcome1
	password := "Welcome1"
	// emailaddr
	emailaddr := username + "@163.com"
	beego.Info(emailaddr)

	beego.Info(password)
	if len(username) < 2 {
		// if len(username) < 2 || len(password) < 6 {
		c.Error("使用者名稱長度不合法", "/gitlab/add")
		return
	}
	// http請求

	beego.Info(infra_access_token)
	beego.Info(infra_gitlab_url)

	// 拼接url
	// url := "http://gitlab.ihaozhuo.com/api/v3/projects/" + str_id + "/repository/branches?simple=true"

	url := infra_gitlab_url + "/api/v4/users"
	beego.Info(url)

	// get請求根據專案id獲取專案分支json
	// url := "https://361way.com/api/users"
	req2, _ := http.NewRequest("GET", url, nil)
	req2.Header.Add("PRIVATE-TOKEN", infra_access_token)
	res2, _ := http.DefaultClient.Do(req2)
	defer res2.Body.Close()
	body2, _ := ioutil.ReadAll(res2.Body)
	// beego.Info(body2)  // [91 123 34 105 100 34 58] 輸出看不懂的東西
	// fmt.Println(string(body2))
	beego.Info("-----------------------------------------------")
	beego.Info("-----------------------------------------------")
	beego.Info("-----------------------------------------------")
	// 把body2轉換為string
	jobjson := string(body2)
	beego.Info(jobjson)

	// 提取json中的使用者資訊
	raw := []byte(jobjson)

	helloFilter, err := jsonpath.Prepare("$..username")
	if err != nil {
		panic(err)
	}

	var data interface{}
	if err = json.Unmarshal(raw, &data); err != nil {
		panic(err)
	}

	out, err := helloFilter(data)
	if err != nil {
		panic(err)
	}
	// 輸出使用者列表
	fmt.Printf("out type:%T\n", out)
	beego.Info("已建立使用者名稱如下")
	beego.Info(out)

	beego.Info("to string")
	userlist := Strval(out)
	fmt.Printf("out type:%T\n", userlist)
	beego.Info(userlist)
	res1 := strings.Contains(userlist, username)
	fmt.Println("\nResult 1: ", res1)
	if res1 {
		beego.Info("使用者存在 請勿重複建立")
		c.Error("使用者存在 請勿重複建立", "/gitlab/add")
		// c.Error("使用者存在 請勿重複建立", "/gitlab/add")
		return
	}
	beego.Info("使用者不存在可以新建")

	//  ---建立使用者
	//  curl -X POST -H "PRIVATE-TOKEN: ${access_token}" http://${gitlab_url}/api/v4/users -H 'cache-control: no-cache' -H 'content-type: application/json' -d '{ "email": "agou@163.com", "username": "agou", "password": "12345678", "name": "阿狗", "skip_confirmation": "true" }'
	// url := "https://361way.com/api/users"
	beego.Info("url", url)
	beego.Info("infra_access_token", infra_access_token)
	//json序列化
	post := "{\"email\":\"" + emailaddr +
		"\",\"username\":\"" + username +
		"\",\"password\":\"" + "12345678" +
		"\",\"name\":\"" + chinesename +
		"\",\"skip_confirmation\":\"" + "true" +
		"\"}"

	var jsonStr = []byte(post)

	// jsonStr := []byte(`{ "email": emailaddr, "username": username, "password": "12345678", "name": chinesename, "skip_confirmation": "true"  }`)
	req3, err3 := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req3.Header.Add("PRIVATE-TOKEN", infra_access_token)
	req3.Header.Set("Content-Type", "application/json")
	req3.Header.Set("cache-control", "no-cache")

	client3 := &http.Client{}
	resp3, _ := client3.Do(req3)
	if err3 != nil {
		// handle error
	}
	defer resp3.Body.Close()
	statuscode3 := resp3.StatusCode
	head3 := resp3.Header
	body3, _ := ioutil.ReadAll(resp3.Body)
	beego.Info("body3")
	fmt.Println(string(body3))
	beego.Info("statuscode3")
	fmt.Println(statuscode3)
	beego.Info("head3")
	fmt.Println(head3)
	c.Ctx.WriteString("已經獲取jenkins job 資訊")

}

func (c *GitlabController) Delete() {
	c.TplName = "admin/gitlab/delete.html"
	// c.Ctx.WriteString("ADD")

}

func (c *GitlabController) DoDelete() {
	infra_access_token := beego.AppConfig.String("infra_access_token")
	infra_gitlab_url := beego.AppConfig.String("infra_gitlab_url")

	chinesename := strings.Trim(c.GetString("chinesename"), " ")
	beego.Info(chinesename)
	username := models.ChineseTo(chinesename)
	beego.Info(username)

	if len(username) < 2 {
		// if len(username) < 2 || len(password) < 6 {
		c.Error("使用者名稱長度不合法", "/gitlab/add")
		return
	}
	// http請求

	beego.Info(infra_access_token)
	beego.Info(infra_gitlab_url)

	// 拼接url
	// url := "http://gitlab.ihaozhuo.com/api/v3/projects/" + str_id + "/repository/branches?simple=true"

	url := infra_gitlab_url + "/api/v4/users"
	beego.Info(url)

	// get請求根據專案id獲取專案分支json
	// url := "https://361way.com/api/users"
	req2, _ := http.NewRequest("GET", url, nil)
	req2.Header.Add("PRIVATE-TOKEN", infra_access_token)
	res2, _ := http.DefaultClient.Do(req2)
	defer res2.Body.Close()
	body2, _ := ioutil.ReadAll(res2.Body)
	// beego.Info(body2)  // [91 123 34 105 100 34 58] 輸出看不懂的東西
	// fmt.Println(string(body2))
	beego.Info("-----------------------------------------------")
	beego.Info("-----------------------------------------------")
	beego.Info("-----------------------------------------------")
	// 把body2轉換為string
	jobjson := string(body2)
	beego.Info(jobjson)

	// 提取json中的使用者資訊
	raw := []byte(jobjson)

	helloFilter, err := jsonpath.Prepare("$..username")
	if err != nil {
		panic(err)
	}

	var data interface{}
	if err = json.Unmarshal(raw, &data); err != nil {
		panic(err)
	}

	out, err := helloFilter(data)
	if err != nil {
		panic(err)
	}
	// 輸出使用者列表
	fmt.Printf("out type:%T\n", out)
	beego.Info("已建立使用者名稱如下")
	beego.Info(out)

	beego.Info("to string")
	userlist := Strval(out)
	fmt.Printf("out type:%T\n", userlist)
	beego.Info(userlist)
	res1 := strings.Contains(userlist, username)
	fmt.Println("\nResult 1: ", res1)
	if !res1 {
		beego.Info("使用者不存在 請確認")
		c.Error("使用者不存在 請確認", "/gitlab/delete")
		// c.Error("使用者存在 請勿重複建立", "/gitlab/add")
		return
	}
	beego.Info("使用者可以刪除    " + chinesename)
	// 獲取使用者的id
	beego.Info(jobjson)
	var person []Person

	err = json.Unmarshal(raw, &person)
	if err != nil {
		fmt.Println("error:", err)
	}
	beego.Info("jq")
	fmt.Printf("%+v", person)

	fmt.Printf("out type:%T\n", person)
	beego.Info("jq")
	// beego.Info("jq")
	// beego.Info(jq)
	for _, v := range person {
		// beego.Info(v)
		// fmt.Printf("out type:%T\n", v)
		beego.Info(v.Id, v.Username)
		if v.Username != username {
			beego.Info("使用者名稱不匹配", v.Username)

		} else {
			beego.Info("使用者名稱匹配成功", v.Username)
			beego.Info("使用者id為", v.Id)

			// 執行刪除
			//  curl  -X DELETE -H "PRIVATE-TOKEN: ${access_token}" http://${gitlab_url}/api/v4/users/${userid}?hard_delete=true
			delete_url := infra_gitlab_url + "/api/v4/users/" + strconv.Itoa(v.Id) + "?hard_delete=true"
			beego.Info("url", delete_url)
			beego.Info("infra_access_token", infra_access_token)


			req, _ := http.NewRequest("DELETE", delete_url, nil)
			req.Header.Add("PRIVATE-TOKEN", infra_access_token)
	 
			res, _ := http.DefaultClient.Do(req)
		 
			defer res.Body.Close()
			body, _ := ioutil.ReadAll(res.Body)
			statuscode := res.StatusCode
			head := res.Header
		 
			beego.Info(res)
			beego.Info(string(body))
			beego.Info(statuscode)
			beego.Info(head)

	
			c.Ctx.WriteString("已經獲取jenkins job 資訊")

			break
		}

	}
	c.Ctx.WriteString("content string")

	c.Success("刪除使用者成功", "/gitlab/delete")
}

建立使用者 阿斯頓

建立完成之後登陸測試

測試重複建立

刪除測試 刪除阿斯頓

相關文章