63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"log"
|
||
|
"net/http"
|
||
|
"strconv"
|
||
|
|
||
|
"git.0x0001f346.de/andreas/gin-oauth2-demo/core"
|
||
|
"git.0x0001f346.de/andreas/gin-oauth2-demo/middleware"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
)
|
||
|
|
||
|
const urlRoot string = "/"
|
||
|
const urlSecret string = "/secret"
|
||
|
const urlSecretWithNumber string = "/secret/:num"
|
||
|
|
||
|
func main() {
|
||
|
router := gin.Default()
|
||
|
router.Use(gin.Recovery())
|
||
|
|
||
|
router.ForwardedByClientIP = true
|
||
|
router.SetTrustedProxies([]string{"127.0.0.1"})
|
||
|
|
||
|
router.NoRoute(func(c *gin.Context) { c.Redirect(http.StatusSeeOther, "/") })
|
||
|
router.NoMethod(func(c *gin.Context) { c.Redirect(http.StatusSeeOther, "/") })
|
||
|
|
||
|
router.Use(middleware.Auth())
|
||
|
groupAuth := router.Group(middleware.URLPrefix)
|
||
|
middleware.SetupRoutes(groupAuth)
|
||
|
middleware.ProtectURL(urlSecret)
|
||
|
middleware.ProtectURL(urlSecretWithNumber)
|
||
|
|
||
|
router.GET(urlRoot, viewRoot)
|
||
|
router.GET(urlSecret, viewSecret)
|
||
|
router.GET(urlSecretWithNumber, viewSecretWithNumber)
|
||
|
|
||
|
log.Fatal(router.Run(":9000"))
|
||
|
}
|
||
|
|
||
|
func viewRoot(c *gin.Context) {
|
||
|
c.JSON(http.StatusOK, gin.H{
|
||
|
"user": c.MustGet("user").(core.User),
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func viewSecret(c *gin.Context) {
|
||
|
c.JSON(http.StatusOK, gin.H{
|
||
|
"secret text": "try to add a number to this URL",
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func viewSecretWithNumber(c *gin.Context) {
|
||
|
num, err := strconv.Atoi(c.Param("num"))
|
||
|
if err != nil {
|
||
|
c.Redirect(http.StatusSeeOther, urlSecret)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
c.JSON(http.StatusOK, gin.H{
|
||
|
"secret id": num,
|
||
|
})
|
||
|
}
|