feat(links): create basic link shortening algo

This commit is contained in:
maotovisk 2025-08-06 23:16:55 -03:00
parent fc46164556
commit 81e72cedfa
9 changed files with 144 additions and 23 deletions

View file

@ -44,8 +44,37 @@ func (h *LinkHandler) ListLinks(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(linkList)
}
func (h *LinkHandler) CreateLink(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var linkRequest struct {
URL string `json:"url"`
RedirectCode *string `json:"redirect_code,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&linkRequest); err != nil {
http.Error(w, fmt.Sprintf("Failed to decode request body: %v", err), http.StatusBadRequest)
return
}
link, err := h.linkService.CreateLink(r.Context(), linkRequest.URL, linkRequest.RedirectCode)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to create link: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(link)
}
func (h *LinkHandler) GetUrl(w http.ResponseWriter, r *http.Request) {
currentCode := r.PathValue("id")
json.NewEncoder(w).Encode(&Response{Message: currentCode})
link, err := h.linkService.GetLink(r.Context(), currentCode)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to get link: %v", err), http.StatusInternalServerError)
return
}
http.Redirect(w, r, link.LongURL, http.StatusFound)
}