Skip to content

Instantly share code, notes, and snippets.

@vkuznecovas
Created May 31, 2018 12:10
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vkuznecovas/087fc18bef1a1b04b2e7d7863fae4868 to your computer and use it in GitHub Desktop.
Save vkuznecovas/087fc18bef1a1b04b2e7d7863fae4868 to your computer and use it in GitHub Desktop.
GIN and GOTH OAuth example
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