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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
const (
clientID = ""
clientSecret = ""
redirectURI = "http://localhost:8080/callback" // 确保与 GitHub 应用配置一致
)
func main() {
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/callback", callbackHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
authURL := "https://github.com/login/oauth/authorize"
u, err := url.Parse(authURL)
if err != nil {
http.Error(w, "Failed to build URL", http.StatusInternalServerError)
return
}
q := u.Query()
q.Set("client_id", clientID)
q.Set("redirect_uri", redirectURI)
u.RawQuery = q.Encode()
http.Redirect(w, r, u.String(), http.StatusFound)
}
func callbackHandler(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
fmt.Println("Authorization code:", code)
token, err := exchangeCodeForToken(code)
// fmt.Println(token)
if err != nil {
http.Error(w, "Failed to get access token", http.StatusInternalServerError)
fmt.Println("Error getting access token:", err)
return
}
userInfo, err := getUserInfo(token)
if err != nil {
http.Error(w, "Failed to get user info", http.StatusInternalServerError)
fmt.Println("Error getting user info:", err)
return
}
fmt.Fprintf(w, "User Info: %s", userInfo)
fmt.Printf("UserInfo: %s", userInfo)
}
func exchangeCodeForToken(code string) (string, error) {
tokenURL := "https://github.com/login/oauth/access_token"
resp, err := http.PostForm(tokenURL, url.Values{
"client_id": {clientID},
"client_secret": {clientSecret},
"code": {code},
"redirect_uri": {redirectURI},
})
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to get access token, status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Print the raw response for debugging purposes
fmt.Printf("Token exchange response: %s\n", string(body))
// Parse the response to extract the access token
values, err := url.ParseQuery(string(body))
if err != nil {
return "", err
}
accessToken := values.Get("access_token")
if accessToken == "" {
return "", fmt.Errorf("access_token not found in response")
}
return accessToken, nil
}
func getUserInfo(token string) (string, error) {
userURL := "https://api.github.com/user"
req, err := http.NewRequest("GET", userURL, nil)
if err != nil {
return "", err
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("User-Agent", "Go OAuth App") // GitHub API requires a User-Agent header
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
|