46 lines
1021 B
Go
46 lines
1021 B
Go
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) {
|
|
switch r.Method {
|
|
case http.MethodPost:
|
|
var reqBody dto.ReqBody
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&reqBody)
|
|
if err != nil {
|
|
http.Error(w, "Error: ", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
shortUrl, err := repository.CrearUrl(reqBody.LongUrl, db)
|
|
if err != nil {
|
|
http.Error(w, "Error: "+err.Error(), http.StatusBadRequest)
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"shortUrl": shortUrl,
|
|
})
|
|
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)
|
|
return
|
|
}
|
|
http.Redirect(w, r, longUrl, http.StatusMovedPermanently)
|
|
|
|
default:
|
|
http.Error(w, "404", http.StatusBadGateway)
|
|
}
|
|
|
|
}
|