From 31f783d8214c1f137d7d91914d02b9c52f07084d Mon Sep 17 00:00:00 2001 From: JulianSobott Date: Tue, 28 Jun 2022 22:04:22 +0200 Subject: [PATCH 1/2] feat: write access log --- main.go | 3 +++ models/access.go | 8 ++++++++ models/setup.go | 2 +- 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 models/access.go diff --git a/main.go b/main.go index 7983ad9..3feaae0 100644 --- a/main.go +++ b/main.go @@ -93,6 +93,9 @@ func main() { return } + access := models.Access{UrlID: url.ID, Date: time.Now()} + models.DB.Create(&access) + c.Redirect(http.StatusMovedPermanently, url.Url) }) printAscii() 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 } From e592f7e3c024a932da3b28b982acbc307178c190 Mon Sep 17 00:00:00 2001 From: JulianSobott Date: Tue, 28 Jun 2022 22:32:35 +0200 Subject: [PATCH 2/2] feat: return access count --- main.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 3feaae0..ba4de3a 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "html/template" "math/rand" "net/http" + "strings" "time" ) @@ -87,16 +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 } - access := models.Access{UrlID: url.ID, Date: time.Now()} - models.DB.Create(&access) + 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) + c.Redirect(http.StatusMovedPermanently, url.Url) + } }) printAscii() r.Run()