diff --git a/cmd/config/config.go b/cmd/config/config.go index 3dcaa83..5736a65 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -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 } diff --git a/cmd/shortener/main.go b/cmd/shortener/main.go index 13d0fc2..03254e9 100644 --- a/cmd/shortener/main.go +++ b/cmd/shortener/main.go @@ -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" @@ -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 { @@ -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 @@ -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) diff --git a/internal/envirements/envirements.go b/internal/envirements/envirements.go index 5628199..5bd2e52 100644 --- a/internal/envirements/envirements.go +++ b/internal/envirements/envirements.go @@ -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 } diff --git a/internal/handlers/urlhandlers.go b/internal/handlers/urlhandlers.go index 01653b6..192da38 100644 --- a/internal/handlers/urlhandlers.go +++ b/internal/handlers/urlhandlers.go @@ -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" @@ -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{} @@ -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() diff --git a/internal/logger/logger.go b/internal/logger/logger.go deleted file mode 100644 index 90c66f6..0000000 --- a/internal/logger/logger.go +++ /dev/null @@ -1 +0,0 @@ -package logger diff --git a/internal/shoturlmaker/maker.go b/internal/shoturlmaker/maker.go new file mode 100644 index 0000000..9b9fce7 --- /dev/null +++ b/internal/shoturlmaker/maker.go @@ -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 +}