primer intento de servicio para acortar urls
This commit is contained in:
47
repository/CrearUrl.go
Normal file
47
repository/CrearUrl.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"crypto/sha3"
|
||||
"fmt"
|
||||
"url-short/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CrearUrl(longURL string, db *gorm.DB) (string, error) {
|
||||
// checkeamos por longurl repetida
|
||||
counturl := int64(0)
|
||||
result := db.Model(&models.Url{}).Where("longurl = ?", longURL).Count(&counturl)
|
||||
if result.Error != nil {
|
||||
return "", result.Error
|
||||
}
|
||||
if counturl != 0 {
|
||||
println(1)
|
||||
var short models.Url
|
||||
result = db.Model(&short).Where("longurl = ?", longURL).Select("shorturl").First(&short)
|
||||
if result.Error != nil {
|
||||
return "", result.Error
|
||||
}
|
||||
return short.Shorturl, nil
|
||||
}
|
||||
|
||||
// shortURL := base64.StdEncoding.EncodeToString([]byte(longURL))[:10]
|
||||
sha := sha3.New224()
|
||||
sha.Write([]byte(longURL))
|
||||
shortURL := fmt.Sprintf("%x", sha.Sum(nil))[:10]
|
||||
|
||||
result = db.Model(&models.Url{}).Where("shorturl = ?", shortURL).Count(&counturl)
|
||||
if result.Error != nil {
|
||||
return "", result.Error
|
||||
}
|
||||
if counturl != 0 {
|
||||
return shortURL, nil
|
||||
}
|
||||
|
||||
result = db.Create(&models.Url{Longurl: longURL, Shorturl: shortURL})
|
||||
|
||||
if result.Error != nil {
|
||||
return "", result.Error
|
||||
}
|
||||
return shortURL, nil
|
||||
}
|
||||
Reference in New Issue
Block a user