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

Iter7 #7

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
27 changes: 27 additions & 0 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package config

import (
"fmt"
"github.com/nabbat/23_kogorta_shotener/internal/envirements"
"github.com/nabbat/23_kogorta_shotener/internal/flags"
)

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

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

if en.ResultURL != "" && en.RunAddr != "http://" {
c.ResultURL = en.ResultURL
} else {
c.ResultURL = fl.ResultURL
}
fmt.Println(c)
return c
}
23 changes: 23 additions & 0 deletions cmd/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package config

import (
"github.com/nabbat/23_kogorta_shotener/internal/envirements"
"reflect"
"testing"
)

func TestSetEnv(t *testing.T) {
tests := []struct {
name string
want *envirements.EnvConfig
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SetEnv(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("SetEnv() = %v, want %v", got, tt.want)
}
})
}
}
43 changes: 42 additions & 1 deletion cmd/shortener/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,44 @@
package main

func main() {}
import (
"github.com/gorilla/mux"
"github.com/nabbat/23_kogorta_shotener/cmd/config"
"github.com/nabbat/23_kogorta_shotener/internal/handlers"
"github.com/nabbat/23_kogorta_shotener/internal/liblog"
urlstorage "github.com/nabbat/23_kogorta_shotener/internal/storage"
"net/http"
)

func main() {
// Инициализируем логер
log := liblog.NewLogger()

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

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

r := mux.NewRouter()

// Регистрируем middleware для логирования запросов
r.Use(handlers.RequestLoggingMiddleware(log))
// Регистрируем middleware для логирования ответов
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")

log.Info("RunAddr: ", c.RunAddr, " | ", "ResultURL: ", c.ResultURL)
log.Info("Running server on ", c.RunAddr)

err := http.ListenAndServe(c.RunAddr, r)
if err != nil {
panic(err)
}
}
17 changes: 17 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module github.com/nabbat/23_kogorta_shotener

go 1.20

require (
github.com/gorilla/mux v1.8.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.8.4
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
go.uber.org/zap v1.25.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
19 changes: 19 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c=
go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
3 changes: 0 additions & 3 deletions internal/app/README.md

This file was deleted.

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

import (
"os"
"strings"
)

type EnvConfig struct {
RunAddr string
ResultURL string
}

// ParseEnv Get system environments
func ParseEnv() *EnvConfig {
env := &EnvConfig{}
env.RunAddr = os.Getenv("RUN_ADDR")
env.ResultURL = os.Getenv("SERVER_ADDRESS")
// парсим переданные серверу аргументы в зарегистрированные переменные
if !strings.HasPrefix(env.ResultURL, "http://") && env.ResultURL != "" {
env.ResultURL = "http://" + env.ResultURL
}
return env
}
22 changes: 22 additions & 0 deletions internal/envirements/envirements_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package envirements

import (
"reflect"
"testing"
)

func TestParseEnv(t *testing.T) {
tests := []struct {
name string
want *EnvConfig
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ParseEnv(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("ParseEnv() = %v, want %v", got, tt.want)
}
})
}
}
27 changes: 27 additions & 0 deletions internal/flags/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package flags

import (
flag "github.com/spf13/pflag"
"strings"
)

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

// ParseFlags обрабатывает аргументы командной строки
// и сохраняет их значения в соответствующих переменных
func ParseFlags() *Flags {
// Create a Config instance
flg := &Flags{}
flag.StringVarP(&flg.RunAddr, "a", "a", "localhost:8080", "Адрес запуска HTTP-сервера.")
flag.StringVarP(&flg.ResultURL, "b", "b", "http://localhost:8080", "Адрес результирующего сокращённого URL.")
// парсим переданные серверу аргументы в зарегистрированные переменные
flag.Parse()
if !strings.HasPrefix(flg.ResultURL, "http://") {
flg.ResultURL = "http://" + flg.ResultURL
}
return flg
}
22 changes: 22 additions & 0 deletions internal/flags/flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package flags

import (
"reflect"
"testing"
)

func TestParseFlags(t *testing.T) {
tests := []struct {
name string
want *Flags
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ParseFlags(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("ParseFlags() = %v, want %v", got, tt.want)
}
})
}
}
Loading
Loading