Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iter1 #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ vendor/
# IDEs directories
.idea
.vscode
.DS_Store
Binary file added cmd/.DS_Store
Binary file not shown.
84 changes: 83 additions & 1 deletion cmd/shortener/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,85 @@
package main

func main() {}
import (
"encoding/base64"
"fmt"
"io"
"log"
"net/http"
)

// Словарь для хранения соответствий между сокращёнными и оригинальными URL
var urlMap map[string]string

// Перенаправляем по полной ссылке
func redirectHandler(w http.ResponseWriter, r *http.Request) {
// Получаем идентификатор из URL-пути
id := r.URL.Path[1:]

// Получаем оригинальный URL из словаря
// TODO Создать хранилище

if originalURL, found := urlMap[id]; found {
// Устанавливаем заголовок Location и возвращаем ответ с кодом 307
w.Header().Set("Location", originalURL)
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
http.Error(w, "Ссылка не найдена", http.StatusBadRequest)

}

func shortenURLHandler(w http.ResponseWriter, r *http.Request) {
// Читаем тело запроса (URL)
urlBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Ошибка чтения запроса", http.StatusBadRequest)
return
}

// Преобразуем в строку
url := string(urlBytes)

// Генерируем уникальный идентификатор сокращённого URL
id := generateID(url)

// Добавляем соответствие в словарь
urlMap[id] = url

// Отправляем ответ с сокращённым URL
shortenedURL := fmt.Sprintf("http://localhost:8080/%s", id)
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusCreated)
if _, err := io.WriteString(w, shortenedURL); err != nil {
log.Fatal(err)
}
}

// Простая функция для генерации уникального идентификатора
func generateID(fullURL string) string {
encodedStr := base64.URLEncoding.EncodeToString([]byte(fullURL))
// Возвращаем первые 6 символов закодированной строки
if len(encodedStr) > 6 {
return encodedStr[:6]
}
return encodedStr
}

func main() {
mux := http.NewServeMux()
urlMap = make(map[string]string)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// GET OR POST
if r.Method != http.MethodPost {
redirectHandler(w, r)
return
}
shortenURLHandler(w, r)

})

err := http.ListenAndServe(":8080", mux)
if err != nil {
panic(err)
}
}
Binary file added cmd/shortener/shortenertest
Binary file not shown.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/nabbat/url-shortener-server.git

go 1.20
Binary file added internal/.DS_Store
Binary file not shown.
Loading