Skip to content

Commit

Permalink
iter5 [BLOCKER] completed
Browse files Browse the repository at this point in the history
  • Loading branch information
ByteDSM committed Oct 11, 2023
1 parent 49684d6 commit 91dd87f
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 40 deletions.
18 changes: 6 additions & 12 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,19 @@ import (
"github.com/nabbat/23_kogorta_shotener/internal/flags"
)

// Config структура для хранения настроек
type Config struct {
RunAddr string
ResultURL string
}

func SetEnv() *Config {
func SetEnv() *envirements.EnvConfig {
fl := flags.ParseFlags()
en := envirements.ParseEnv()
c := &Config{}
c := &envirements.EnvConfig{}

if en.EnvRunAddr != "" {
c.RunAddr = en.EnvRunAddr
if en.RunAddr != "" {
c.RunAddr = en.RunAddr
} else {
c.RunAddr = fl.RunAddr
}

if en.EnvResultURL != "" && en.EnvRunAddr != "http://" {
c.ResultURL = en.EnvResultURL
if en.ResultURL != "" && en.RunAddr != "http://" {
c.ResultURL = en.ResultURL
} else {
c.ResultURL = fl.ResultURL
}
Expand Down
36 changes: 18 additions & 18 deletions cmd/shortener/main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package main

import (
"encoding/base64"
"fmt"
"github.com/gorilla/mux"
"github.com/nabbat/23_kogorta_shotener/cmd/config"
"github.com/nabbat/23_kogorta_shotener/internal/envirements"
"github.com/nabbat/23_kogorta_shotener/internal/handlers"
"github.com/nabbat/23_kogorta_shotener/internal/shotenermaker"
urlstorage "github.com/nabbat/23_kogorta_shotener/internal/storage"
"io"
"log"
"net/http"
Expand Down Expand Up @@ -37,7 +40,7 @@ func redirectHandler(w http.ResponseWriter, r *http.Request) {

}

func shortenURLHandler(w http.ResponseWriter, r *http.Request, c *config.Config) {
func shortenURLHandler(w http.ResponseWriter, r *http.Request, c *envirements.EnvConfig) {
// Читаем тело запроса (URL)
urlBytes, err := io.ReadAll(r.Body)
if err != nil {
Expand All @@ -49,7 +52,7 @@ func shortenURLHandler(w http.ResponseWriter, r *http.Request, c *config.Config)
url := string(urlBytes)

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

// Добавляем соответствие в словарь
urlMap[id] = url
Expand All @@ -63,25 +66,22 @@ func shortenURLHandler(w http.ResponseWriter, r *http.Request, c *config.Config)
}
}

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

func main() {
// Получаем переменные если они есть
c := config.SetEnv()

// Run server
// Создаем хранилище
storage := urlstorage.NewURLStorage()
// Создаем хэндлеры
redirectHandler := &handlers.RedirectHandler{}
shortenURLHandler := &handlers.ShortenURLHandler{}

r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
shortenURLHandler(w, r, c)
}).Methods("POST")
r.HandleFunc("/{idShortenURL}", redirectHandler).Methods("GET")
r.Use(handlers.PanicHandler) // Добавляем PanicHandler middleware

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

fmt.Println("RunAddr: ResultURL: ", c.RunAddr, c.ResultURL)
fmt.Println("Running server on", c.RunAddr)
err := http.ListenAndServe(c.RunAddr, r)
Expand Down
12 changes: 6 additions & 6 deletions internal/envirements/envirements.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ import (
)

type EnvConfig struct {
EnvRunAddr string
EnvResultURL string
RunAddr string
ResultURL string
}

// ParseEnv Get system environments
func ParseEnv() *EnvConfig {
env := &EnvConfig{}
env.EnvRunAddr = os.Getenv("RUN_ADDR")
env.EnvResultURL = os.Getenv("SERVER_ADDRESS")
env.RunAddr = os.Getenv("RUN_ADDR")
env.ResultURL = os.Getenv("SERVER_ADDRESS")
// парсим переданные серверу аргументы в зарегистрированные переменные
if !strings.HasPrefix(env.EnvResultURL, "http://") && env.EnvResultURL != "" {
env.EnvResultURL = "http://" + env.EnvResultURL
if !strings.HasPrefix(env.ResultURL, "http://") && env.ResultURL != "" {
env.ResultURL = "http://" + env.ResultURL
}
return env
}
6 changes: 3 additions & 3 deletions internal/handlers/urlhandlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package handlers
import (
"fmt"
"github.com/gorilla/mux"
"github.com/nabbat/23_kogorta_shotener/cmd/config"
"github.com/nabbat/23_kogorta_shotener/internal/envirements"
"github.com/nabbat/23_kogorta_shotener/internal/shotenermaker"
urlstorage "github.com/nabbat/23_kogorta_shotener/internal/storage"
"io"
Expand All @@ -16,7 +16,7 @@ type RedirectHandlerInterface interface {
}

type ShortenURLHandlerInterface interface {
HandleShortenURL(storage *urlstorage.URLStorage, c *config.Config) http.HandlerFunc
HandleShortenURL(storage *urlstorage.URLStorage, c *envirements.EnvConfig) http.HandlerFunc
}

type RedirectHandler struct{}
Expand Down Expand Up @@ -48,7 +48,7 @@ func (rh *RedirectHandler) HandleRedirect(storage *urlstorage.URLStorage) http.H

type ShortenURLHandler struct{}

func (sh *ShortenURLHandler) HandleShortenURL(storage *urlstorage.URLStorage, c *config.Config) http.HandlerFunc {
func (sh *ShortenURLHandler) HandleShortenURL(storage *urlstorage.URLStorage, c *envirements.EnvConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Читаем тело запроса (URL)
defer r.Body.Close()
Expand Down
1 change: 0 additions & 1 deletion internal/logger/logger.go

This file was deleted.

13 changes: 13 additions & 0 deletions internal/shoturlmaker/maker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package shoturlmaker

import "encoding/base64"

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

0 comments on commit 91dd87f

Please sign in to comment.