Instantly share code, notes, and snippets.

@vkuznecovas /main.go Secret
Created May 31, 2018

Embed
What would you like to do?
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