redirect
This commit is contained in:
23
repository/RecuperarUrl.go
Normal file
23
repository/RecuperarUrl.go
Normal 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
|
||||||
|
}
|
||||||
@@ -3,31 +3,42 @@ package routes
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"url-short/dto"
|
"url-short/dto"
|
||||||
"url-short/repository"
|
"url-short/repository"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
func Url(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
|
func Url(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
|
||||||
if r.Method == http.MethodPost {
|
switch r.Method {
|
||||||
var reqBody dto.ReqBody
|
case http.MethodPost:
|
||||||
|
var reqBody dto.ReqBody
|
||||||
|
|
||||||
err := json.NewDecoder(r.Body).Decode(&reqBody)
|
err := json.NewDecoder(r.Body).Decode(&reqBody)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Error: ", http.StatusBadRequest)
|
http.Error(w, "Error: ", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
shortUrl, err := repository.CrearUrl(reqBody.LongUrl, db)
|
shortUrl, err := repository.CrearUrl(reqBody.LongUrl, db)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Error: "+err.Error(), http.StatusBadRequest)
|
http.Error(w, "Error: "+err.Error(), http.StatusBadRequest)
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
json.NewEncoder(w).Encode(map[string]string{
|
json.NewEncoder(w).Encode(map[string]string{
|
||||||
"shortUrl": shortUrl,
|
"shortUrl": shortUrl,
|
||||||
})
|
})
|
||||||
}else{
|
case http.MethodGet:
|
||||||
http.Error(w, "404", http.StatusBadGateway);
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user