feat(links): create basic link shortening algo
This commit is contained in:
parent
fc46164556
commit
81e72cedfa
9 changed files with 144 additions and 23 deletions
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
46
internal/handlers/log_middleware.go
Normal file
46
internal/handlers/log_middleware.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (sr *statusRecorder) WriteHeader(code int) {
|
||||
sr.statusCode = code
|
||||
sr.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (sr *statusRecorder) Write(b []byte) (int, error) {
|
||||
if sr.statusCode == 0 {
|
||||
sr.statusCode = http.StatusOK
|
||||
}
|
||||
|
||||
return sr.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func LogMiddleware(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w}
|
||||
|
||||
h.ServeHTTP(rec, r)
|
||||
duration := time.Since(start)
|
||||
|
||||
statusCode := rec.statusCode
|
||||
|
||||
log.Printf("%s %s %s from %s - %d %s in %s\n",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
r.Proto,
|
||||
r.RemoteAddr,
|
||||
statusCode,
|
||||
http.StatusText(statusCode),
|
||||
duration.String())
|
||||
})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue