-
-
Save vkuznecovas/087fc18bef1a1b04b2e7d7863fae4868 to your computer and use it in GitHub Desktop.
GIN and GOTH OAuth example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"os" | |
"github.com/gin-gonic/gin" | |
"github.com/markbates/goth" | |
"github.com/markbates/goth/gothic" | |
"github.com/markbates/goth/providers/github" | |
) | |
func main() { | |
r := gin.Default() | |
githubProvider := github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:8080/callback") | |
goth.UseProviders(githubProvider) | |
htmlFormat := `<html><body>%v</body></html>` | |
r.GET("/", func(c *gin.Context) { | |
html := fmt.Sprintf(htmlFormat, `<a href="/github">Login through github</a>`) | |
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html)) | |
}) | |
r.GET("/github", func(c *gin.Context) { | |
q := c.Request.URL.Query() | |
q.Add("provider", "github") | |
c.Request.URL.RawQuery = q.Encode() | |
gothic.BeginAuthHandler(c.Writer, c.Request) | |
}) | |
r.GET("/callback", func(c *gin.Context) { | |
q := c.Request.URL.Query() | |
q.Add("provider", "github") | |
c.Request.URL.RawQuery = q.Encode() | |
user, err := gothic.CompleteUserAuth(c.Writer, c.Request) | |
if err != nil { | |
c.AbortWithError(http.StatusInternalServerError, err) | |
return | |
} | |
res, err := json.Marshal(user) | |
if err != nil { | |
c.AbortWithError(http.StatusInternalServerError, err) | |
return | |
} | |
jsonString := string(res) | |
html := fmt.Sprintf(htmlFormat, jsonString) | |
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html)) | |
}) | |
r.Run() // listen and serve on 0.0.0.0:8080 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment