-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathgithub.go
75 lines (63 loc) · 1.57 KB
/
github.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
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Millisecond)
defer cancel()
fmt.Println(githubInfo(ctx, "tebeka"))
}
// githubInfo returns name and number of public repos for login
func githubInfo(ctx context.Context, login string) (string, int, error) {
url := "https://api.github.com/users/" + url.PathEscape(login)
// resp,err := http.Get(url)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", 0, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", 0, err
}
if resp.StatusCode != http.StatusOK {
return "", 0, fmt.Errorf("%#v - %s", url, resp.Status)
}
defer resp.Body.Close()
// fmt.Printf("Content-Type: %s\n", resp.Header.Get("Content-Type"))
// var r Reply
var r struct { // anonymous struct
Name string
// Public_Repos int
NumRepos int `json:"public_repos"`
}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&r); err != nil {
return "", 0, err
}
return r.Name, r.NumRepos, nil
}
/*
type Reply struct {
Name string
// Public_Repos int
NumRepos int `json:"public_repos"`
}
*/
/* JSON <-> Go
true/false <-> true/false
string <-> string
null <-> nil
number <-> float64, float32, int8, int16, int32, int64, int, uint8, ...
array <-> []any ([]interface{})
object <-> map[string]any, struct
encoding/json API
JSON -> io.Reader -> Go: json.Decoder
JSON -> []byte -> Go: json.Unmarshal
Go -> io.Writer -> JSON: json.Encoder
Go -> []byte -> JSON: json.Marshal
*/