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

Code Refactoring #26

Merged
merged 13 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,12 @@ when utilizing it.
# Stargazers over time

[![Stargazers over time](https://starchart.cc/evg4b/uncors.svg?variant=adaptive)](https://starchart.cc/evg4b/uncors)

# Support project

<p align="center" dir="auto">
<br>
<a target="_blank" rel="noopener noreferrer" href="https://www.buymeacoffee.com/evg4b">
<img src="https://github.com/appcraftstudio/buymeacoffee/raw/master/Images/snapshot-bmc-button.png" width="200" style="max-width: 100%;">
</a>
</p>
27 changes: 14 additions & 13 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,26 @@ toolchain go1.21.1
require (
github.com/PuerkitoBio/purell v1.2.1
github.com/bmatcuk/doublestar/v4 v4.6.1
github.com/deckarep/golang-set/v2 v2.6.0
github.com/dustin/go-humanize v1.0.1
github.com/go-http-utils/headers v0.0.0-20181008091004-fed159eddc2a
github.com/gobuffalo/validate v2.0.4+incompatible
github.com/gojuno/minimock/v3 v3.1.3
github.com/gojuno/minimock/v3 v3.3.2
github.com/gorilla/mux v1.8.1
github.com/hashicorp/go-version v1.6.0
github.com/mitchellh/mapstructure v1.5.0
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5
github.com/pterm/pterm v0.12.71
github.com/samber/lo v1.38.1
github.com/spf13/afero v1.10.0
github.com/pterm/pterm v0.12.74
github.com/samber/lo v1.39.0
github.com/spf13/afero v1.11.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.17.0
github.com/spf13/viper v1.18.2
github.com/stretchr/testify v1.8.4
golang.org/x/net v0.18.0
golang.org/x/net v0.19.0
)

require (
github.com/deckarep/golang-set/v2 v2.5.0 // indirect
github.com/sagikazarmark/locafero v0.3.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
Expand All @@ -44,15 +45,15 @@ require (
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa // indirect
golang.org/x/sys v0.14.0 // indirect
golang.org/x/term v0.14.0 // indirect
golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/term v0.16.0 // indirect
golang.org/x/text v0.14.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
469 changes: 30 additions & 439 deletions go.sum

Large diffs are not rendered by default.

5 changes: 0 additions & 5 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@ import (
"github.com/spf13/viper"
)

const (
defaultHTTPPort = 80
defaultHTTPSPort = 443
)

var flags *pflag.FlagSet

type UncorsConfig struct {
Expand Down
2 changes: 2 additions & 0 deletions internal/config/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
)

const (
defaultHTTPPort = 80
defaultHTTPSPort = 443
DefaultExpirationTime = 30 * time.Minute
DefaultClearTime = 30 * time.Minute
)
Expand Down
43 changes: 43 additions & 0 deletions internal/config/mappings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,49 @@ func TestMappings(t *testing.T) {
"http://localhost => https://github.com",
},
},
{
name: "http and https mappings with statics",
mappings: config.Mappings{
{
From: hosts.Localhost.HTTP(),
To: hosts.Github.HTTPS(),
Statics: config.StaticDirectories{
{
Path: "/static",
Dir: "/tmp",
},
{
Path: "/static2",
Dir: "/tmp2",
Index: "index.html",
},
},
},
},
expected: []string{
"http://localhost => https://github.com",
" static: /static => /tmp",
" static: /static2 => /tmp2",
},
},
{
name: "http and https mappings with cache",
mappings: config.Mappings{
{
From: hosts.Localhost.HTTP(),
To: hosts.Github.HTTPS(),
Cache: config.CacheGlobs{
"/static",
"/static2",
},
},
},
expected: []string{
"http://localhost => https://github.com",
" cache: /static",
" cache: /static2",
},
},
{
name: "mapping and mocks",
mappings: config.Mappings{
Expand Down
6 changes: 1 addition & 5 deletions internal/handler/cache/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,7 @@ type Middleware struct {
}

func NewMiddleware(options ...MiddlewareOption) *Middleware {
middleware := &Middleware{}

for _, option := range options {
option(middleware)
}
middleware := helpers.ApplyOptions(&Middleware{}, options)

helpers.AssertIsDefined(middleware.logger, "Logger is not configured")
helpers.AssertIsDefined(middleware.storage, "Cache storage is not configured")
Expand Down
9 changes: 2 additions & 7 deletions internal/handler/mock/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/evg4b/uncors/internal/config"
"github.com/evg4b/uncors/internal/contracts"
"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/infra"
"github.com/spf13/afero"
)
Expand All @@ -18,13 +19,7 @@ type Handler struct {
}

func NewMockHandler(options ...HandlerOption) *Handler {
handler := &Handler{}

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

return handler
return helpers.ApplyOptions(&Handler{}, options)
}

func (h *Handler) ServeHTTP(writer contracts.ResponseWriter, request *contracts.Request) {
Expand Down
20 changes: 5 additions & 15 deletions internal/handler/proxy/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ type Handler struct {
}

func NewProxyHandler(options ...HandlerOption) *Handler {
middleware := &Handler{}

for _, option := range options {
option(middleware)
}
middleware := helpers.ApplyOptions(&Handler{}, options)

helpers.AssertIsDefined(middleware.replacers, "ProxyHandler: ReplacerFactory is not configured")
helpers.AssertIsDefined(middleware.logger, "ProxyHandler: Logger is not configured")
Expand Down Expand Up @@ -77,24 +73,18 @@ func (h *Handler) executeQuery(request *http.Request) (*http.Response, error) {
return originalResponse, nil
}

// nolint: unparam
func copyCookiesToSource(target *http.Response, replacer *urlreplacer.Replacer, source http.ResponseWriter) error {
func copyCookiesToSource(target *http.Response, replacer *urlreplacer.Replacer, source http.ResponseWriter) {
for _, cookie := range target.Cookies() {
cookie.Secure = replacer.IsTargetSecure()
// TODO: Replace domain in cookie
cookie.Domain = replacer.ReplaceSoft(cookie.Domain)
http.SetCookie(source, cookie)
}

return nil
}

// nolint: unparam
func copyCookiesToTarget(source *http.Request, replacer *urlreplacer.Replacer, target *http.Request) error {
func copyCookiesToTarget(source *http.Request, replacer *urlreplacer.Replacer, target *http.Request) {
for _, cookie := range source.Cookies() {
cookie.Secure = replacer.IsTargetSecure()
// TODO: Replace domain in cookie
cookie.Domain = replacer.ReplaceSoft(cookie.Domain)
target.AddCookie(cookie)
}

return nil
}
4 changes: 1 addition & 3 deletions internal/handler/proxy/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ func (h *Handler) makeOriginalRequest(
return nil, err
}

if err = copyCookiesToTarget(req, replacer, originalRequest); err != nil {
return nil, fmt.Errorf("failed to copy cookies in request: %w", err)
}
copyCookiesToTarget(req, replacer, originalRequest)

return originalRequest, nil
}
4 changes: 1 addition & 3 deletions internal/handler/proxy/responce.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ func (h *Handler) makeUncorsResponse(
target http.ResponseWriter,
replacer *urlreplacer.Replacer,
) error {
if err := copyCookiesToSource(original, replacer, target); err != nil {
return fmt.Errorf("failed to copy cookies in request: %w", err)
}
copyCookiesToSource(original, replacer, target)

modifications := modificationsMap{
headers.Location: func(s string) (string, error) { // nolint: unparam
Expand Down
14 changes: 4 additions & 10 deletions internal/handler/static/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ type Middleware struct {
prefix string
}

func NewStaticMiddleware(options ...MiddlewareOption) *Middleware {
return helpers.ApplyOptions(&Middleware{}, options)
}

func (h *Middleware) Wrap(next contracts.Handler) contracts.Handler {
return contracts.HandlerFunc(func(writer contracts.ResponseWriter, request *contracts.Request) {
response := contracts.WrapResponseWriter(writer)
Expand All @@ -42,16 +46,6 @@ func (h *Middleware) Wrap(next contracts.Handler) contracts.Handler {
})
}

func NewStaticMiddleware(options ...MiddlewareOption) *Middleware {
handler := &Middleware{}

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

return handler
}

func (h *Middleware) extractFilePath(request *http.Request) string {
filePath := strings.TrimPrefix(request.URL.Path, h.prefix)
if !strings.HasPrefix(filePath, "/") {
Expand Down
13 changes: 4 additions & 9 deletions internal/handler/uncors_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/evg4b/uncors/internal/contracts"
"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/infra"
"github.com/evg4b/uncors/internal/log"
"github.com/evg4b/uncors/pkg/urlx"
"github.com/gorilla/mux"
)
Expand All @@ -35,14 +36,7 @@ type RequestHandler struct {
var errHostNotMapped = errors.New("host not mapped")

func NewUncorsRequestHandler(options ...RequestHandlerOption) *RequestHandler {
handler := &RequestHandler{
Router: mux.NewRouter(),
mappings: config.Mappings{},
}

for _, option := range options {
option(handler)
}
handler := helpers.ApplyOptions(&RequestHandler{Router: mux.NewRouter(), mappings: config.Mappings{}}, options)

helpers.AssertIsDefined(handler.cacheMiddlewareFactory, "Cache middleware is not set")

Expand Down Expand Up @@ -73,8 +67,9 @@ func NewUncorsRequestHandler(options ...RequestHandlerOption) *RequestHandler {
setDefaultHandler(router, defaultHandler)
}

setDefaultHandler(handler.Router, contracts.HandlerFunc(func(writer contracts.ResponseWriter, _ *http.Request) {
setDefaultHandler(handler.Router, contracts.HandlerFunc(func(writer contracts.ResponseWriter, r *http.Request) {
infra.HTTPError(writer, errHostNotMapped)
log.Errorf("Host %s://%s is not mapped", r.URL.Scheme, r.URL.Host)
}))

return handler
Expand Down
9 changes: 9 additions & 0 deletions internal/helpers/structures.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package helpers

func ApplyOptions[T any](service *T, options []func(*T)) *T {
for _, option := range options {
option(service)
}

return service
}
39 changes: 39 additions & 0 deletions internal/helpers/structures_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package helpers_test

import (
"testing"

"github.com/evg4b/uncors/internal/helpers"
"github.com/stretchr/testify/assert"
)

type myService struct {
service string
}

func TestApplyOptions(t *testing.T) {
t.Run("ApplyOptions sets service value", func(t *testing.T) {
const testValue = "TestValue"

service := &myService{}
options := []func(*myService){
func(s *myService) {
s.service = testValue
},
}

result := helpers.ApplyOptions(service, options)

assert.Equal(t, service, result, "The same service should be returned")
assert.Equal(t, testValue, result.service, "Service option should be applied")
})

t.Run("ApplyOptions handles empty options", func(t *testing.T) {
service := &myService{}

result := helpers.ApplyOptions(service, nil)

assert.Equal(t, service, result, "The same service should be returned")
assert.Equal(t, "", result.service, "Service value should not be applied")
})
}
Loading