Skip to content

Commit

Permalink
Renaming
Browse files Browse the repository at this point in the history
  • Loading branch information
evg4b committed Jun 18, 2023
1 parent 6984183 commit 5261ce8
Show file tree
Hide file tree
Showing 20 changed files with 157 additions and 157 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,29 @@ import (
"github.com/spf13/afero"
)

type Middleware struct {
type Handler struct {
response config.Response
logger contracts.Logger
fs afero.Fs
after func(duration time.Duration) <-chan time.Time
}

func NewMockMiddleware(options ...MiddlewareOption) *Middleware {
middleware := &Middleware{}
func NewMockHandler(options ...HandlerOption) *Handler {
handler := &Handler{}

for _, option := range options {
option(middleware)
option(handler)
}

return middleware
return handler
}

func (m *Middleware) ServeHTTP(writer *contracts.ResponseWriter, request *contracts.Request) {
response := m.response
func (h *Handler) ServeHTTP(writer *contracts.ResponseWriter, request *contracts.Request) {
response := h.response
header := writer.Header()

if response.Delay > 0 {
m.logger.Debugf("Delay %s for %s", response.Delay, request.URL.RequestURI())
h.logger.Debugf("Delay %s for %s", response.Delay, request.URL.RequestURI())
ctx := request.Context()

url := request.URL.RequestURI()
Expand All @@ -41,11 +41,11 @@ func (m *Middleware) ServeHTTP(writer *contracts.ResponseWriter, request *contra
select {
case <-ctx.Done():
writer.WriteHeader(http.StatusServiceUnavailable)
m.logger.Debugf("Delay is canceled (url: %s)", url)
h.logger.Debugf("Delay is canceled (url: %s)", url)

return
case <-m.after(response.Delay):
m.logger.Debugf("Delay is complete (url: %s)", url)
case <-h.after(response.Delay):
h.logger.Debugf("Delay is complete (url: %s)", url)

break waitingLoop
}
Expand All @@ -57,18 +57,18 @@ func (m *Middleware) ServeHTTP(writer *contracts.ResponseWriter, request *contra
header.Set(key, value)
}

if len(m.response.File) > 0 {
err := m.serveFileContent(writer, request)
if len(h.response.File) > 0 {
err := h.serveFileContent(writer, request)
if err != nil {
infra.HTTPError(writer, err)

return
}
} else {
m.serveRawContent(writer)
h.serveRawContent(writer)
}

m.logger.PrintResponse(&http.Response{
h.logger.PrintResponse(&http.Response{
Request: request,
StatusCode: response.Code,
})
Expand Down
35 changes: 35 additions & 0 deletions internal/handler/mock/handler_options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package mock

import (
"time"

"github.com/evg4b/uncors/internal/config"
"github.com/evg4b/uncors/internal/contracts"
"github.com/spf13/afero"
)

type HandlerOption = func(*Handler)

func WithLogger(logger contracts.Logger) HandlerOption {
return func(h *Handler) {
h.logger = logger
}
}

func WithResponse(response config.Response) HandlerOption {
return func(h *Handler) {
h.response = response
}
}

func WithFileSystem(fs afero.Fs) HandlerOption {
return func(h *Handler) {
h.fs = fs
}
}

func WithAfter(after func(duration time.Duration) <-chan time.Time) HandlerOption {
return func(h *Handler) {
h.after = after
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func TestHandler(t *testing.T) {
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
handler := mock.NewMockMiddleware(
handler := mock.NewMockHandler(
mock.WithLogger(mocks.NewNoopLogger(t)),
mock.WithResponse(testCase.response),
mock.WithFileSystem(fileSystem),
Expand Down Expand Up @@ -132,7 +132,7 @@ func TestHandler(t *testing.T) {
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
handler := mock.NewMockMiddleware(
handler := mock.NewMockHandler(
mock.WithLogger(mocks.NewNoopLogger(t)),
mock.WithResponse(testCase.response),
mock.WithFileSystem(fileSystem),
Expand Down Expand Up @@ -221,7 +221,7 @@ func TestHandler(t *testing.T) {
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
handler := mock.NewMockMiddleware(
handler := mock.NewMockHandler(
mock.WithLogger(mocks.NewNoopLogger(t)),
mock.WithResponse(testCase.response),
mock.WithFileSystem(fileSystem),
Expand Down Expand Up @@ -269,7 +269,7 @@ func TestHandler(t *testing.T) {
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
handler := mock.NewMockMiddleware(
handler := mock.NewMockHandler(
mock.WithLogger(mocks.NewNoopLogger(t)),
mock.WithResponse(testCase.response),
mock.WithFileSystem(fileSystem),
Expand Down Expand Up @@ -341,7 +341,7 @@ func TestHandler(t *testing.T) {
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
called := false
handler := mock.NewMockMiddleware(
handler := mock.NewMockHandler(
mock.WithLogger(mocks.NewNoopLogger(t)),
mock.WithResponse(testCase.response),
mock.WithFileSystem(fileSystem),
Expand All @@ -364,7 +364,7 @@ func TestHandler(t *testing.T) {
})

t.Run("correctly cancel delay", func(t *testing.T) {
handler := mock.NewMockMiddleware(
handler := mock.NewMockHandler(
mock.WithLogger(mocks.NewNoopLogger(t)),
mock.WithResponse(config.Response{
Code: http.StatusOK,
Expand Down
35 changes: 0 additions & 35 deletions internal/handler/mock/middleware_options.go

This file was deleted.

6 changes: 3 additions & 3 deletions internal/handler/mock/serve_file_content.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"os"
)

func (m *Middleware) serveFileContent(writer http.ResponseWriter, request *http.Request) error {
fileName := m.response.File
file, err := m.fs.OpenFile(fileName, os.O_RDONLY, os.ModePerm)
func (h *Handler) serveFileContent(writer http.ResponseWriter, request *http.Request) error {
fileName := h.response.File
file, err := h.fs.OpenFile(fileName, os.O_RDONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("filed to opent file %s: %w", fileName, err)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/handler/mock/serve_raw_content.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
"github.com/go-http-utils/headers"
)

func (m *Middleware) serveRawContent(writer http.ResponseWriter) {
response := m.response
func (h *Handler) serveRawContent(writer http.ResponseWriter) {
response := h.response
header := writer.Header()
if len(header.Get(headers.ContentType)) == 0 {
contentType := http.DetectContentType([]byte(response.Raw))
Expand Down
6 changes: 3 additions & 3 deletions internal/handler/mocked_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"github.com/gorilla/mux"
)

func (m *RequestHandler) makeMockedRoutes(router *mux.Router, mocks config.Mocks) {
func (h *RequestHandler) makeMockedRoutes(router *mux.Router, mocks config.Mocks) {
var defaultMocks config.Mocks

for _, mockDef := range mocks {
Expand All @@ -15,7 +15,7 @@ func (m *RequestHandler) makeMockedRoutes(router *mux.Router, mocks config.Mocks
setMethod(route, mockDef.Method)
setQueries(route, mockDef.Queries)
setHeaders(route, mockDef.Headers)
route.Handler(m.createHandler(mockDef.Response))
route.Handler(h.createHandler(mockDef.Response))
} else {
defaultMocks = append(defaultMocks, mockDef)
}
Expand All @@ -24,6 +24,6 @@ func (m *RequestHandler) makeMockedRoutes(router *mux.Router, mocks config.Mocks
for _, mockDef := range defaultMocks {
route := router.NewRoute()
setPath(route, mockDef.Path)
route.Handler(m.createHandler(mockDef.Response))
route.Handler(h.createHandler(mockDef.Response))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,48 +31,48 @@ func NewProxyHandler(options ...HandlerOption) *Handler {
return middleware
}

func (m *Handler) ServeHTTP(response *contracts.ResponseWriter, request *contracts.Request) {
if err := m.handle(response, request); err != nil {
func (h *Handler) ServeHTTP(response *contracts.ResponseWriter, request *contracts.Request) {
if err := h.handle(response, request); err != nil {
infra.HTTPError(response, err)
}
}

func (m *Handler) handle(resp http.ResponseWriter, req *http.Request) error {
func (h *Handler) handle(resp http.ResponseWriter, req *http.Request) error {
if strings.EqualFold(req.Method, http.MethodOptions) {
return m.makeOptionsResponse(resp, req)
return h.makeOptionsResponse(resp, req)
}

targetReplacer, sourceReplacer, err := m.replacers.Make(req.URL)
targetReplacer, sourceReplacer, err := h.replacers.Make(req.URL)
if err != nil {
return fmt.Errorf("failed to transform general url: %w", err)
}

originalRequest, err := m.makeOriginalRequest(req, targetReplacer)
originalRequest, err := h.makeOriginalRequest(req, targetReplacer)
if err != nil {
return fmt.Errorf("failed to create reuest to original source: %w", err)
}

originalResponse, err := m.executeQuery(originalRequest)
originalResponse, err := h.executeQuery(originalRequest)
if err != nil {
return err
}

defer helpers.CloseSafe(originalResponse.Body)

err = m.makeUncorsResponse(originalResponse, resp, sourceReplacer)
err = h.makeUncorsResponse(originalResponse, resp, sourceReplacer)
if err != nil {
return fmt.Errorf("failed to make uncors response: %w", err)
}

return nil
}

func (m *Handler) executeQuery(request *http.Request) (*http.Response, error) {
originalResponse, err := m.http.Do(request)
func (h *Handler) executeQuery(request *http.Request) (*http.Response, error) {
originalResponse, err := h.http.Do(request)
if err != nil {
return nil, fmt.Errorf("failed to do reuest: %w", err)
}
m.logger.PrintResponse(originalResponse)
h.logger.PrintResponse(originalResponse)

return originalResponse, nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestProxyMiddleware(t *testing.T) {
func TestProxyHandler(t *testing.T) {
replacerFactory, err := urlreplacer.NewURLReplacerFactory(config.Mappings{
{From: "http://premium.local.com", To: "https://premium.api.com"},
})
Expand Down Expand Up @@ -66,7 +66,7 @@ func TestProxyMiddleware(t *testing.T) {
}
})

proc := proxy.NewProxyHandler(
handler := proxy.NewProxyHandler(
proxy.WithHTTPClient(httpClient),
proxy.WithURLReplacerFactory(replacerFactory),
proxy.WithLogger(mocks.NewNoopLogger(t)),
Expand All @@ -81,7 +81,7 @@ func TestProxyMiddleware(t *testing.T) {

req.Header.Add(testCase.headerKey, testCase.URL)

proc.ServeHTTP(contracts.WrapResponseWriter(httptest.NewRecorder()), req)
handler.ServeHTTP(contracts.WrapResponseWriter(httptest.NewRecorder()), req)
})
}
})
Expand Down Expand Up @@ -119,7 +119,7 @@ func TestProxyMiddleware(t *testing.T) {
}
})

proc := proxy.NewProxyHandler(
handler := proxy.NewProxyHandler(
proxy.WithHTTPClient(httpClient),
proxy.WithURLReplacerFactory(replacerFactory),
proxy.WithLogger(mocks.NewNoopLogger(t)),
Expand All @@ -134,7 +134,7 @@ func TestProxyMiddleware(t *testing.T) {

recorder := httptest.NewRecorder()

proc.ServeHTTP(contracts.WrapResponseWriter(recorder), req)
handler.ServeHTTP(contracts.WrapResponseWriter(recorder), req)

assert.Equal(t, testCase.expectedURL, recorder.Header().Get(testCase.headerKey))
})
Expand All @@ -153,7 +153,7 @@ func TestProxyMiddleware(t *testing.T) {
}
})

proc := proxy.NewProxyHandler(
handler := proxy.NewProxyHandler(
proxy.WithHTTPClient(httpClient),
proxy.WithURLReplacerFactory(replacerFactory),
proxy.WithLogger(mocks.NewNoopLogger(t)),
Expand All @@ -167,7 +167,7 @@ func TestProxyMiddleware(t *testing.T) {

recorder := httptest.NewRecorder()

proc.ServeHTTP(contracts.WrapResponseWriter(recorder), req)
handler.ServeHTTP(contracts.WrapResponseWriter(recorder), req)

header := recorder.Header()
assert.Equal(t, "*", header.Get(headers.AccessControlAllowOrigin))
Expand All @@ -180,7 +180,7 @@ func TestProxyMiddleware(t *testing.T) {
})

t.Run("OPTIONS request handling", func(t *testing.T) {
middleware := proxy.NewProxyHandler(
handler := proxy.NewProxyHandler(
proxy.WithHTTPClient(http.DefaultClient),
proxy.WithURLReplacerFactory(replacerFactory),
proxy.WithLogger(mocks.NewNoopLogger(t)),
Expand Down Expand Up @@ -241,7 +241,7 @@ func TestProxyMiddleware(t *testing.T) {
req, err := http.NewRequestWithContext(context.TODO(), http.MethodOptions, "/", nil)
testutils.CheckNoError(t, err)

middleware.ServeHTTP(contracts.WrapResponseWriter(recorder), req)
handler.ServeHTTP(contracts.WrapResponseWriter(recorder), req)

assert.Equal(t, http.StatusOK, recorder.Code)
assert.Equal(t, testCase.expected, recorder.Header())
Expand Down
Loading

0 comments on commit 5261ce8

Please sign in to comment.