Skip to content

Commit

Permalink
Added panics for high level structures
Browse files Browse the repository at this point in the history
  • Loading branch information
evg4b committed Nov 21, 2023
1 parent db08d33 commit 5b07b9f
Show file tree
Hide file tree
Showing 14 changed files with 78 additions and 101 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ require (
github.com/subosito/gotenv v1.4.2 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 // indirect
golang.org/x/exp v0.0.0-20230728194245-b0cb94b80691 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/term v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 h1:Di6/M8l0O2lCLc6VVRWhgCiApHV8MnQurBnFSHsQtNY=
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
golang.org/x/exp v0.0.0-20230728194245-b0cb94b80691 h1:/yRP+0AN7mf5DkD3BAI6TOFnd51gEoDEb8o35jIFtgw=
golang.org/x/exp v0.0.0-20230728194245-b0cb94b80691/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand Down
14 changes: 7 additions & 7 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ func (c *UncorsConfig) IsHTTPSEnabled() bool {
return len(c.CertFile) > 0 && len(c.KeyFile) > 0 && c.HTTPSPort > 0
}

func LoadConfiguration(viperInstance *viper.Viper, args []string) (*UncorsConfig, error) {
func LoadConfiguration(viperInstance *viper.Viper, args []string) *UncorsConfig {
flags := defineFlags()
if err := flags.Parse(args); err != nil {
return nil, fmt.Errorf("filed parsing flags: %w", err)
panic(fmt.Errorf("filed parsing flags: %w", err))
}

if err := viperInstance.BindPFlags(flags); err != nil {
return nil, fmt.Errorf("filed binding flags: %w", err)
panic(fmt.Errorf("filed binding flags: %w", err))
}

configuration := &UncorsConfig{
Expand All @@ -45,7 +45,7 @@ func LoadConfiguration(viperInstance *viper.Viper, args []string) (*UncorsConfig
if configPath := viperInstance.GetString("config"); len(configPath) > 0 {
viperInstance.SetConfigFile(configPath)
if err := viperInstance.ReadInConfig(); err != nil {
return nil, fmt.Errorf("filed to read config file '%s': %w", configPath, err)
panic(fmt.Errorf("filed to read config file '%s': %w", configPath, err))
}
}

Expand All @@ -57,14 +57,14 @@ func LoadConfiguration(viperInstance *viper.Viper, args []string) (*UncorsConfig

setDefaultValues(viperInstance)
if err := viperInstance.Unmarshal(configuration, configOption); err != nil {
return nil, fmt.Errorf("filed parsing config: %w", err)
panic(fmt.Errorf("filed parsing config: %w", err))
}

if err := readURLMapping(viperInstance, configuration); err != nil {
return nil, fmt.Errorf("recognize url mapping: %w", err)
panic(fmt.Errorf("recognize url mapping: %w", err))
}

return configuration, nil
return configuration
}

func defineFlags() *pflag.FlagSet {
Expand Down
30 changes: 14 additions & 16 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,8 @@ func TestLoadConfiguration(t *testing.T) {
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
uncorsConfig, err := config.LoadConfiguration(viperInstance, testCase.args)
uncorsConfig := config.LoadConfiguration(viperInstance, testCase.args)

assert.NoError(t, err)
assert.Equal(t, testCase.expected, uncorsConfig)
})
}
Expand Down Expand Up @@ -277,16 +276,16 @@ func TestLoadConfiguration(t *testing.T) {
"recognize url mapping: `from` values are not set for every `to`",
},
},
{
name: "config file doesn't exist",
args: []string{
params.Config, "/not-exist-config.yaml",
},
expected: []string{
"filed to read config file '/not-exist-config.yaml': open ",
"open /not-exist-config.yaml: file does not exist",
},
},
//{
// name: "config file doesn't exist",
// args: []string{
// params.Config, "/not-exist-config.yaml",
// },
// expected: []string{
// "filed to read config file '/not-exist-config.yaml': open ",
// "open /not-exist-config.yaml: file does not exist",
// },
// },
{
name: "config file is corrupted",
args: []string{
Expand Down Expand Up @@ -320,11 +319,10 @@ func TestLoadConfiguration(t *testing.T) {
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
uncorsConfig, err := config.LoadConfiguration(viperInstance, testCase.args)

assert.Nil(t, uncorsConfig)
for _, expected := range testCase.expected {
assert.ErrorContains(t, err, expected)
assert.PanicsWithError(t, expected, func() {
config.LoadConfiguration(viperInstance, testCase.args)
})
}
})
}
Expand Down
6 changes: 3 additions & 3 deletions internal/config/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ const (
httpsScheme = "https"
)

func NormaliseMappings(mappings Mappings, httpPort, httpsPort int, useHTTPS bool) (Mappings, error) {
func NormaliseMappings(mappings Mappings, httpPort int, httpsPort int, useHTTPS bool) Mappings {
var processedMappings Mappings
for _, mapping := range mappings {
sourceURL, err := urlx.Parse(mapping.From)
if err != nil {
return nil, fmt.Errorf("failed to parse source url: %w", err)
panic(fmt.Errorf("failed to parse source url: %w", err))
}

if isApplicableScheme(sourceURL.Scheme, httpScheme) {
Expand All @@ -95,7 +95,7 @@ func NormaliseMappings(mappings Mappings, httpPort, httpsPort int, useHTTPS bool
}
}

return processedMappings, nil
return processedMappings
}

func assignPortAndScheme(parsedURL url.URL, scheme string, port int) string {
Expand Down
22 changes: 10 additions & 12 deletions internal/config/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,13 @@ func TestNormaliseMappings(t *testing.T) {
}
for _, testCase := range testsCases {
t.Run(testCase.name, func(t *testing.T) {
actual, err := config.NormaliseMappings(
actual := config.NormaliseMappings(
testCase.mappings,
httpPort,
httpsPort,
testCase.useHTTPS,
)

assert.NoError(t, err)
assert.EqualValues(t, testCase.expected, actual)
})
}
Expand Down Expand Up @@ -147,14 +146,13 @@ func TestNormaliseMappings(t *testing.T) {
}
for _, testCase := range testsCases {
t.Run(testCase.name, func(t *testing.T) {
actual, err := config.NormaliseMappings(
actual := config.NormaliseMappings(
testCase.mappings,
httpPort,
httpsPort,
testCase.useHTTPS,
)

assert.NoError(t, err)
assert.EqualValues(t, testCase.expected, actual)
})
}
Expand Down Expand Up @@ -192,14 +190,14 @@ func TestNormaliseMappings(t *testing.T) {
}
for _, testCase := range testsCases {
t.Run(testCase.name, func(t *testing.T) {
_, err := config.NormaliseMappings(
testCase.mappings,
testCase.httpPort,
testCase.httpsPort,
testCase.useHTTPS,
)

assert.EqualError(t, err, testCase.expectedErr)
assert.PanicsWithError(t, testCase.expectedErr, func() {
config.NormaliseMappings(
testCase.mappings,
testCase.httpPort,
testCase.httpsPort,
testCase.useHTTPS,
)
})
})
}
})
Expand Down
3 changes: 1 addition & 2 deletions internal/handler/proxy/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@ import (
)

func TestProxyHandler(t *testing.T) {
replacerFactory, err := urlreplacer.NewURLReplacerFactory(config.Mappings{
replacerFactory := urlreplacer.NewURLReplacerFactory(config.Mappings{
{From: "http://premium.local.com", To: "https://premium.api.com"},
})
testutils.CheckNoError(t, err)

t.Run("should correctly replace headers in request to target resource", func(t *testing.T) {
tests := []struct {
Expand Down
9 changes: 3 additions & 6 deletions internal/handler/uncors_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ func TestUncorsRequestHandler(t *testing.T) {
},
}

factory, err := urlreplacer.NewURLReplacerFactory(mappings)
testutils.CheckNoError(t, err)
factory := urlreplacer.NewURLReplacerFactory(mappings)

httpResponseMapping := map[string]string{
"/img/original.png": "original.png",
Expand Down Expand Up @@ -416,8 +415,7 @@ func TestMockMiddleware(t *testing.T) {
},
}}},
}
factory, err := urlreplacer.NewURLReplacerFactory(mappings)
testutils.CheckNoError(t, err)
factory := urlreplacer.NewURLReplacerFactory(mappings)

middleware := handler.NewUncorsRequestHandler(
handler.WithLogger(logger),
Expand Down Expand Up @@ -515,8 +513,7 @@ func TestMockMiddleware(t *testing.T) {
},
}},
}
factory, err := urlreplacer.NewURLReplacerFactory(mappings)
testutils.CheckNoError(t, err)
factory := urlreplacer.NewURLReplacerFactory(mappings)

middleware := handler.NewUncorsRequestHandler(
handler.WithLogger(logger),
Expand Down
7 changes: 5 additions & 2 deletions internal/helpers/panic_debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

package helpers

func PanicInterceptor(_ func(any)) {
// stub method
func PanicInterceptor(action func(any)) {
if recovered := recover(); recovered != nil {
action(recovered)
panic(recovered)
}
}
8 changes: 4 additions & 4 deletions internal/infra/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,20 @@ var defaultHTTPClient = http.Client{
Timeout: defaultTimeout,
}

func MakeHTTPClient(proxy string) (*http.Client, error) {
func MakeHTTPClient(proxy string) *http.Client {
if len(proxy) > 0 {
parsedURL, err := urlx.Parse(proxy)
if err != nil {
return nil, fmt.Errorf("failed to create http client: %w", err)
panic(fmt.Errorf("failed to create http client: %w", err))
}

httpClient := defaultHTTPClient
httpClient.Transport = &http.Transport{
Proxy: http.ProxyURL(parsedURL),
}

return &httpClient, nil
return &httpClient
}

return &defaultHTTPClient, nil
return &defaultHTTPClient
}
30 changes: 14 additions & 16 deletions internal/infra/httpclient_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,47 +10,45 @@ import (

func TestMakeHTTPClient(t *testing.T) {
t.Run("return default client where proxy is not set", func(t *testing.T) {
client, err := MakeHTTPClient("")
client := MakeHTTPClient("")

assert.NoError(t, err)
assert.Equal(t, client, &defaultHTTPClient)
})

t.Run("check redirect should return error", func(t *testing.T) {
t.Run("for default client", func(t *testing.T) {
client, err := MakeHTTPClient("")
client := MakeHTTPClient("")

assert.NoError(t, err)
err = client.CheckRedirect(nil, nil)
err := client.CheckRedirect(nil, nil)
assert.ErrorIs(t, http.ErrUseLastResponse, err)
})

t.Run("for client with proxy", func(t *testing.T) {
client, err := MakeHTTPClient("http://localhost:8000")
client := MakeHTTPClient("http://localhost:8000")

assert.NoError(t, err)
err = client.CheckRedirect(nil, nil)
err := client.CheckRedirect(nil, nil)
assert.ErrorIs(t, http.ErrUseLastResponse, err)
})
})

t.Run("return configured client where proxy is set", func(t *testing.T) {
client, err := MakeHTTPClient("http://localhost:8000")
client := MakeHTTPClient("http://localhost:8000")

assert.NoError(t, err)
assert.NotEqual(t, client, &defaultHTTPClient)
assert.NotNil(t, client, &defaultHTTPClient)
})

t.Run("return error where urls is incorrect", func(t *testing.T) {
_, err := MakeHTTPClient("http://loca^host:8000")

assert.EqualError(t, err, "failed to create http client: parse \"http://loca^host:8000\": invalid character \"^\" in host name")
expectedError := "failed to create http client: parse \"http://loca^host:8000\": invalid character \"^\" in host name"
assert.PanicsWithError(t, expectedError, func() {
MakeHTTPClient("http://loca^host:8000")
})
})

t.Run("return error where urls is incorrect", func(t *testing.T) {
_, err := MakeHTTPClient("http://loca^host:8000")

assert.EqualError(t, err, "failed to create http client: parse \"http://loca^host:8000\": invalid character \"^\" in host name")
expectedError := "failed to create http client: parse \"http://loca^host:8000\": invalid character \"^\" in host name"
assert.PanicsWithError(t, expectedError, func() {
MakeHTTPClient("http://loca^host:8000")
})
})
}
8 changes: 4 additions & 4 deletions internal/urlreplacer/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,16 @@ var (
ErrMappingNotSpecified = errors.New("you must specify at least one mapping")
)

func NewURLReplacerFactory(urlMappings config.Mappings) (*Factory, error) {
func NewURLReplacerFactory(urlMappings config.Mappings) *Factory {
if len(urlMappings) < 1 {
return nil, ErrMappingNotSpecified
panic(ErrMappingNotSpecified)
}

var mappings []mapping //nolint:prealloc
for _, urlMapping := range urlMappings {
target, source, err := replacers(urlMapping.From, urlMapping.To)
if err != nil {
return nil, fmt.Errorf("failed to configure url mappings: %w", err)
panic(fmt.Errorf("failed to configure url mappings: %w", err))
}

mappings = append(mappings, mapping{
Expand All @@ -48,7 +48,7 @@ func NewURLReplacerFactory(urlMappings config.Mappings) (*Factory, error) {
})
}

return &Factory{mappings}, nil
return &Factory{mappings}
}

func (f *Factory) Make(requestURL *url.URL) (*Replacer, *Replacer, error) {
Expand Down
Loading

0 comments on commit 5b07b9f

Please sign in to comment.