golang操作golang.org/x/oauth2库第三方登录github
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)
var (
githubOauthConfig = &oauth2.Config{
ClientID: "14023dc0974e8eef4aea",
ClientSecret: "eb869c9936f2c6e0de68f1fe2ed3680127cc1ef8",
Scopes: []string{"user:email", "repo"},
Endpoint: github.Endpoint,
}
)
func handleGithubLogin(c *gin.Context) {
authURL := githubOauthConfig.AuthCodeURL("state")
c.Redirect(http.StatusTemporaryRedirect, authURL)
}
func handleGithubCallback(c *gin.Context) {
code := c.Query("code")
token, err := githubOauthConfig.Exchange(c, code)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"access_token": token.AccessToken})
}
func main() {
r := gin.Default()
githubOauthConfig.RedirectURL = "http://localhost:8080/github/callback"
r.GET("/github/login", handleGithubLogin)
r.GET("/github/callback", handleGithubCallback)
r.Run(":8080")
}