diff --git a/main.go b/main.go index 7983ad9..ba4de3a 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "html/template" "math/rand" "net/http" + "strings" "time" ) @@ -87,13 +88,28 @@ func main() { r.GET("/:id", func(c *gin.Context) { var url models.Url + id := c.Param("id") - if err := models.DB.First(&url, "id = ?", c.Param("id")).Error; err != nil { + if strings.HasSuffix(c.Param("id"), "+") { + id = strings.TrimSuffix(c.Param("id"), "+") + } + + if err := models.DB.First(&url, "id = ?", id).Error; err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "Record not found!"}) return } - c.Redirect(http.StatusMovedPermanently, url.Url) + if strings.HasSuffix(c.Param("id"), "+") { + var count int64 + models.DB.Table("accesses").Where("url_id = ?", id).Count(&count) + c.JSON(http.StatusOK, gin.H{"count": count}) + return + } else { + access := models.Access{UrlID: url.ID, Date: time.Now()} + models.DB.Create(&access) + + c.Redirect(http.StatusMovedPermanently, url.Url) + } }) printAscii() r.Run() diff --git a/models/access.go b/models/access.go new file mode 100644 index 0000000..391dd2d --- /dev/null +++ b/models/access.go @@ -0,0 +1,8 @@ +package models + +import "time" + +type Access struct { + UrlID string + Date time.Time +} diff --git a/models/setup.go b/models/setup.go index 29fdeda..031c1ae 100644 --- a/models/setup.go +++ b/models/setup.go @@ -15,7 +15,7 @@ func ConnectDatabase() { panic("Failed to connect to database: " + err.Error()) } - database.AutoMigrate(&Url{}) + database.AutoMigrate(&Url{}, &Access{}) DB = database }