This repository has been archived by the owner on Dec 19, 2022. It is now read-only.
forked from leominov/gitlab-project-settings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
64 lines (52 loc) · 1.36 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type User map[string]interface{}
func (p User) Get(key string) interface{} {
return p[key]
}
func (c *Client) GetUserIdByName(name string) (int, error) {
resp, err := c.doRequest(http.MethodGet, fmt.Sprintf("users?username=%s", name), nil)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return 0, fmt.Errorf("Error searching for user %s. Return code not 2XX: %s", name, resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
usr := []*User{}
if err := json.Unmarshal(b, &usr); err != nil {
return 0, err
}
if l := len(usr); l != 1 {
return 0, fmt.Errorf("Found %d %s users, need one", l, name)
}
return int(usr[0].Get("id").(float64)), nil
}
func (c *Client) GetUserNameById(id int) (string, error) {
resp, err := c.doRequest(http.MethodGet, fmt.Sprintf("users/%d", id), nil)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return "", fmt.Errorf("Error searching for user %d. Return code not 2XX: %s", id, resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
usr := User{}
if err := json.Unmarshal(b, &usr); err != nil {
return "", err
}
return usr.Get("username").(string), nil
}