This commit is contained in:
2026-03-16 20:40:33 -03:00
parent 0905005543
commit e33faa687d
2 changed files with 52 additions and 18 deletions

View File

@@ -0,0 +1,23 @@
package repository
import (
"strconv"
"url-short/models"
"gorm.io/gorm"
)
func RecuperarUrl(shortUrl string, db *gorm.DB) (string, error) {
var url models.Url
i, err := strconv.ParseInt(shortUrl, 10, 64);
if err != nil {
return "", err
}
result := db.Where(&models.Url{Shorturl: i}).First(&url)
if result.Error != nil {
return "", result.Error
}
return url.Longurl, nil
}

View File

@@ -3,13 +3,15 @@ package routes
import (
"encoding/json"
"net/http"
"strings"
"url-short/dto"
"url-short/repository"
"gorm.io/gorm"
)
func Url(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
if r.Method == http.MethodPost {
switch r.Method {
case http.MethodPost:
var reqBody dto.ReqBody
err := json.NewDecoder(r.Body).Decode(&reqBody)
@@ -26,8 +28,17 @@ func Url(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
json.NewEncoder(w).Encode(map[string]string{
"shortUrl": shortUrl,
})
}else{
http.Error(w, "404", http.StatusBadGateway);
case http.MethodGet:
var paths = strings.Split(r.URL.Path, "/")
longUrl, err := repository.RecuperarUrl(paths[len(paths)-1], db)
if err != nil {
http.Error(w, "Error: "+err.Error(), http.StatusBadRequest)
}
http.Redirect(w, r, longUrl, http.StatusPermanentRedirect)
default:
http.Error(w, "404", http.StatusBadGateway)
}
}