-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.go
75 lines (61 loc) · 1.71 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"
"net/http"
"time"
"github.com/go-resty/resty/v2"
)
var httpClient = &http.Client{
Timeout: 2 * time.Minute,
}
// GitHubUserProfile represents the user profile data received
// from GitHub after successful authentication.
type GitHubUserProfile struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
Type string `json:"type"`
Name string `json:"name"`
Company string `json:"company"`
Blog string `json:"blog"`
Location string `json:"location"`
Email string `json:"email"`
Bio string `json:"bio"`
TwitterUsername string `json:"twitter_username"`
}
type OauthResponse struct {
AccessToken string `json:"access_token"`
}
// getGitHubUserProfile retrives the authenticated user's profile.
func getGitHubUserProfile(
ctx context.Context,
accessToken string,
) (*GitHubUserProfile, error) {
endpoint := "https://api.github.com/user"
var userProfile GitHubUserProfile
client := resty.NewWithClient(httpClient)
_, err := client.R().
SetHeader("Accept", "application/json").
SetHeader("Authorization", "token "+accessToken).
SetContext(ctx).
SetResult(&userProfile).
Get(endpoint)
return &userProfile, err
}
// exchangeCodeForToken exchanges the received Oauth code for an access token.
func exchangeCodeForToken(
ctx context.Context,
endpoint string,
) (*OauthResponse, error) {
var oauth OauthResponse
client := resty.NewWithClient(httpClient)
_, err := client.R().
SetHeader("Accept", "application/json").
SetContext(ctx).
SetResult(&oauth).
Post(endpoint)
if err != nil {
return nil, err
}
return &oauth, nil
}