diff --git a/.gitignore b/.gitignore index 3362f51..46831dc 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,5 @@ vendor/ # IDEs directories .idea .vscode +cmd/.DS_Store +.DS_Store diff --git a/cmd/shortener/main.go b/cmd/shortener/main.go index 38dd16d..6125eac 100644 --- a/cmd/shortener/main.go +++ b/cmd/shortener/main.go @@ -1,3 +1,21 @@ package main -func main() {} +import ( + "github.com/shilin-anton/urlreducer/internal/app/config" + "github.com/shilin-anton/urlreducer/internal/app/server" + "github.com/shilin-anton/urlreducer/internal/app/storage" + "github.com/shilin-anton/urlreducer/internal/logger" + "log" +) + +func main() { + config.ParseConfig() + err := logger.Initialize(config.LogLevel) + if err != nil { + log.Fatal("Error initializing logger") + } + + myStorage := storage.New() + myServer := server.New(myStorage) + myServer.Start() +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..eded9b0 --- /dev/null +++ b/go.mod @@ -0,0 +1,18 @@ +module github.com/shilin-anton/urlreducer + +go 1.21.3 + +require ( + github.com/go-chi/chi/v5 v5.0.11 + github.com/stretchr/testify v1.8.1 + go.uber.org/zap v1.27.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/go-resty/resty/v2 v2.12.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/net v0.22.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1c5b0f4 --- /dev/null +++ b/go.sum @@ -0,0 +1,72 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +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/go-chi/chi/v5 v5.0.11 h1:BnpYbFZ3T3S1WMpD79r7R5ThWX40TaFB7L31Y8xqSwA= +github.com/go-chi/chi/v5 v5.0.11/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-resty/resty/v2 v2.12.0 h1:rsVL8P90LFvkUYq/V5BTVe203WfRIU4gvcf+yfzJzGA= +github.com/go-resty/resty/v2 v2.12.0/go.mod h1:o0yGPrkS3lOe1+eFajk6kBW8ScXzwU3hD69/gt2yB/0= +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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +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.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= +golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +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.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/config/config.go b/internal/app/config/config.go new file mode 100644 index 0000000..014f66a --- /dev/null +++ b/internal/app/config/config.go @@ -0,0 +1,31 @@ +package config + +import ( + "flag" + "os" +) + +var RunAddr string +var BaseAddr string +var LogLevel string + +const defaultRunURL = "localhost:8080" +const defaultBaseURL = "http://localhost:8080" +const defaultLogLevel = "info" + +func ParseConfig() { + flag.StringVar(&RunAddr, "a", defaultRunURL, "address and port to run server") + flag.StringVar(&BaseAddr, "b", defaultBaseURL, "base URL before short link") + flag.StringVar(&LogLevel, "l", defaultLogLevel, "log level") + flag.Parse() + + if envRunAddr := os.Getenv("SERVER_ADDRESS"); envRunAddr != "" { + RunAddr = envRunAddr + } + if envBaseAddr := os.Getenv("BASE_URL"); envBaseAddr != "" { + BaseAddr = envBaseAddr + } + if envLogLevel := os.Getenv("LOG_LEVEL"); envLogLevel != "" { + LogLevel = envLogLevel + } +} diff --git a/internal/app/handlers/handler.go b/internal/app/handlers/handler.go new file mode 100644 index 0000000..c0cf748 --- /dev/null +++ b/internal/app/handlers/handler.go @@ -0,0 +1,164 @@ +package handlers + +import ( + "bytes" + "crypto/md5" + "encoding/hex" + "encoding/json" + "github.com/go-chi/chi/v5" + "github.com/shilin-anton/urlreducer/internal/app/config" + "github.com/shilin-anton/urlreducer/internal/app/storage" + "github.com/shilin-anton/urlreducer/internal/logger" + "io" + "net/http" + "strconv" + "time" +) + +type Storage interface { + Add(short string, url string) + Get(short string) (string, bool) +} + +type Server struct { + data Storage + handler http.Handler +} + +// types for logger +type responseData struct { + status int + size int +} + +type shortenRequest struct { + URL string `json:"url"` +} + +type shortenResponse struct { + Result string `json:"result"` +} + +type loggingResponseWriter struct { + http.ResponseWriter + responseData *responseData +} + +func (lrw *loggingResponseWriter) WriteHeader(code int) { + lrw.responseData.status = code + lrw.ResponseWriter.WriteHeader(code) +} + +func (lrw *loggingResponseWriter) Write(data []byte) (int, error) { + size, err := lrw.ResponseWriter.Write(data) + lrw.responseData.size += size + return size, err +} + +func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + s.handler.ServeHTTP(w, r) +} + +func New() *Server { + r := chi.NewRouter() + + r.Use(requestLoggerMiddleware) + r.Use(responseLoggerMiddleware) + + s := &Server{ + data: make(storage.Storage), + handler: r, + } + r.Get("/{short}", s.GetHandler) + r.Post("/", s.PostHandler) + r.Post("/api/shorten", s.PostShortenHandler) + + return s +} + +func shortenURL(url string) string { + // Решил использовать хэширование и первые символы результата, как короткую форму URL + hash := md5.Sum([]byte(url)) + hashString := hex.EncodeToString(hash[:]) + shortURL := hashString[:8] + return shortURL +} + +func (s Server) PostHandler(res http.ResponseWriter, req *http.Request) { + body, err := io.ReadAll(req.Body) + if err != nil { + http.Error(res, "Error reading request body", http.StatusInternalServerError) + return + } + defer req.Body.Close() + + url := string(body) + short := shortenURL(url) + + s.data.Add(short, url) + + res.Header().Set("Content-Type", "text/plain") + res.WriteHeader(http.StatusCreated) + res.Write([]byte(config.BaseAddr + "/" + short)) +} + +func (s Server) GetHandler(res http.ResponseWriter, req *http.Request) { + short := chi.URLParam(req, "short") + + url, ok := s.data.Get(short) + if !ok { + http.NotFound(res, req) + return + } + res.Header().Set("Location", url) + res.WriteHeader(http.StatusTemporaryRedirect) +} + +func (s Server) PostShortenHandler(res http.ResponseWriter, req *http.Request) { + var request shortenRequest + var buf bytes.Buffer + _, err := buf.ReadFrom(req.Body) + if err != nil { + http.Error(res, err.Error(), http.StatusInternalServerError) + return + } + if err = json.Unmarshal(buf.Bytes(), &request); err != nil { + http.Error(res, err.Error(), http.StatusBadRequest) + return + } + if request.URL == "" { + http.Error(res, "url must be passed", http.StatusUnprocessableEntity) + return + } + + short := shortenURL(request.URL) + s.data.Add(short, request.URL) + + res.Header().Set("Content-Type", "application/json") + res.WriteHeader(http.StatusCreated) + response := shortenResponse{ + Result: config.BaseAddr + "/" + short, + } + + enc := json.NewEncoder(res) + if err = enc.Encode(response); err != nil { + http.Error(res, err.Error(), http.StatusInternalServerError) + return + } +} + +func requestLoggerMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + logger.RequestLogger(r.RequestURI, r.Method, time.Since(start).String()) + next.ServeHTTP(w, r) + }) +} + +func responseLoggerMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + lrw := &loggingResponseWriter{ResponseWriter: w, responseData: &responseData{}} + next.ServeHTTP(lrw, r) + logger.ResponseLogger(strconv.Itoa(lrw.responseData.status), strconv.Itoa(lrw.responseData.size)) + }) +} diff --git a/internal/app/handlers/handler_test.go b/internal/app/handlers/handler_test.go new file mode 100644 index 0000000..40d4950 --- /dev/null +++ b/internal/app/handlers/handler_test.go @@ -0,0 +1,159 @@ +package handlers + +import ( + "github.com/shilin-anton/urlreducer/internal/app/config" + "github.com/stretchr/testify/assert" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestPostHandler(t *testing.T) { + srv := New() + + tests := []struct { + name string + method string + url string + requestBody string + wantStatusCode int + }{ + { + name: "Valid POST request", + method: http.MethodPost, + url: "/", + requestBody: "http://example.com", + wantStatusCode: http.StatusCreated, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + req := httptest.NewRequest(test.method, test.url, strings.NewReader(test.requestBody)) + w := httptest.NewRecorder() + + srv.handler.ServeHTTP(w, req) + + resp := w.Result() + defer resp.Body.Close() + + if resp.StatusCode != test.wantStatusCode { + t.Errorf("unexpected status code: got %d, want %d", resp.StatusCode, test.wantStatusCode) + } + }) + } +} + +func TestGetHandler(t *testing.T) { + srv := New() + srv.data.Add("test_short", "https://smth.ru") + + tests := []struct { + name string + method string + url string + wantStatusCode int + wantLocationHeader string + }{ + { + name: "Valid GET request with existing short link", + method: http.MethodGet, + url: "/test_short", + wantStatusCode: http.StatusTemporaryRedirect, + wantLocationHeader: "https://smth.ru", + }, + { + name: "Invalid GET request with non-existing short link", + method: http.MethodGet, + url: "/non_existing_short_link", + wantStatusCode: http.StatusNotFound, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + req := httptest.NewRequest(test.method, test.url, nil) + w := httptest.NewRecorder() + + srv.handler.ServeHTTP(w, req) + + resp := w.Result() + defer resp.Body.Close() + + if resp.StatusCode != test.wantStatusCode { + t.Errorf("unexpected status code: got %d, want %d", resp.StatusCode, test.wantStatusCode) + } + + if test.wantLocationHeader != "" { + location := resp.Header.Get("Location") + if location != test.wantLocationHeader { + t.Errorf("unexpected Location header: got %s, want %s", location, test.wantLocationHeader) + } + } + }) + } +} + +func TestServer_PostShortenHandler(t *testing.T) { + srv := New() + config.BaseAddr = "http://localhost:8080" + + testCases := []struct { + name string + method string + body string + expectedCode int + expectedBody string + }{ + { + name: "method_post_without_body", + method: http.MethodPost, + expectedCode: http.StatusBadRequest, + expectedBody: "", + }, + { + name: "method_post_unsupported_type", + method: http.MethodPost, + body: `{"url": ""}`, + expectedCode: http.StatusUnprocessableEntity, + expectedBody: "", + }, + { + name: "method_post_success", + method: http.MethodPost, + body: `{"url": "https://yandex.ru"}`, + expectedCode: http.StatusCreated, + expectedBody: `{"result": "http://localhost:8080/e9db20b2"}`, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequest(tc.method, "/api/shorten", strings.NewReader(tc.body)) + w := httptest.NewRecorder() + + if len(tc.body) > 0 { + req.Header.Set("Content-Type", "application/json") + } + + srv.handler.ServeHTTP(w, req) + + resp := w.Result() + defer resp.Body.Close() + + if resp.StatusCode != tc.expectedCode { + t.Errorf("unexpected status code: got %d, want %d", resp.StatusCode, tc.expectedCode) + } + if tc.expectedBody != "" { + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("failed to read response body: %v", err) + } + bodyString := string(body) + assert.JSONEq(t, tc.expectedBody, bodyString) + } + }) + } +} diff --git a/internal/app/server/server.go b/internal/app/server/server.go new file mode 100644 index 0000000..bd476cb --- /dev/null +++ b/internal/app/server/server.go @@ -0,0 +1,31 @@ +package server + +import ( + "github.com/shilin-anton/urlreducer/internal/app/config" + "github.com/shilin-anton/urlreducer/internal/app/handlers" + "log" + "net/http" +) + +type Storage interface { + Add(short string, url string) + Get(short string) (string, bool) +} + +type server struct { + handler http.Handler + storage Storage +} + +func New(storage Storage) *server { + handler := handlers.New() + S := &server{ + handler: handler, + storage: storage, + } + return S +} + +func (s server) Start() { + log.Fatal(http.ListenAndServe(config.RunAddr, s.handler)) +} diff --git a/internal/app/storage/storage.go b/internal/app/storage/storage.go new file mode 100644 index 0000000..7490c1f --- /dev/null +++ b/internal/app/storage/storage.go @@ -0,0 +1,17 @@ +package storage + +type Storage map[string]string + +func (s Storage) Add(short string, url string) { + s[short] = url +} + +func (s Storage) Get(short string) (string, bool) { + url, ok := s[short] + return url, ok +} + +func New() Storage { + storage := make(map[string]string) + return storage +} diff --git a/internal/logger/logger.go b/internal/logger/logger.go new file mode 100644 index 0000000..8774af5 --- /dev/null +++ b/internal/logger/logger.go @@ -0,0 +1,60 @@ +package logger + +import ( + "go.uber.org/zap" + "net/http" +) + +// Log синглтон. +var Log *zap.Logger = zap.NewNop() + +type ( + // Структура для хранения сведений об ответе + responseData struct { + status int + size int + } + + // добавляем реализацию http.ResponseWriter + loggingResponseWriter struct { + http.ResponseWriter // встраиваем оригинальный http.ResponseWriter + responseData *responseData + } +) + +// Initialize инициализирует логер. +func Initialize(level string) error { + // преобразуем текстовый уровень логирования в zap.AtomicLevel + lvl, err := zap.ParseAtomicLevel(level) + if err != nil { + return err + } + // создаём новую конфигурацию логера + cfg := zap.NewProductionConfig() + // устанавливаем уровень + cfg.Level = lvl + // создаём логер на основе конфигурации + zl, err := cfg.Build() + if err != nil { + return err + } + // устанавливаем синглтон + Log = zl + return nil +} + +func RequestLogger(uri string, method string, duration string) { + Log.Info("got incoming HTTP request", + zap.String("URI", uri), + zap.String("method", method), + zap.String("duration", duration), + ) +} + +// ResponseLogger — middleware-логер для HTTP-ответов. +func ResponseLogger(status string, size string) { + Log.Info("HTTP response has been sent", + zap.String("code", status), + zap.String("size", size), + ) +}