first up
This commit is contained in:
66
main.go
Normal file
66
main.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/go-github/github"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
var (
|
||||
clientID = "YOUR_CLIENT_ID"
|
||||
clientSecret = "YOUR_CLIENT_SECRET"
|
||||
redirectURL = "http://localhost:8080/callback"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 创建OAuth配置
|
||||
oauthConf := &oauth2.Config{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
RedirectURL: redirectURL,
|
||||
Scopes: []string{"user:email"},
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: "https://github.com/login/oauth/authorize",
|
||||
TokenURL: "https://github.com/login/oauth/access_token",
|
||||
},
|
||||
}
|
||||
|
||||
// 创建HTTP处理程序
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
// 重定向到GitHub OAuth登录页面
|
||||
url := oauthConf.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
||||
})
|
||||
|
||||
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
// 获取访问令牌
|
||||
code := r.URL.Query().Get("code")
|
||||
token, err := oauthConf.Exchange(context.Background(), code)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to exchange token", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 创建GitHub客户端
|
||||
client := github.NewClient(oauthConf.Client(context.Background(), token))
|
||||
|
||||
// 获取用户数据
|
||||
user, _, err := client.Users.Get(context.Background(), "")
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to get user", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 在控制台上打印用户数据
|
||||
fmt.Printf("Hello, %s\n", *user.Name)
|
||||
})
|
||||
|
||||
// 启动HTTP服务器
|
||||
fmt.Println("Server listening on http://localhost:8080")
|
||||
if err := http.ListenAndServe(":8080", nil); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user