Skip to content

Commit 62f4976

Browse files
refactor(tests): min go 1.23, golangci-lint 2.5.0, linter advices (#31)
This pull request introduces a series of updates and improvements to the codebase, focusing on dependency updates, testing enhancements, and general code hygiene. ### CI/CD - **Go Version:** The Go version used in the CI workflow has been upgraded f om `1.22` to `1.23`. This allows us to leverage the latest features and improvements in the Go language. - **golangci-lint:** The version of `golangci-lint` has been updated from `v2.1.6` to `v2.5.0`. This brings in new linting rules and bug fixes, helping to improve code quality. ### Testing - **Context Handling:** In the test files, all instances of `context.Background()` have been replaced with `t.Context()`. This is a significant improvement in our testing practices. `t.Context()` provides a context that is automatically canceled when the test or subtest completes, preventing resource leaks from dangling goroutines and making the tests more robust. - **Test Assertion Fix:** A bug in the `TestUpdate` function within `client_test.go` has been resolved. Previously, the `originalComment` and `changedComment` variables were identical, meaning the test was not correctly verifying the update functionality. This has been corrected to ensure the test is effective. - **Loop Variable Handling:** The `//nolint:copyloopvar` directive has been removed from the `TestConflict` function. This is now possible due to the improved handling of loop variables in Go `1.22` and later. ### Other Changes - **Go Module:** The `go.mod` file has been updated to reflect the new Go version (`1.23.0`) and the `toolchain` directive has been removed. - **Code Formatting:** Various minor code formatting adjustments have been made throughout the codebase to improve readability and maintain consistency. - **Documentation:** A minor typo in a function comment in `listzones.go` has been corrected.
1 parent 03033c8 commit 62f4976

16 files changed

Lines changed: 59 additions & 14 deletions

.github/workflows/ci.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ jobs:
1212
test:
1313
strategy:
1414
matrix:
15-
go: ["1.22", "stable"]
15+
go: ["1.23", "stable"]
1616
name: test
1717
runs-on: ubuntu-latest
1818
steps:
@@ -31,8 +31,8 @@ jobs:
3131
golangci:
3232
strategy:
3333
matrix:
34-
go: ["1.22", "stable"]
35-
lint: ["v2.1.6"]
34+
go: ["1.23", "stable"]
35+
lint: ["v2.5.0"]
3636
name: lint
3737
runs-on: ubuntu-latest
3838
steps:

client.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ var errResponseTooLarge = retry.PermanentError{
3838

3939
type Client struct {
4040
*settings
41+
4142
creds Credentials
4243
}
4344

@@ -66,10 +67,13 @@ func sendRequestRetry[TRESP commonResponseSetter](
6667
error,
6768
) {
6869
var resp *response[TRESP]
70+
6971
reterr := retry.ExpBackoff(ctx, logger, retryFirstDelay, retryMaxDelay,
7072
retryFactor, retryMaxAttempts, func() error {
7173
var err error
74+
7275
resp, err = sendRequest[TRESP](ctx, client, logger, req)
76+
7377
return err
7478
})
7579

@@ -105,8 +109,10 @@ func sendRequest[TRESP commonResponseSetter](
105109

106110
// request timeout
107111
reqCtx := ctx
112+
108113
if client.requestTimeout > 0 {
109114
var reqCtxCancel func()
115+
110116
reqCtx, reqCtxCancel = context.WithTimeout(reqCtx, client.requestTimeout)
111117
defer reqCtxCancel()
112118
}
@@ -145,6 +151,7 @@ func sendRequest[TRESP commonResponseSetter](
145151
if resp.StatusCode >= 400 {
146152
err = handleErrorResponse(resp, logger)
147153
logFullRequestResponse(logger, reqNoAuth, reqBody, resp, rawResponseFromErr(err))
154+
148155
return nil, err
149156
}
150157

@@ -171,6 +178,7 @@ func handleSuccessResponse[TRESP commonResponseSetter](httpResp *http.Response,
171178
ret.headers = httpResp.Header
172179

173180
var err error
181+
174182
ret.rawBody, err = readResponseBody(httpResp.Body)
175183
if err != nil {
176184
// error response already specifies is can retry or not
@@ -183,6 +191,7 @@ func handleSuccessResponse[TRESP commonResponseSetter](httpResp *http.Response,
183191

184192
if len(ret.rawBody) == maxResponseLength {
185193
logger.W(fmt.Sprintf("Response from CloudFlare rejected because is bigger than %d", maxResponseLength))
194+
186195
return nil, retry.PermanentError{
187196
Cause: errors.Join(err, HTTPError{
188197
Code: httpResp.StatusCode,
@@ -238,6 +247,7 @@ func handleErrorResponse(resp *http.Response, _ *log.Logger) error {
238247
}
239248

240249
var cfcommon cfResponseCommon
250+
241251
err = json.Unmarshal(respBody, &cfcommon)
242252
if err != nil {
243253
return retry.PermanentError{Cause: fmt.Errorf("CloudFlare returned an error, unmarshaling the error body as json failed: %w; %w", err, httpErr)}
@@ -283,6 +293,7 @@ func logFullRequestResponse(
283293

284294
func requestURL(treq *request) string {
285295
urlstring := baseURL + "/" + treq.path
296+
286297
theurl, err := url.Parse(urlstring)
287298
if err != nil {
288299
// this only happens in case of coding error on cfapi

client_test.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,15 @@ const (
2828

2929
func TestCreateCNAME(t *testing.T) {
3030
t.Parallel()
31+
3132
ctx := context.Background()
3233
client, testZoneID := getClient(ctx, t)
3334
cname := "CNAME"
3435
comment := "integration test"
3536

3637
// create a DNS record
3738
recName := testRecordName(t)
39+
3840
resp, err := client.CreateRecord(ctx, &cfdns.CreateRecordRequest{
3941
ZoneID: testZoneID,
4042
Name: recName,
@@ -52,6 +54,7 @@ func TestCreateCNAME(t *testing.T) {
5254

5355
// assert that it is present
5456
var recs []*cfdns.ListRecordsResponseItem
57+
5558
recs, err = cfdns.ReadAll(ctx, client.ListRecords(&cfdns.ListRecordsRequest{
5659
ZoneID: testZoneID,
5760
Name: resp.Name,
@@ -75,15 +78,17 @@ func TestCreateCNAME(t *testing.T) {
7578

7679
func TestUpdate(t *testing.T) {
7780
t.Parallel()
81+
7882
originalComment := "integration test"
79-
changedComment := "integration test"
83+
changedComment := "integration test - changed"
8084
cname := "cname"
8185

8286
ctx := context.Background()
8387
client, testZoneID := getClient(ctx, t)
8488

8589
// create a DNS record
8690
recName := testRecordName(t)
91+
8792
resp, err := client.CreateRecord(ctx, &cfdns.CreateRecordRequest{
8893
ZoneID: testZoneID,
8994
Name: recName,
@@ -139,6 +144,7 @@ func TestUpdate(t *testing.T) {
139144
// Test a few cases of error to make sure error handling works.
140145
func TestConflict(t *testing.T) {
141146
t.Parallel()
147+
142148
ctx := context.Background()
143149
client, testZoneID := getClient(ctx, t)
144150

@@ -160,13 +166,14 @@ func TestConflict(t *testing.T) {
160166
}
161167

162168
for _, tc := range cases {
163-
tc := tc //nolint:copyloopvar
164169
t.Run(tc.typ, func(t *testing.T) {
165170
t.Parallel()
171+
166172
comment := "integration test"
167173

168174
// create a DNS record
169175
recName := testRecordName(t)
176+
170177
resp, err := client.CreateRecord(ctx, &cfdns.CreateRecordRequest{
171178
ZoneID: testZoneID,
172179
Name: recName,
@@ -238,6 +245,7 @@ func getClient(ctx context.Context, t *testing.T) (_ *cfdns.Client, testZoneID s
238245
}
239246

240247
t.Fatalf("Zone %s not found on CloudFlare", testzone)
248+
241249
return nil, ""
242250
}
243251

@@ -250,7 +258,9 @@ func testRecordName(t *testing.T) string {
250258
testzone := os.Getenv(envTestZone)
251259

252260
rnd := make([]byte, 4)
253-
if _, err := rand.Read(rnd); err != nil {
261+
262+
_, err := rand.Read(rnd)
263+
if err != nil {
254264
t.Fatalf("Error reading random number: %v", err)
255265
}
256266

@@ -292,6 +302,7 @@ func cleanup(
292302
}
293303

294304
t.Logf("Error listing records when looking for old test data: %v", err)
305+
295306
return
296307
}
297308

@@ -304,6 +315,7 @@ func cleanup(
304315
if err != nil {
305316
t.Errorf("Record %s (%s %s %s) has a time part %q that is invalid",
306317
record.ID, record.Name, record.Type, record.Content, matches[1])
318+
307319
continue
308320
}
309321

@@ -326,6 +338,7 @@ func cleanup(
326338

327339
func requireNotNil(t *testing.T, v any) {
328340
t.Helper()
341+
329342
if v == nil {
330343
t.Fatalf("Unexpected nil value")
331344
}

createrecord.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ func (c *Client) CreateRecord(
4141
TTL: ttl,
4242
},
4343
})
44-
4544
if err != nil {
4645
return nil, err
4746
}
@@ -50,6 +49,7 @@ func (c *Client) CreateRecord(
5049
log(fmt.Sprintf("Record %s %s %s created with ID=%s",
5150
req.Name, req.Type, req.Content, resp.body.Result.ID))
5251
})
52+
5353
return &CreateRecordResponse{
5454
ID: resp.body.Result.ID,
5555
Name: resp.body.Result.Name,
@@ -84,6 +84,7 @@ type createRecordAPIRequest struct {
8484

8585
type createRecordAPIResponse struct {
8686
cfResponseCommon
87+
8788
Result struct {
8889
ID string `json:"id"`
8990
Name string `json:"name"`

deleterecord.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,14 @@ func (c *Client) DeleteRecord(
2828
queryParams: url.Values{},
2929
body: nil,
3030
})
31-
3231
if err != nil {
3332
return nil, err
3433
}
3534

3635
c.logger.D(func(log log.DebugFn) {
3736
log(fmt.Sprintf("Record %s deleted", req.RecordID))
3837
})
38+
3939
return &DeleteRecordResponse{}, err
4040
}
4141

go.mod

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ module github.com/simplesurance/cfdns
22

33
go 1.23.0
44

5-
toolchain go1.24.3
6-
75
require (
86
github.com/fatih/color v1.18.0
97
golang.org/x/time v0.12.0

iterator.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type fetchFn[T any] func(ctx context.Context) (batch []*T, last bool, _ error)
2323
func (it *Iterator[T]) Next(ctx context.Context) (retElm *T, err error) {
2424
if len(it.elements) == 0 && !it.isLast {
2525
var elements []*T
26+
2627
elements, it.isLast, err = it.fetchNext(ctx)
2728
if err != nil {
2829
return nil, err
@@ -37,13 +38,15 @@ func (it *Iterator[T]) Next(ctx context.Context) (retElm *T, err error) {
3738

3839
retElm = it.elements[0]
3940
it.elements = it.elements[1:]
41+
4042
return retElm, nil
4143
}
4244

4345
// ReadAll is an utility function that reads all elements from an iterator
4446
// and return them as an array.
4547
func ReadAll[T any](ctx context.Context, it *Iterator[T]) ([]*T, error) {
4648
ret := []*T{}
49+
4750
for {
4851
item, err := it.Next(ctx)
4952
if err != nil {

listrecords.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ func (c *Client) ListRecords(
5252
queryParams: queryParams,
5353
body: nil,
5454
})
55-
5655
if err != nil {
5756
return nil, false, err
5857
}
@@ -100,6 +99,7 @@ type ListRecordsResponseItem struct {
10099

101100
type listRecordsAPIResponse struct {
102101
cfResponseCommon
102+
103103
Result []listRecordsAPIResponseItem `json:"result"`
104104
}
105105

listzones.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99
"github.com/simplesurance/cfdns/log"
1010
)
1111

12-
// Listzones lists zones on CloudFlare.
12+
// ListZones lists zones on CloudFlare.
1313
//
1414
// API Reference: https://developers.cloudflare.com/api/operations/zones-get
1515
func (c *Client) ListZones(
@@ -44,7 +44,6 @@ func (c *Client) ListZones(
4444
queryParams: queryParams,
4545
body: nil,
4646
})
47-
4847
if err != nil {
4948
return nil, false, err
5049
}
@@ -75,6 +74,7 @@ type ListZonesResponseItem struct {
7574

7675
type listZoneAPIResponse struct {
7776
cfResponseCommon
77+
7878
Result []listZoneAPIResponseItem `json:"result"`
7979
}
8080

log/logger.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,27 +66,31 @@ func (l *Logger) I(msg string, opt ...Option) {
6666
if helper := l.driver.PreLog(); helper != nil {
6767
helper()
6868
}
69+
6970
l.log(msg, Info, opt...)
7071
}
7172

7273
func (l *Logger) W(msg string, opt ...Option) {
7374
if helper := l.driver.PreLog(); helper != nil {
7475
helper()
7576
}
77+
7678
l.log(msg, Warn, opt...)
7779
}
7880

7981
func (l *Logger) E(msg string, opt ...Option) {
8082
if helper := l.driver.PreLog(); helper != nil {
8183
helper()
8284
}
85+
8386
l.log(msg, Error, opt...)
8487
}
8588

8689
func (l *Logger) d(msg string, opt ...Option) {
8790
if helper := l.driver.PreLog(); helper != nil {
8891
helper()
8992
}
93+
9094
l.log(msg, Debug, opt...)
9195
}
9296

0 commit comments

Comments
 (0)