Skip to content

Commit

Permalink
iter7 completed
Browse files Browse the repository at this point in the history
  • Loading branch information
ByteDSM committed Oct 28, 2023
1 parent f51458c commit 399d05d
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 235 deletions.
1 change: 1 addition & 0 deletions cmd/shortener/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func main() {
r.Use(handlers.ResponseLoggingMiddleware(log))
r.Use(handlers.PanicHandler) // Добавляем PanicHandler middleware

r.HandleFunc("/api/shorten", shortenURLHandler.HandleShortenURLJSON(storage, c, log)).Methods("POST")
r.HandleFunc("/", shortenURLHandler.HandleShortenURL(storage, c, log)).Methods("POST")
r.HandleFunc("/{idShortenURL}", redirectHandler.HandleRedirect(storage, log)).Methods("GET")

Expand Down
42 changes: 42 additions & 0 deletions internal/handlers/urlhandlers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package handlers

import (
"bytes"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/nabbat/23_kogorta_shotener/internal/envirements"
Expand Down Expand Up @@ -135,3 +137,43 @@ func RequestLoggingMiddleware(log liblog.Logger) mux.MiddlewareFunc {
})
}
}

func (sh *ShortenURLHandler) HandleShortenURLJSON(storage *urlstorage.URLStorage, c *envirements.EnvConfig, log liblog.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Читаем JSON из тела запроса
type URLJSONRequest struct {
URL string `json:"url"`
}
var urlJSONRequest URLJSONRequest
var buf bytes.Buffer

// читаем тело запроса
_, err := buf.ReadFrom(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

// десериализуем JSON
if err = json.Unmarshal(buf.Bytes(), &urlJSONRequest); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

// Генерируем уникальный идентификатор сокращенного URL
shortURL := shotenermaker.GenerateID([]byte(urlJSONRequest.URL))

// Добавляем соответствие в словарь
storage.AddURL(shortURL, urlJSONRequest.URL)

// Формируем JSON-ответ с сокращенным URL
response := map[string]string{"result": c.ResultURL + "/" + shortURL}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Error("Ошибка записи JSON-ответа:", err)
http.Error(w, "Ошибка записи JSON-ответа", http.StatusInternalServerError)
}
}
}
235 changes: 0 additions & 235 deletions internal/handlers/urlhandlers_test.go

This file was deleted.

0 comments on commit 399d05d

Please sign in to comment.