55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"log"
|
||
|
"net/http"
|
||
|
|
||
|
"github.com/foolin/goview/supports/ginview"
|
||
|
"github.com/gin-contrib/sessions"
|
||
|
"github.com/gin-contrib/sessions/cookie"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
db, err := connectDB()
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
defer db.Close()
|
||
|
|
||
|
r := gin.Default()
|
||
|
|
||
|
r.HTMLRender = ginview.Default()
|
||
|
|
||
|
store := cookie.NewStore([]byte("secret"))
|
||
|
r.Use(sessions.Sessions("mysession", store))
|
||
|
|
||
|
r.StaticFile("/favicon.ico", "./assets/favicon.ico")
|
||
|
|
||
|
r.GET("/", func(c *gin.Context) {
|
||
|
c.HTML(http.StatusOK, "index", gin.H{})
|
||
|
})
|
||
|
|
||
|
r.POST("/", func(c *gin.Context) {
|
||
|
shortUrl := getShortUrl(db, c.PostForm("url"))
|
||
|
if len(shortUrl) > 0 {
|
||
|
shortUrl = "https://" + c.Request.Host + "/" + shortUrl
|
||
|
}
|
||
|
c.HTML(http.StatusOK, "index", gin.H{
|
||
|
"shortUrl": shortUrl,
|
||
|
})
|
||
|
})
|
||
|
|
||
|
r.GET("/:short_url", func(c *gin.Context) {
|
||
|
redirectUrl := getRedirectUrl(db, c.Param("short_url"))
|
||
|
|
||
|
if len(redirectUrl) == 0 {
|
||
|
c.Redirect(http.StatusMovedPermanently, "/")
|
||
|
}
|
||
|
|
||
|
c.Redirect(http.StatusMovedPermanently, redirectUrl)
|
||
|
})
|
||
|
|
||
|
r.Run()
|
||
|
}
|