Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"html/template"
"math/rand"
"net/http"
"strings"
"time"
)

Expand Down Expand Up @@ -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()
Expand Down
8 changes: 8 additions & 0 deletions models/access.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package models

import "time"

type Access struct {
UrlID string
Date time.Time
}
2 changes: 1 addition & 1 deletion models/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func ConnectDatabase() {
panic("Failed to connect to database: " + err.Error())
}

database.AutoMigrate(&Url{})
database.AutoMigrate(&Url{}, &Access{})

DB = database
}