68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package worker
|
|
|
|
import (
|
|
"StuAcaWorksAI/proto"
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
// 获取access token
|
|
func ExchangeCodeForAccessToken(clientID, clientSecret, code, redirectURI string) (proto.GitHubOAuthResponse, error) {
|
|
request := proto.GitHubOAuthRequest{
|
|
ClientID: clientID,
|
|
ClientSecret: clientSecret,
|
|
Code: code,
|
|
RedirectURI: redirectURI,
|
|
}
|
|
|
|
payload, err := json.Marshal(request)
|
|
if err != nil {
|
|
return proto.GitHubOAuthResponse{}, err
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewBuffer(payload))
|
|
if err != nil {
|
|
return proto.GitHubOAuthResponse{}, err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return proto.GitHubOAuthResponse{}, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return proto.GitHubOAuthResponse{}, err
|
|
}
|
|
|
|
var response proto.GitHubOAuthResponse
|
|
err = json.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return proto.GitHubOAuthResponse{}, err
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
// 获取用户信息
|
|
func GetGitHubUserInfo(accessToken string) {
|
|
|
|
url := "https://api.github.com/user"
|
|
headers := map[string]string{
|
|
"Authorization": "Bearer " + accessToken,
|
|
}
|
|
err, data := DoGetRequest(url, headers)
|
|
if err != nil {
|
|
return
|
|
}
|
|
fmt.Println("User Info:", string(data))
|
|
}
|