Skip to content

Commit

Permalink
Refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
evg4b committed Jun 1, 2023
1 parent 8f0de5e commit d4cda47
Show file tree
Hide file tree
Showing 28 changed files with 116 additions and 107 deletions.
5 changes: 1 addition & 4 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
run:
skip-dirs:
- testing
- dist
linters:
enable-all: true
disable:
Expand Down Expand Up @@ -37,6 +33,7 @@ linters-settings:
- to
- ok
- fs
- ca
presets:
- bugs
- comment
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ docker run -p 80:3000 evg4b/uncors --from 'http://local.github.com' --to 'https:

## Stew (Cross-platform)

Also you can install binaris using [Stew](https://github.com/marwanhawari/) with the following commands:
Also, you can install binaris using [Stew](https://github.com/marwanhawari/) with the following commands:

```bash
stew install evg4b/uncors
Expand Down
6 changes: 2 additions & 4 deletions internal/config/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,16 @@ func readURLMapping(config *viper.Viper, configuration *UncorsConfig) error {
}

for index, key := range from {
value := to[index]
prev, ok := lo.Find(configuration.Mappings, func(item Mapping) bool {
return strings.EqualFold(item.From, key)
})

if ok {
// log.Warningf("Mapping for %s from (%s) replaced new value (%s)", key, prev, value)
prev.To = value
prev.To = to[index]
} else {
configuration.Mappings = append(configuration.Mappings, Mapping{
From: key,
To: value,
To: to[index],
})
}
}
Expand Down
13 changes: 5 additions & 8 deletions internal/config/hooks/time_decode_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ import (

func StringToTimeDurationHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data any) (any, error) {
if f.Kind() != reflect.String {
if f.Kind() != reflect.String || t != reflect.TypeOf(time.Second) {
return data, nil
}

if t != reflect.TypeOf(time.Second) {
return data, nil
}

trimmed := strings.ReplaceAll(data.(string), " ", "") //nolint: forcetypeassert

return time.ParseDuration(trimmed) //nolint:wrapcheck
//nolint:wrapcheck
return time.ParseDuration(
strings.ReplaceAll(data.(string), " ", ""), //nolint: forcetypeassert
)
}
}
28 changes: 9 additions & 19 deletions internal/config/mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,18 @@ import (
)

type Mapping struct {
From string `mapstructure:"from"`
To string `mapstructure:"to"`
Statics StaticDirs `mapstructure:"statics"`
Mocks []Mock `mapstructure:"mocks"`
From string `mapstructure:"from"`
To string `mapstructure:"to"`
Statics StaticDirectories `mapstructure:"statics"`
Mocks Mocks `mapstructure:"mocks"`
}

func (u Mapping) Clone() Mapping {
func (u *Mapping) Clone() Mapping {
return Mapping{
From: u.From,
To: u.To,
Statics: lo.If(u.Statics == nil, StaticDirs(nil)).
ElseF(func() StaticDirs {
return lo.Map(u.Statics, func(item StaticDir, index int) StaticDir {
return item.Clone()
})
}),
Mocks: lo.If(u.Mocks == nil, []Mock(nil)).
ElseF(func() []Mock {
return lo.Map(u.Mocks, func(item Mock, index int) Mock {
return item.Clone()
})
}),
From: u.From,
To: u.To,
Statics: u.Statics.Clone(),
Mocks: u.Mocks.Clone(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/config/mapping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func TestURLMappingClone(t *testing.T) {
expected: config.Mapping{
From: localhost,
To: localhostSecure,
Statics: []config.StaticDir{
Statics: []config.StaticDirectory{
{Path: "/cc", Dir: "cc"},
},
},
Expand Down
17 changes: 15 additions & 2 deletions internal/config/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"time"

"github.com/evg4b/uncors/internal/helpers"
"github.com/samber/lo"
)

type Response struct {
Expand All @@ -14,7 +15,7 @@ type Response struct {
Delay time.Duration `mapstructure:"delay"`
}

func (r Response) Clone() Response {
func (r *Response) Clone() Response {
return Response{
Code: r.Code,
Headers: helpers.CloneMap(r.Headers),
Expand All @@ -32,7 +33,7 @@ type Mock struct {
Response Response `mapstructure:"response"`
}

func (m Mock) Clone() Mock {
func (m *Mock) Clone() Mock {
return Mock{
Path: m.Path,
Method: m.Method,
Expand All @@ -41,3 +42,15 @@ func (m Mock) Clone() Mock {
Response: m.Response.Clone(),
}
}

type Mocks []Mock

func (m Mocks) Clone() Mocks {
if m == nil {
return nil
}

return lo.Map(m, func(item Mock, index int) Mock {
return item.Clone()
})
}
29 changes: 20 additions & 9 deletions internal/config/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,36 @@ import (
"reflect"

"github.com/mitchellh/mapstructure"
"github.com/samber/lo"
)

type StaticDirs = []StaticDir

type StaticDir struct {
type StaticDirectory struct {
Path string `mapstructure:"path"`
Dir string `mapstructure:"dir"`
Index string `mapstructure:"index"`
}

func (s StaticDir) Clone() StaticDir {
return StaticDir{
func (s *StaticDirectory) Clone() StaticDirectory {
return StaticDirectory{
Path: s.Path,
Dir: s.Dir,
Index: s.Index,
}
}

var staticDirMappingsType = reflect.TypeOf(StaticDirs{})
type StaticDirectories []StaticDirectory

func (d StaticDirectories) Clone() StaticDirectories {
if d == nil {
return nil
}

return lo.Map(d, func(item StaticDirectory, index int) StaticDirectory {
return item.Clone()
})
}

var staticDirMappingsType = reflect.TypeOf(StaticDirectories{})

func StaticDirMappingHookFunc() mapstructure.DecodeHookFunc { //nolint: ireturn
return func(f reflect.Type, t reflect.Type, rawData any) (any, error) {
Expand All @@ -35,18 +46,18 @@ func StaticDirMappingHookFunc() mapstructure.DecodeHookFunc { //nolint: ireturn
return rawData, nil
}

var mappings StaticDirs
var mappings StaticDirectories
for path, mappingDef := range mappingsDefs {
if def, ok := mappingDef.(string); ok {
mappings = append(mappings, StaticDir{
mappings = append(mappings, StaticDirectory{
Path: path,
Dir: def,
})

continue
}

mapping := StaticDir{}
mapping := StaticDirectory{}
err := decodeConfig(mappingDef, &mapping)
if err != nil {
return nil, err
Expand Down
22 changes: 11 additions & 11 deletions internal/config/static_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ const (
func TestStaticDirMappingHookFunc(t *testing.T) {
const configFile = "config.yaml"
type testType struct {
Statics config.StaticDirs `mapstructure:"statics"`
Statics config.StaticDirectories `mapstructure:"statics"`
}

tests := []struct {
name string
config string
expected config.StaticDirs
expected config.StaticDirectories
}{
{
name: "decode plan mapping",
Expand All @@ -34,7 +34,7 @@ statics:
/path: /static-dir
/another-path: /another-static-dir
`,
expected: config.StaticDirs{
expected: config.StaticDirectories{
{Path: anotherPath, Dir: anotherStaticDir},
{Path: path, Dir: staticDir},
},
Expand All @@ -46,7 +46,7 @@ statics:
/path: { dir: /static-dir }
/another-path: { dir: /another-static-dir }
`,
expected: config.StaticDirs{
expected: config.StaticDirectories{
{Path: path, Dir: staticDir},
{Path: anotherPath, Dir: anotherStaticDir},
},
Expand All @@ -58,7 +58,7 @@ statics:
/path: { dir: /static-dir, index: index.html }
/another-path: { dir: /another-static-dir, index: default.html }
`,
expected: config.StaticDirs{
expected: config.StaticDirectories{
{Path: path, Dir: staticDir, Index: "index.html"},
{Path: anotherPath, Dir: anotherStaticDir, Index: "default.html"},
},
Expand All @@ -70,7 +70,7 @@ statics:
/path: { dir: /static-dir, index: index.html }
/another-path: /another-static-dir
`,
expected: config.StaticDirs{
expected: config.StaticDirectories{
{Path: path, Dir: staticDir, Index: "index.html"},
{Path: anotherPath, Dir: anotherStaticDir},
},
Expand Down Expand Up @@ -101,28 +101,28 @@ statics:
func TestStaticDirMappingClone(t *testing.T) {
tests := []struct {
name string
expected config.StaticDir
expected config.StaticDirectory
}{
{
name: "empty structure",
expected: config.StaticDir{},
expected: config.StaticDirectory{},
},
{
name: "structure with 1 field",
expected: config.StaticDir{
expected: config.StaticDirectory{
Dir: "dir",
},
},
{
name: "structure with 2 field",
expected: config.StaticDir{
expected: config.StaticDirectory{
Dir: "dir",
Path: "/some-path",
},
},
{
name: "structure with all field",
expected: config.StaticDir{
expected: config.StaticDirectory{
Dir: "dir",
Path: "/one-more-path",
Index: "index.html",
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/static_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/spf13/afero"
)

func (m *RequestHandler) makeStaticRoutes(router *mux.Router, statics config.StaticDirs, next http.Handler) {
func (m *RequestHandler) makeStaticRoutes(router *mux.Router, statics config.StaticDirectories, next http.Handler) {
for _, staticDir := range statics {
clearPath := strings.TrimSuffix(staticDir.Path, "/")
path := clearPath + "/"
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/uncors_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func TestUncorsRequestHandler(t *testing.T) {
{
From: localhost,
To: localhostSecure,
Statics: []config.StaticDir{
Statics: []config.StaticDirectory{
{Dir: "/assets", Path: "/cc/", Index: indexHTML},
{Dir: "/assets", Path: "/pnp/", Index: "index.php"},
{Dir: "/images", Path: "/img/"},
Expand Down
2 changes: 2 additions & 0 deletions internal/helpers/clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ func CloneMap[K comparable, V any](data map[K]V) map[K]V {
for key, value := range data {
if cloneable, ok := any(value).(lo.Clonable[V]); ok {
cloned[key] = cloneable.Clone()
} else if cloneablePtr, ok := any(&value).(lo.Clonable[V]); ok { //nolint:gosec
cloned[key] = cloneablePtr.Clone()
} else {
cloned[key] = value
}
Expand Down
2 changes: 1 addition & 1 deletion internal/helpers/clone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

type clonableTestStruct struct{ Value string }

func (t clonableTestStruct) Clone() clonableTestStruct {
func (t *clonableTestStruct) Clone() clonableTestStruct {
return clonableTestStruct{Value: "Cloned:" + t.Value}
}

Expand Down
3 changes: 3 additions & 0 deletions internal/infra/cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/evg4b/uncors/internal/infra"
"github.com/evg4b/uncors/testing/mocks"
"github.com/go-http-utils/headers"
"github.com/stretchr/testify/assert"
)

func TestWriteCorsHeaders(t *testing.T) {
Expand Down Expand Up @@ -59,6 +60,8 @@ func TestWriteCorsHeaders(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
infra.WriteCorsHeaders(tt.header)

assert.Equal(t, tt.expected, tt.header)
})
}
}
14 changes: 4 additions & 10 deletions internal/infra/http_error.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package infra

import (
"io"
"net/http"

"github.com/evg4b/uncors/internal/sfmt"
"github.com/go-http-utils/headers"
"github.com/pterm/pterm"
"github.com/pterm/pterm/putils"
"github.com/samber/lo"
)

var style = pterm.Style{}
Expand All @@ -21,10 +19,10 @@ func HTTPError(writer http.ResponseWriter, err error) {
writer.WriteHeader(http.StatusInternalServerError)
message := sfmt.Sprintf("%d Error", http.StatusInternalServerError)

writeLine(writer)
writeLine(writer, pageHeader(message))
writeLine(writer)
writeLine(writer, sfmt.Sprintf("Occurred error: %s", err))
sfmt.Fprintln(writer)
sfmt.Fprintln(writer, pageHeader(message))
sfmt.Fprintln(writer)
sfmt.Fprintln(writer, sfmt.Sprintf("Occurred error: %s", err))
}

func pageHeader(message string) string {
Expand All @@ -36,7 +34,3 @@ func pageHeader(message string) string {

return text
}

func writeLine(writer io.Writer, data ...string) {
sfmt.Fprintln(writer, lo.ToAnySlice(data)...)
}
Loading

0 comments on commit d4cda47

Please sign in to comment.