Skip to content

Commit

Permalink
Added helpers.CloseSafe method
Browse files Browse the repository at this point in the history
  • Loading branch information
evg4b committed May 30, 2023
1 parent d88bdcb commit f0705c9
Show file tree
Hide file tree
Showing 16 changed files with 290 additions and 31 deletions.
4 changes: 1 addition & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,10 @@ linters:
- exhaustruct
- wsl
- gci
- gofmt
- gofumpt
- nolintlint
- tagliatelle
- maintidx
- ireturn
- bodyclose
linters-settings:
varnamelen:
ignore-names:
Expand Down
3 changes: 2 additions & 1 deletion internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ func TestLoadConfiguration(t *testing.T) {
File: "/demo.txt",
},
},
}},
},
},
{From: mocks.SourceHost1, To: mocks.TargetHost1},
{From: mocks.SourceHost2, To: mocks.TargetHost2},
{From: mocks.SourceHost3, To: mocks.TargetHost3},
Expand Down
1 change: 0 additions & 1 deletion internal/config/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ func decodeConfig[T any](data any, mapping *T, decodeFuncs ...mapstructure.Decod
ErrorUnused: true,
IgnoreUntaggedFields: true,
})

if err != nil {
return err //nolint:wrapcheck
}
Expand Down
6 changes: 4 additions & 2 deletions internal/config/mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ func (u Mapping) Clone() Mapping {
}
}

var mappingType = reflect.TypeOf(Mapping{})
var mappingFields = getTagValues(mappingType, "mapstructure")
var (
mappingType = reflect.TypeOf(Mapping{})
mappingFields = getTagValues(mappingType, "mapstructure")
)

func URLMappingHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, rawData any) (any, error) {
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/proxy/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (m *Handler) handle(resp http.ResponseWriter, req *http.Request) error {
return err
}

defer originalResponse.Body.Close()
defer helpers.CloseSafe(originalResponse.Body)

err = m.makeUncorsResponse(originalResponse, resp, sourceReplacer)
if err != nil {
Expand Down
7 changes: 2 additions & 5 deletions internal/handler/static/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"

"github.com/evg4b/uncors/internal/contracts"
"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/infra"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/spf13/afero"
Expand Down Expand Up @@ -38,11 +39,7 @@ func (m *Middleware) ServeHTTP(writer http.ResponseWriter, request *http.Request
filePath := m.extractFilePath(request)

file, stat, err := m.openFile(filePath)
defer func() {
if file != nil {
file.Close()
}
}()
defer helpers.CloseSafe(file)

if err != nil {
if errors.Is(err, errNorHandled) {
Expand Down
1 change: 1 addition & 0 deletions internal/handler/static/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const (
demoJS = "/assets/demo.js"
indexHTML = "/index.html"
)

const (
indexJSContent = "console.log('index.js')"
demoJSContent = "console.log('demo.js')"
Expand Down
13 changes: 13 additions & 0 deletions internal/helpers/closer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package helpers

import "io"

func CloseSafe(resource io.Closer) {
if resource == nil {
return
}

if err := resource.Close(); err != nil {
panic(err)
}
}
33 changes: 33 additions & 0 deletions internal/helpers/closer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package helpers_test

import (
"testing"

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

func TestCloseSafe(t *testing.T) {
t.Run("should correct handle nil pointer", func(t *testing.T) {
assert.NotPanics(t, func() {
helpers.CloseSafe(nil)
})
})

t.Run("correctly close resource without error", func(t *testing.T) {
assert.NotPanics(t, func() {
resource := mocks.NewCloserMock(t).CloseMock.Return(nil)

helpers.CloseSafe(resource)
})
})

t.Run("panics when resource close return error", func(t *testing.T) {
assert.Panics(t, func() {
resource := mocks.NewCloserMock(t).CloseMock.Return(mocks.ErrTest1)

helpers.CloseSafe(resource)
})
})
}
8 changes: 4 additions & 4 deletions internal/helpers/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import (
)

func TestNormaliseRequest(t *testing.T) {
var url, err = urlx.Parse("http://localhost")
url, err := urlx.Parse("http://localhost")
testutils.CheckNoError(t, err)

t.Run("set correct scheme", func(t *testing.T) {
t.Run("http", func(t *testing.T) {
var request = &http.Request{
request := &http.Request{
URL: url,
Host: "localhost",
}
Expand All @@ -28,7 +28,7 @@ func TestNormaliseRequest(t *testing.T) {
})

t.Run("https", func(t *testing.T) {
var request = &http.Request{
request := &http.Request{
URL: url,
TLS: &tls.ConnectionState{},
Host: "localhost",
Expand All @@ -41,7 +41,7 @@ func TestNormaliseRequest(t *testing.T) {
})

t.Run("fill url.host", func(t *testing.T) {
var request = &http.Request{
request := &http.Request{
URL: url,
TLS: &tls.ConnectionState{},
Host: "localhost",
Expand Down
8 changes: 5 additions & 3 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ type UncorsServer struct {
inShutdown AtomicBool
}

const readHeaderTimeout = 30 * time.Second
const shutdownTimeout = 15 * time.Second
const (
readHeaderTimeout = 30 * time.Second
shutdownTimeout = 15 * time.Second
)

func NewUncorsServer(ctx context.Context, handler http.Handler) *UncorsServer {
globalCtx, globalCtxCancel := context.WithCancel(ctx)
Expand Down Expand Up @@ -79,7 +81,7 @@ func (srv *UncorsServer) ListenAndServeTLS(addr string, certFile, keyFile string
return err
}

defer listener.Close()
defer helpers.CloseSafe(listener)

srv.Addr = listener.Addr().String()
err = srv.ServeTLS(listener, certFile, keyFile)
Expand Down
12 changes: 4 additions & 8 deletions internal/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"
"time"

"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/server"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/testing/testutils"
Expand Down Expand Up @@ -42,9 +43,7 @@ func TestNewUncorsServer(t *testing.T) {

res, err := http.DefaultClient.Do(&http.Request{URL: uri, Method: http.MethodGet})
testutils.CheckNoError(t, err)
defer func() {
testutils.CheckNoError(t, res.Body.Close())
}()
defer helpers.CloseSafe(res.Body)

data, err := io.ReadAll(res.Body)
testutils.CheckNoError(t, err)
Expand Down Expand Up @@ -75,9 +74,7 @@ func TestNewUncorsServer(t *testing.T) {

response, err := httpClient.Do(&http.Request{URL: uri, Method: http.MethodGet})
testutils.CheckNoError(t, err)
defer func() {
testutils.CheckNoError(t, response.Body.Close())
}()
defer helpers.CloseSafe(response.Body)

actualResponse, err := io.ReadAll(response.Body)
testutils.CheckNoError(t, err)
Expand All @@ -88,8 +85,7 @@ func TestNewUncorsServer(t *testing.T) {

t.Run("run already stopped server", func(t *testing.T) {
uncorsServer := server.NewUncorsServer(ctx, handler)
err := uncorsServer.Close()
testutils.CheckNoServerError(t, err)
testutils.CheckNoServerError(t, uncorsServer.Close())

t.Run("HTTP", func(t *testing.T) {
err := uncorsServer.ListenAndServe("127.0.0.1:0")
Expand Down
3 changes: 2 additions & 1 deletion internal/version/new_version_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"encoding/json"
"github.com/evg4b/uncors/internal/contracts"
"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/log"
"github.com/evg4b/uncors/internal/ui"
"github.com/hashicorp/go-version"
Expand Down Expand Up @@ -42,7 +43,7 @@ func CheckNewVersion(ctx context.Context, client contracts.HTTPClient, rawCurren
return
}

defer response.Body.Close()
defer helpers.CloseSafe(response.Body)
decoder := json.NewDecoder(response.Body)

lastVersionInfo := versionInfo{}
Expand Down
Loading

0 comments on commit f0705c9

Please sign in to comment.