导语:使用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")
}
创建用户 阿斯顿
创建完成之后登陆测试
测试重复创建
删除测试 删除阿斯顿