diff options
| author | Shulhan <ms@kilabit.info> | 2024-03-03 04:59:34 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2024-03-05 14:53:12 +0700 |
| commit | 2fa7605727e90ca323b7b24168632e485d74c583 (patch) | |
| tree | 3533df0fc07ef96b1564736926cc3310994be515 | |
| parent | b921ebfb3e81b367ff24305eb18c5dd073b38635 (diff) | |
| download | pakakeh.go-2fa7605727e90ca323b7b24168632e485d74c583.tar.xz | |
all: comply with linter recommendations #2
HTTP request now implicitly create request with context.
Any false positive related to not closing HTTP response body has been
annotated with "nolint:bodyclose".
In the example code, use consistent "// Output:" comment format, by
prefixing with single space.
Any comment on code now also prefixing with single space.
An error returned without variables now use [errors.New] instead of
[fmt.Errorf].
Any error returned using [fmt.Errorf] now wrapped using "%w" instead of
"%s".
Also, replace error checking using [errors.Is] or [errors.As], instead
of using equal/not-equal operator.
Any statement like "x = x OP y" now replaced with "x OP= y".
Also, swap statement is simplified using "x, y = y, x".
Any switch statement with single case now replaced with if-condition.
Any call to defer on function or program that call [os.Exit], now
replaced by calling the deferred function directly.
Any if-else condition now replaced with switch statement, if possible.
130 files changed, 1153 insertions, 972 deletions
@@ -34,7 +34,7 @@ lint: -go vet ./... -fieldalignment ./... -shadow ./... - -revive ./... + -golangci-lint run --presets bugs,metalinter,performance,unused ./... $(CIIGO): go install git.sr.ht/~shulhan/ciigo/cmd/ciigo diff --git a/api/slack/slack.go b/api/slack/slack.go index 6ed1906e..6e3092e2 100644 --- a/api/slack/slack.go +++ b/api/slack/slack.go @@ -8,6 +8,7 @@ package slack import ( "bytes" + "context" "encoding/json" "fmt" "io" @@ -27,9 +28,21 @@ func PostWebhook(webhookURL string, msg *Message) (err error) { return fmt.Errorf(`%s: %w`, logp, err) } + var ( + ctx = context.Background() + httpReq *http.Request + ) + + httpReq, err = http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewReader(payload)) + if err != nil { + return fmt.Errorf(`%s: %w`, logp, err) + } + + httpReq.Header.Set(`Content-Type`, `application/json`) + var res *http.Response - res, err = http.DefaultClient.Post(webhookURL, `application/json`, bytes.NewReader(payload)) + res, err = http.DefaultClient.Do(httpReq) if err != nil { return fmt.Errorf(`%s: %w`, logp, err) } diff --git a/api/slack/webhook_client.go b/api/slack/webhook_client.go index 651f8d35..4e7683db 100644 --- a/api/slack/webhook_client.go +++ b/api/slack/webhook_client.go @@ -54,7 +54,7 @@ func (wcl *WebhookClient) Post(msg *Message) (err error) { var logp = `Post` - httpRes, resBody, err := wcl.Client.PostJSON(wcl.webhookPath, nil, msg) + httpRes, resBody, err := wcl.Client.PostJSON(wcl.webhookPath, nil, msg) //nolint: bodyclose if err != nil { return fmt.Errorf(`%s: %w`, logp, err) } diff --git a/api/telegram/bot/bot.go b/api/telegram/bot/bot.go index 2f237489..7cbbdc0a 100644 --- a/api/telegram/bot/bot.go +++ b/api/telegram/bot/bot.go @@ -133,7 +133,7 @@ func New(opts Options) (bot *Bot, err error) { // DeleteWebhook remove webhook integration if you decide to switch back to // getUpdates. Returns True on success. Requires no parameters. func (bot *Bot) DeleteWebhook() (err error) { - _, resBody, err := bot.client.PostForm(methodDeleteWebhook, nil, nil) + _, resBody, err := bot.client.PostForm(methodDeleteWebhook, nil, nil) //nolint: bodyclose if err != nil { return fmt.Errorf("DeleteWebhook: %w", err) } @@ -151,7 +151,7 @@ func (bot *Bot) DeleteWebhook() (err error) { // Requires no parameters. // Returns basic information about the bot in form of a User object. func (bot *Bot) GetMe() (user *User, err error) { - _, resBody, err := bot.client.Get(methodGetMe, nil, nil) + _, resBody, err := bot.client.Get(methodGetMe, nil, nil) //nolint: bodyclose if err != nil { return nil, fmt.Errorf("GetMe: %w", err) } @@ -170,7 +170,7 @@ func (bot *Bot) GetMe() (user *User, err error) { // GetMyCommands get the current list of the bot's commands. func (bot *Bot) GetMyCommands() (cmds []Command, err error) { - _, resBody, err := bot.client.Get(methodGetMyCommands, nil, nil) + _, resBody, err := bot.client.Get(methodGetMyCommands, nil, nil) //nolint: bodyclose if err != nil { return nil, fmt.Errorf("GetMyCommands: %w", err) } @@ -191,7 +191,7 @@ func (bot *Bot) GetMyCommands() (cmds []Command, err error) { // If the bot is using getUpdates, will return an object with the url field // empty. func (bot *Bot) GetWebhookInfo() (webhookInfo *WebhookInfo, err error) { - _, resBody, err := bot.client.Get(methodGetWebhookInfo, nil, nil) + _, resBody, err := bot.client.Get(methodGetWebhookInfo, nil, nil) //nolint: bodyclose if err != nil { return nil, fmt.Errorf("GetWebhookInfo: %w", err) } @@ -219,7 +219,7 @@ func (bot *Bot) SendMessage(parent *Message, parseMode, text string) ( ParseMode: parseMode, } - _, resBody, err := bot.client.PostJSON(methodSendMessage, nil, req) + _, resBody, err := bot.client.PostJSON(methodSendMessage, nil, req) //nolint: bodyclose if err != nil { return nil, fmt.Errorf("SendMessage: %w", err) } @@ -253,7 +253,7 @@ func (bot *Bot) SetMyCommands(cmds []Command) (err error) { bot.commands.Commands = cmds - _, resBody, err := bot.client.PostJSON(methodSetMyCommands, nil, &bot.commands) + _, resBody, err := bot.client.PostJSON(methodSetMyCommands, nil, &bot.commands) //nolint: bodyclose if err != nil { return fmt.Errorf("SetMyCommands: %w", err) } @@ -318,7 +318,7 @@ func (bot *Bot) setWebhook() (err error) { var resBody []byte - _, resBody, err = bot.client.PostFormData(methodSetWebhook, nil, params) + _, resBody, err = bot.client.PostFormData(methodSetWebhook, nil, params) //nolint: bodyclose if err != nil { return fmt.Errorf(`%s: %w`, logp, err) } @@ -402,7 +402,7 @@ func (bot *Bot) createServer() (err error) { // handleWebhook handle Updates from Webhook. func (bot *Bot) handleWebhook(epr *http.EndpointRequest) (resBody []byte, err error) { - update := Update{} + var update Update err = json.Unmarshal(epr.RequestBody, &update) if err != nil { diff --git a/lib/ascii/set_benchmark_test.go b/lib/ascii/set_benchmark_test.go index e353f4cc..104dcb2a 100644 --- a/lib/ascii/set_benchmark_test.go +++ b/lib/ascii/set_benchmark_test.go @@ -21,9 +21,9 @@ const N int = 10 // each Set is empty // // if populate is true, fill each set with every 2nd ASCII character -func setupSets(n int, populate bool) []Set { +func setupSets(populate bool) []Set { sets := []Set{} - for i := 0; i < n; i++ { + for i := 0; i < N; i++ { var as Set if populate { for c := 0; c < utf8.RuneSelf; c += 2 { @@ -40,9 +40,9 @@ func setupSets(n int, populate bool) []Set { // each map[byte]struct{} is empty // // if populate is true, fill each set with every 2nd ASCII character -func setupMapSets(n int, populate bool) []map[byte]struct{} { +func setupMapSets(populate bool) []map[byte]struct{} { sets := []map[byte]struct{}{} - for i := 0; i < n; i++ { + for i := 0; i < N; i++ { as := make(map[byte]struct{}) if populate { for c := 0; c < utf8.RuneSelf; c += 2 { @@ -57,7 +57,7 @@ func setupMapSets(n int, populate bool) []map[byte]struct{} { func BenchmarkSet(b *testing.B) { b.Run("Set Add()", func(b *testing.B) { - sets := setupSets(N, false) + sets := setupSets(false) b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { @@ -69,7 +69,7 @@ func BenchmarkSet(b *testing.B) { } }) b.Run("Set Contains()", func(b *testing.B) { - sets := setupSets(N, true) + sets := setupSets(true) var exists bool b.ResetTimer() for i := 0; i < b.N; i++ { @@ -82,7 +82,7 @@ func BenchmarkSet(b *testing.B) { globalExists = exists }) b.Run("Set Remove()", func(b *testing.B) { - sets := setupSets(N, true) + sets := setupSets(true) b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { @@ -93,7 +93,7 @@ func BenchmarkSet(b *testing.B) { } }) b.Run("Set Size()", func(b *testing.B) { - sets := setupSets(N, true) + sets := setupSets(true) var size int b.ResetTimer() for i := 0; i < b.N; i++ { @@ -106,7 +106,7 @@ func BenchmarkSet(b *testing.B) { globalSize = size }) b.Run("Set Visit()", func(b *testing.B) { - sets := setupSets(N, true) + sets := setupSets(true) var val byte b.ResetTimer() for i := 0; i < b.N; i++ { @@ -123,7 +123,7 @@ func BenchmarkSet(b *testing.B) { func BenchmarkMapSet(b *testing.B) { b.Run("map Add", func(b *testing.B) { - sets := setupMapSets(N, false) + sets := setupMapSets(false) b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { @@ -135,7 +135,7 @@ func BenchmarkMapSet(b *testing.B) { } }) b.Run("map Contains", func(b *testing.B) { - sets := setupMapSets(N, true) + sets := setupMapSets(true) var exists bool b.ResetTimer() for i := 0; i < b.N; i++ { @@ -148,7 +148,7 @@ func BenchmarkMapSet(b *testing.B) { globalExists = exists }) b.Run("map Remove", func(b *testing.B) { - sets := setupMapSets(N, true) + sets := setupMapSets(true) b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { @@ -159,7 +159,7 @@ func BenchmarkMapSet(b *testing.B) { } }) b.Run("map Size", func(b *testing.B) { - sets := setupMapSets(N, true) + sets := setupMapSets(true) var size int b.ResetTimer() for i := 0; i < b.N; i++ { @@ -172,7 +172,7 @@ func BenchmarkMapSet(b *testing.B) { globalSize = size }) b.Run("map Visit", func(b *testing.B) { - sets := setupMapSets(N, true) + sets := setupMapSets(true) var val byte b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/lib/bytes/bytes.go b/lib/bytes/bytes.go index 1d894a4f..089aa517 100644 --- a/lib/bytes/bytes.go +++ b/lib/bytes/bytes.go @@ -350,7 +350,7 @@ func ParseHexDump(in []byte) (out []byte, err error) { if start < 16 { start = 0 } else { - start = start - 16 + start -= 16 } var ( prevRow = out[start:] diff --git a/lib/clise/clise_example_test.go b/lib/clise/clise_example_test.go index de2cd5ed..b63655d5 100644 --- a/lib/clise/clise_example_test.go +++ b/lib/clise/clise_example_test.go @@ -28,9 +28,9 @@ func ExampleClise_RecentSlice() { fmt.Println(c.RecentSlice()) c.Push(4, 5, 6, 7) fmt.Println(c.RecentSlice()) - //Output: - //[1 2 3] - //[6 7] + // Output: + // [1 2 3] + // [6 7] } func ExampleClise_Reset() { @@ -40,9 +40,9 @@ func ExampleClise_Reset() { c.Reset() c.Push(1) fmt.Println(c.Slice()) - //Output: - //[1 2 3 4 5] - //[1] + // Output: + // [1 2 3 4 5] + // [1] } func ExampleClise_Slice() { @@ -55,9 +55,9 @@ func ExampleClise_Slice() { fmt.Println(c.Slice()) c.Push(7, 8, 9, 10) fmt.Println(c.Slice()) - //Output: - //[1 2] - //[1 2 3 4 5] - //[2 3 4 5 6] - //[6 7 8 9 10] + // Output: + // [1 2] + // [1 2 3 4 5] + // [2 3 4 5 6] + // [6 7 8 9 10] } diff --git a/lib/clise/example_test.go b/lib/clise/example_test.go index d37cbd1a..9fb7d36c 100644 --- a/lib/clise/example_test.go +++ b/lib/clise/example_test.go @@ -46,10 +46,10 @@ func ExampleClise_MarshalJSON() { fmt.Println(string(bjson)) } - //Output: - //[2,3,4] - //["Hello","Clise","MarshalJSON"] - //["MarshalJSON",{"String":"Hello","Int":1},{"String":"world","Int":2}] + // Output: + // [2,3,4] + // ["Hello","Clise","MarshalJSON"] + // ["MarshalJSON",{"String":"Hello","Int":1},{"String":"world","Int":2}] } func ExampleClise_UnmarshalJSON() { @@ -77,10 +77,10 @@ func ExampleClise_UnmarshalJSON() { } } - //Output: - //UnmarshalJSON: json: cannot unmarshal object into Go value of type []interface {} - //[2 3 4] - //[3 4 5] - //[Hello Clise MarshalJSON] - //[MarshalJSON map[Int:1 String:Hello] map[Int:2 String:world]] + // Output: + // UnmarshalJSON: json: cannot unmarshal object into Go value of type []interface {} + // [2 3 4] + // [3 4 5] + // [Hello Clise MarshalJSON] + // [MarshalJSON map[Int:1 String:Hello] map[Int:2 String:world]] } diff --git a/lib/contact/google/contact.go b/lib/contact/google/contact.go index a94be5eb..bdd6afed 100644 --- a/lib/contact/google/contact.go +++ b/lib/contact/google/contact.go @@ -12,13 +12,15 @@ import ( // // Some of the fields are disabled for speed. type Contact struct { - //ID GD - //ETag string `json:"gd$etag,omitempty"` - //Updated GD `json:"updated,omitempty"` - //Edited GD `json:"app$edited,omitempty"` - //Categories []Category `json:"category,omitempty"` - //Title GD `json:"title,omitempty"` - //Links []Link `json:"link,omitempty"` + // Ignored fields for speedup. + + // ID GD + // ETag string `json:"gd$etag,omitempty"` + // Updated GD `json:"updated,omitempty"` + // Edited GD `json:"app$edited,omitempty"` + // Categories []Category `json:"category,omitempty"` + // Title GD `json:"title,omitempty"` + // Links []Link `json:"link,omitempty"` Name Name `json:"gd$name,omitempty"` Birthday Birthday `json:"gContact$birthday,omitempty"` diff --git a/lib/contact/google/feed.go b/lib/contact/google/feed.go index c0ddcb3d..f547a12c 100644 --- a/lib/contact/google/feed.go +++ b/lib/contact/google/feed.go @@ -8,21 +8,23 @@ package google // // Some of the fields are disabled for speed. type Feed struct { - //XMLNS string `json:"xmlns,omitempty"` - //XMLNSOpenSearch string `json:"xmlns$openSearch,omitempty"` - //XMLNSGContact string `json:"xmlns$gContact,omitempty"` - //XMLNSBatch string `json:"xmlns$batch,omitempty"` - //XMLNSGD string `json:"xmlns$gd,omitempty"` - //GDEtag string `json:"gd$etag,omitempty"` - //Id GD `json:"id,omitempty"` - //Updated GD `json:"updated,omitempty"` - //Categories []Category `json:"category,omitempty"` - //Title GD `json:"title,omitempty"` - //Links []Link `json:"link,omitempty"` - //Authors []Author `json:"author,omitempty"` - //Generator Generator `json:"generator,omitempty"` - //StartIndex GD `json:"openSearch$startIndex,omitempty"` - //ItemsPerPage GD `json:"openSearch$itemsPerPage,omitempty"` + // Ignored fields for speedup. + + // XMLNS string `json:"xmlns,omitempty"` + // XMLNSOpenSearch string `json:"xmlns$openSearch,omitempty"` + // XMLNSGContact string `json:"xmlns$gContact,omitempty"` + // XMLNSBatch string `json:"xmlns$batch,omitempty"` + // XMLNSGD string `json:"xmlns$gd,omitempty"` + // GDEtag string `json:"gd$etag,omitempty"` + // Id GD `json:"id,omitempty"` + // Updated GD `json:"updated,omitempty"` + // Categories []Category `json:"category,omitempty"` + // Title GD `json:"title,omitempty"` + // Links []Link `json:"link,omitempty"` + // Authors []Author `json:"author,omitempty"` + // Generator Generator `json:"generator,omitempty"` + // StartIndex GD `json:"openSearch$startIndex,omitempty"` + // ItemsPerPage GD `json:"openSearch$itemsPerPage,omitempty"` TotalResult GD `json:"openSearch$totalResults,omitempty"` Contacts []Contact `json:"entry,omitempty"` diff --git a/lib/contact/google/google.go b/lib/contact/google/google.go index 3690359f..36030274 100644 --- a/lib/contact/google/google.go +++ b/lib/contact/google/google.go @@ -6,6 +6,7 @@ package google import ( + "context" "encoding/json" "io" "net/http" @@ -39,7 +40,12 @@ func ImportFromJSON(jsonb []byte) (contacts []*contact.Record, err error) { // ImportWithOAuth get Google contact API using OAuth HTTP client. func ImportWithOAuth(client *http.Client) (contacts []*contact.Record, err error) { - req, err := http.NewRequest(http.MethodGet, apiContactsURL, nil) + var ( + ctx = context.Background() + req *http.Request + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodGet, apiContactsURL, nil) if err != nil { return } diff --git a/lib/contact/microsoft/contact.go b/lib/contact/microsoft/contact.go index a85baf13..302eafb8 100644 --- a/lib/contact/microsoft/contact.go +++ b/lib/contact/microsoft/contact.go @@ -12,14 +12,16 @@ import ( // // Some of the fields are disabled for speed up. type Contact struct { - //ETag string `json:"@odata.etag,omitempty"` - //Id string `json:"id,omitempty"` - //Created string `json:"createdDateTime,omitempty"` - //LastModified string `json:"lastModifiedDateTime,omitempty"` - //ChangeKey string `json:"changeKey,omitempty"` - //Categories []string `json:"categories,omitempty"` - //ParentFolderID string `json:"parentFolderId,omitempty"` - //FileAs string `json:"fileAs,omitempty"` + // Ignored fields for speedup. + + // ETag string `json:"@odata.etag,omitempty"` + // Id string `json:"id,omitempty"` + // Created string `json:"createdDateTime,omitempty"` + // LastModified string `json:"lastModifiedDateTime,omitempty"` + // ChangeKey string `json:"changeKey,omitempty"` + // Categories []string `json:"categories,omitempty"` + // ParentFolderID string `json:"parentFolderId,omitempty"` + // FileAs string `json:"fileAs,omitempty"` Birthday string `json:"birthday,omitempty"` @@ -32,9 +34,11 @@ type Contact struct { Title string `json:"title,omitempty"` Generation string `json:"generation,omitempty"` - //YomiGivenName string `json:"yomiGivenName,omitempty"` - //YomiSurname string `json:"yomiSurname,omitempty"` - //YomiCompanyName string `json:"yomiCompanyName,omitempty"` + // Ignored fields for speedup. + + // YomiGivenName string `json:"yomiGivenName,omitempty"` + // YomiSurname string `json:"yomiSurname,omitempty"` + // YomiCompanyName string `json:"yomiCompanyName,omitempty"` JobTitle string `json:"jobTitle,omitempty"` Company string `json:"companyName,omitempty"` diff --git a/lib/contact/microsoft/microsoft.go b/lib/contact/microsoft/microsoft.go index 9928d8dd..b0a70065 100644 --- a/lib/contact/microsoft/microsoft.go +++ b/lib/contact/microsoft/microsoft.go @@ -10,6 +10,7 @@ package microsoft import ( + "context" "encoding/json" "io" "net/http" @@ -45,7 +46,12 @@ func ImportFromJSON(jsonb []byte) ( // ImportWithOAuth get Microsoft Live contacts using OAuth HTTP client. func ImportWithOAuth(client *http.Client) (contacts []*contact.Record, err error) { - req, err := http.NewRequest(http.MethodGet, apiContactsURL, nil) + var ( + ctx = context.Background() + req *http.Request + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodGet, apiContactsURL, nil) if err != nil { return } diff --git a/lib/contact/yahoo/contact.go b/lib/contact/yahoo/contact.go index 80a593b9..735cd4af 100644 --- a/lib/contact/yahoo/contact.go +++ b/lib/contact/yahoo/contact.go @@ -15,12 +15,13 @@ type Contact struct { Fields []Field `json:"fields"` // Ignored fields for speedup. - //ID int `json:"id"` - //IsConnection bool `json:"isConnection"` - //Error int `json:"error"` - //RestoredID int `json:"restoredId"` - //Categories []Category `json:"categories"` - //Meta + + // ID int `json:"id"` + // IsConnection bool `json:"isConnection"` + // Error int `json:"error"` + // RestoredID int `json:"restoredId"` + // Categories []Category `json:"categories"` + // Meta } // Decode will convert the interface value in each field into its struct diff --git a/lib/contact/yahoo/field.go b/lib/contact/yahoo/field.go index db04abc9..3c07c69b 100644 --- a/lib/contact/yahoo/field.go +++ b/lib/contact/yahoo/field.go @@ -30,10 +30,11 @@ type Field struct { Flags []string `json:"flags"` // Ignored fields for speedup. - //ID int `json:"id"` - //EditedBy string `json:"editedBy"` - //Categories []string `json:"categories"` - //Meta + + // ID int `json:"id"` + // EditedBy string `json:"editedBy"` + // Categories []string `json:"categories"` + // Meta } // getValueType will return the Go type of field's Value. diff --git a/lib/contact/yahoo/yahoo.go b/lib/contact/yahoo/yahoo.go index 46522758..d3cee4a6 100644 --- a/lib/contact/yahoo/yahoo.go +++ b/lib/contact/yahoo/yahoo.go @@ -10,6 +10,7 @@ package yahoo import ( + "context" "encoding/json" "io" "net/http" @@ -44,8 +45,13 @@ func ImportFromJSON(jsonb []byte) (contacts []*contact.Record, err error) { // ImportWithOAuth get Yahoo contacts using OAuth HTTP client. func ImportWithOAuth(client *http.Client, guid string) (contacts []*contact.Record, err error) { - api := apiContactsURL + guid + apiContactsSuffix - req, err := http.NewRequest(http.MethodGet, api, nil) + var ( + ctx = context.Background() + api = apiContactsURL + guid + apiContactsSuffix + req *http.Request + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodGet, api, nil) if err != nil { return } diff --git a/lib/crypto/crypto.go b/lib/crypto/crypto.go index 0cf3f484..b85b5266 100644 --- a/lib/crypto/crypto.go +++ b/lib/crypto/crypto.go @@ -39,7 +39,7 @@ var ErrStdinPassphrase = errors.New(`cannot read passhprase from stdin`) // List of environment variables reads when reading passphrase // interactively. const ( - envKeySSHAskpassRequire = `SSH_ASKPASS_REQUIRE` + envKeySSHAskpassRequire = `SSH_ASKPASS_REQUIRE` //nolint: gosec envKeySSHAskpass = `SSH_ASKPASS` envKeyDisplay = `DISPLAY` ) diff --git a/lib/dns/dns.go b/lib/dns/dns.go index 014cb587..219c5414 100644 --- a/lib/dns/dns.go +++ b/lib/dns/dns.go @@ -137,6 +137,4 @@ var rcodeNames = map[ResponseCode]string{ // timeNow return the current time. // This variable provides to help mocking the test that require time value. -var timeNow = func() time.Time { - return time.Now() -} +var timeNow = time.Now diff --git a/lib/dns/doh_client.go b/lib/dns/doh_client.go index a2414279..73d5ca59 100644 --- a/lib/dns/doh_client.go +++ b/lib/dns/doh_client.go @@ -8,6 +8,7 @@ import ( "bytes" "crypto/tls" "encoding/base64" + "errors" "fmt" "io" "net/http" @@ -43,8 +44,7 @@ func NewDoHClient(nameserver string, allowInsecure bool) (cl *DoHClient, err err } if nsURL.Scheme != "https" { - err = fmt.Errorf("DoH name server must be HTTPS") - return nil, err + return nil, errors.New(`DoH name server must be HTTPS`) } tr = &http.Transport{ @@ -96,7 +96,7 @@ func (cl *DoHClient) Close() error { // It will return an error if the Name is empty. func (cl *DoHClient) Lookup(q MessageQuestion, allowRecursion bool) (res *Message, err error) { if len(q.Name) == 0 { - return nil, fmt.Errorf("Lookup: empty question name") + return nil, errors.New(`Lookup: empty question name`) } if q.Type == 0 { q.Type = RecordTypeA diff --git a/lib/dns/dot_client.go b/lib/dns/dot_client.go index e4bfe24b..bd5e362e 100644 --- a/lib/dns/dot_client.go +++ b/lib/dns/dot_client.go @@ -6,6 +6,7 @@ package dns import ( "crypto/tls" + "errors" "fmt" "net" "time" @@ -67,7 +68,7 @@ func (cl *DoTClient) Close() error { // It will return an error if the Name is empty. func (cl *DoTClient) Lookup(q MessageQuestion, allowRecursion bool) (res *Message, err error) { if len(q.Name) == 0 { - return nil, fmt.Errorf("Lookup: empty question name") + return nil, errors.New(`Lookup: empty question name`) } if q.Type == 0 { q.Type = RecordTypeA diff --git a/lib/dns/funcs.go b/lib/dns/funcs.go index d18be454..9da1469e 100644 --- a/lib/dns/funcs.go +++ b/lib/dns/funcs.go @@ -6,6 +6,7 @@ package dns import ( "bytes" + "errors" "fmt" "net" @@ -58,7 +59,7 @@ func ParseNameServers(nameservers []string) (udpAddrs []*net.UDPAddr, err error) // without error. func LookupPTR(client Client, ip net.IP) (answer string, err error) { if ip == nil { - return "", fmt.Errorf("empty IP address") + return ``, errors.New(`empty IP address`) } var ( @@ -96,7 +97,7 @@ func LookupPTR(client Client, ip net.IP) (answer string, err error) { var ok bool answer, ok = rranswers[0].Value.(string) if !ok { - return "", fmt.Errorf("invalid PTR record data") + return ``, errors.New(`invalid PTR record data`) } return answer, nil diff --git a/lib/dns/hosts_file_example_test.go b/lib/dns/hosts_file_example_test.go index 9a25c814..5cd784cf 100644 --- a/lib/dns/hosts_file_example_test.go +++ b/lib/dns/hosts_file_example_test.go @@ -24,8 +24,8 @@ func ExampleHostsFile_Get() { fmt.Println(hostsFile.Get("my.local", "")) fmt.Println(hostsFile.Get("my.local", "127.0.0.2")) fmt.Println(hostsFile.Get("my.my", "")) - //Output: - //{Name:my.local Type:1 Class:0 TTL:0 Value:127.0.0.1} - //{Name:my.local Type:1 Class:0 TTL:0 Value:127.0.0.2} - //<nil> + // Output: + // {Name:my.local Type:1 Class:0 TTL:0 Value:127.0.0.1} + // {Name:my.local Type:1 Class:0 TTL:0 Value:127.0.0.2} + // <nil> } diff --git a/lib/dns/message.go b/lib/dns/message.go index e434d792..318d72fb 100644 --- a/lib/dns/message.go +++ b/lib/dns/message.go @@ -5,6 +5,7 @@ package dns import ( + "errors" "fmt" "net" "strconv" @@ -1013,7 +1014,7 @@ func (msg *Message) Unpack() (err error) { // message. func (msg *Message) UnpackHeaderQuestion() (err error) { if len(msg.packet) <= sectionHeaderSize { - return fmt.Errorf("UnpackHeaderQuestion: missing question") + return errors.New(`UnpackHeaderQuestion: missing question`) } msg.Header.unpack(msg.packet) diff --git a/lib/dns/rdata_hinfo.go b/lib/dns/rdata_hinfo.go index cb2e2638..0b9358e1 100644 --- a/lib/dns/rdata_hinfo.go +++ b/lib/dns/rdata_hinfo.go @@ -28,7 +28,7 @@ func (hinfo *RDataHINFO) unpack(packet []byte) error { ) x++ hinfo.CPU = libbytes.Copy(packet[x : x+size]) - x = x + size + x += size size = int(packet[x]) x++ hinfo.OS = libbytes.Copy(packet[x : x+size]) diff --git a/lib/dns/record_type_example_test.go b/lib/dns/record_type_example_test.go index 9d8e96d6..8ff3e2a1 100644 --- a/lib/dns/record_type_example_test.go +++ b/lib/dns/record_type_example_test.go @@ -9,17 +9,17 @@ import "fmt" func ExampleRecordType() { fmt.Println(RecordType(1)) // Known record type. fmt.Println(RecordType(17)) // Unregistered record type. - //Output: - //1 - //17 + // Output: + // 1 + // 17 } func ExampleRecordTypeFromAddress() { fmt.Println(RecordTypeFromAddress([]byte("127.0.0.1"))) fmt.Println(RecordTypeFromAddress([]byte("fc00::"))) fmt.Println(RecordTypeFromAddress([]byte("127"))) - //Output: - //1 - //28 - //0 + // Output: + // 1 + // 28 + // 0 } diff --git a/lib/dns/resource_record.go b/lib/dns/resource_record.go index 20945f41..bcbd95c7 100644 --- a/lib/dns/resource_record.go +++ b/lib/dns/resource_record.go @@ -284,7 +284,7 @@ func unpackDomainName(packet []byte, start uint) (name string, end uint, err err x++ } if !isJump { - end = end + uint(count) + end += uint(count) } } return out.String(), end, nil diff --git a/lib/dns/server.go b/lib/dns/server.go index 9da9d85e..fcf40cab 100644 --- a/lib/dns/server.go +++ b/lib/dns/server.go @@ -109,13 +109,13 @@ func NewServer(opts *ServerOptions) (srv *Server, err error) { udpAddr = opts.getUDPAddress() srv.udp, err = net.ListenUDP("udp", udpAddr) if err != nil { - return nil, fmt.Errorf("dns: error listening on UDP '%v': %s", udpAddr, err) + return nil, fmt.Errorf(`dns: error listening on UDP '%v': %w`, udpAddr, err) } tcpAddr = opts.getTCPAddress() srv.tcp, err = net.ListenTCP("tcp", tcpAddr) if err != nil { - return nil, fmt.Errorf("dns: error listening on TCP '%v': %s", tcpAddr, err) + return nil, fmt.Errorf(`dns: error listening on TCP '%v': %w`, tcpAddr, err) } if len(opts.TLSCertFile) > 0 && len(opts.TLSPrivateKey) > 0 { diff --git a/lib/dns/server_options.go b/lib/dns/server_options.go index 47eb3938..974f5cff 100644 --- a/lib/dns/server_options.go +++ b/lib/dns/server_options.go @@ -5,6 +5,7 @@ package dns import ( + "errors" "fmt" "log" "net" @@ -159,7 +160,7 @@ func (opts *ServerOptions) init() (err error) { opts.initNameServers() if len(opts.primaryUDP) == 0 && len(opts.primaryDoh) == 0 && len(opts.primaryDot) == 0 { - return fmt.Errorf("dns: no valid name servers") + return errors.New(`dns: no valid name servers`) } return nil diff --git a/lib/dns/tcp_client.go b/lib/dns/tcp_client.go index 27886b14..d047e864 100644 --- a/lib/dns/tcp_client.go +++ b/lib/dns/tcp_client.go @@ -5,6 +5,7 @@ package dns import ( + "errors" "fmt" "io" "net" @@ -83,10 +84,10 @@ func (cl *TCPClient) Connect(raddr *net.TCPAddr) (err error) { // or no connection, or Name is empty. func (cl *TCPClient) Lookup(q MessageQuestion, allowRecursion bool) (msg *Message, err error) { if cl.addr == nil || cl.conn == nil { - return nil, fmt.Errorf("Lookup: no name server or active connection") + return nil, errors.New(`Lookup: no name server or active connection`) } if len(q.Name) == 0 { - return nil, fmt.Errorf("Lookup: empty question name") + return nil, errors.New(`Lookup: empty question name`) } if q.Type == 0 { q.Type = RecordTypeA diff --git a/lib/dns/udp_client.go b/lib/dns/udp_client.go index 6819bc4c..9f3eeb11 100644 --- a/lib/dns/udp_client.go +++ b/lib/dns/udp_client.go @@ -5,6 +5,7 @@ package dns import ( + "errors" "fmt" "net" "sync" @@ -78,10 +79,10 @@ func (cl *UDPClient) Close() error { // or no connection, or Name is empty. func (cl *UDPClient) Lookup(q MessageQuestion, allowRecursion bool) (msg *Message, err error) { if cl.addr == nil || cl.conn == nil { - return nil, fmt.Errorf("Lookup: no name server or active connection") + return nil, errors.New(`Lookup: no name server or active connection`) } if len(q.Name) == 0 { - return nil, fmt.Errorf("Lookup: empty question name") + return nil, errors.New(`Lookup: empty question name`) } if q.Type == 0 { q.Type = RecordTypeA diff --git a/lib/dns/udp_client_pool.go b/lib/dns/udp_client_pool.go index 68dea82a..8eaee5df 100644 --- a/lib/dns/udp_client_pool.go +++ b/lib/dns/udp_client_pool.go @@ -69,14 +69,17 @@ func (ucp *UDPClientPool) newClient() interface{} { ) ucp.Lock() - defer ucp.Unlock() ucp.seq %= len(ucp.ns) cl, err = NewUDPClient(ucp.ns[ucp.seq]) if err != nil { + ucp.Unlock() log.Fatal("udp: UDPClientPool: cannot create new client: ", err) } ucp.seq++ + + ucp.Unlock() + return cl } diff --git a/lib/dns/zone.go b/lib/dns/zone.go index 281e9968..f2689447 100644 --- a/lib/dns/zone.go +++ b/lib/dns/zone.go @@ -252,12 +252,10 @@ func (zone *Zone) Remove(rr *ResourceRecord) (err error) { if rr.Type == RecordTypeSOA { zone.SOA = NewRDataSOA(zone.Origin, ``) - } else { - if zone.recordRemove(rr) { - err = zone.Save() - if err != nil { - return fmt.Errorf(`%s: %w`, logp, err) - } + } else if zone.recordRemove(rr) { + err = zone.Save() + if err != nil { + return fmt.Errorf(`%s: %w`, logp, err) } } zone.onUpdate() diff --git a/lib/dns/zone_parser.go b/lib/dns/zone_parser.go index 6cb1890c..6b477ba4 100644 --- a/lib/dns/zone_parser.go +++ b/lib/dns/zone_parser.go @@ -447,7 +447,7 @@ func (m *zoneParser) parseRR(prevRR *ResourceRecord, tok []byte) (rr *ResourceRe case flagRRType: err = m.parseRRData(rr, orgtok, c) if err != nil { - return nil, fmt.Errorf(`%s: line %d: %s`, logp, m.lineno, err) + return nil, fmt.Errorf(`%s: line %d: %w`, logp, m.lineno, err) } flag = flagRREnd } diff --git a/lib/dsv/common_test.go b/lib/dsv/common_test.go index 4d4a820d..8e43aa27 100644 --- a/lib/dsv/common_test.go +++ b/lib/dsv/common_test.go @@ -6,6 +6,7 @@ package dsv import ( "bytes" + "errors" "fmt" "io" "os" @@ -72,7 +73,7 @@ func doReadWrite(t *testing.T, dsvReader *Reader, dsvWriter *Writer, for { n, e := Read(dsvReader) - if e == io.EOF || n == 0 { + if errors.Is(e, io.EOF) || n == 0 { _, e = dsvWriter.Write(dsvReader) if e != nil { t.Fatal(e) diff --git a/lib/dsv/dsvinterface.go b/lib/dsv/dsvinterface.go index 54c063b9..048de4b7 100644 --- a/lib/dsv/dsvinterface.go +++ b/lib/dsv/dsvinterface.go @@ -5,6 +5,7 @@ package dsv import ( + "errors" "io" ) @@ -24,7 +25,7 @@ func SimpleRead(fcfg string, dataset interface{}) ( } _, e = Read(reader) - if e != nil && e != io.EOF { + if e != nil && !errors.Is(e, io.EOF) { return nil, e } diff --git a/lib/dsv/metadata.go b/lib/dsv/metadata.go index 626fa1ed..99b951ca 100644 --- a/lib/dsv/metadata.go +++ b/lib/dsv/metadata.go @@ -36,7 +36,7 @@ type Metadata struct { ValueSpace []string `json:"ValueSpace"` // T type of column in integer. - T int + T int `json:"T"` // Skip, if its true this column will be ignored, not saved in reader // object. Default to false. diff --git a/lib/dsv/reader_test.go b/lib/dsv/reader_test.go index a60f333e..5d48b552 100644 --- a/lib/dsv/reader_test.go +++ b/lib/dsv/reader_test.go @@ -5,6 +5,7 @@ package dsv import ( + "errors" "fmt" "io" "strings" @@ -207,8 +208,7 @@ func doRead(t *testing.T, dsvReader *Reader, exp []string) { test.Assert(t, "", exp[i], r) i++ - } else if e == io.EOF { - // EOF + } else if errors.Is(e, io.EOF) { break } } @@ -325,8 +325,7 @@ func TestReaderToColumns(t *testing.T) { test.Assert(t, "", expectation[i], r) i++ - } else if e == io.EOF { - // EOF + } else if errors.Is(e, io.EOF) { break } } @@ -357,7 +356,7 @@ func TestTransposeToColumns(t *testing.T) { _, e = Read(reader) - if e != io.EOF { + if !errors.Is(e, io.EOF) { t.Fatal(e) } @@ -387,7 +386,7 @@ func TestSortColumnsByIndex(t *testing.T) { reader.SetMaxRows(-1) _, e = Read(reader) - if e != io.EOF { + if !errors.Is(e, io.EOF) { t.Fatal(e) } @@ -433,7 +432,7 @@ func TestSplitRowsByValue(t *testing.T) { _, e = Read(reader) - if e != nil && e != io.EOF { + if e != nil && !errors.Is(e, io.EOF) { t.Fatal(e) } @@ -514,12 +513,12 @@ func TestMergeColumns(t *testing.T) { reader2.SetMaxRows(-1) _, e = Read(reader1) - if e != io.EOF { + if !errors.Is(e, io.EOF) { t.Fatal(e) } _, e = Read(reader2) - if e != io.EOF { + if !errors.Is(e, io.EOF) { t.Fatal(e) } @@ -558,12 +557,12 @@ func TestMergeRows(t *testing.T) { reader2.SetMaxRows(-1) _, e = Read(reader1) - if e != io.EOF { + if !errors.Is(e, io.EOF) { t.Fatal(e) } _, e = Read(reader2) - if e != io.EOF { + if !errors.Is(e, io.EOF) { t.Fatal(e) } diff --git a/lib/dsv/readerinterface.go b/lib/dsv/readerinterface.go index c6fa1cb6..736b999d 100644 --- a/lib/dsv/readerinterface.go +++ b/lib/dsv/readerinterface.go @@ -6,6 +6,7 @@ package dsv import ( "bytes" + "errors" "fmt" "io" "os" @@ -195,7 +196,7 @@ func parsingRightQuote(reader ReaderInterface, rq, line []byte, startAt int) ( N: 0, } - if e == io.EOF { + if errors.Is(e, io.EOF) { eRead.T &= EReadEOF } @@ -408,7 +409,7 @@ err: What: fmt.Sprint(e), } - if e == io.EOF { + if errors.Is(e, io.EOF) { eRead.T = EReadEOF } else { eRead.T = EReadLine diff --git a/lib/dsv/writer.go b/lib/dsv/writer.go index d429e6f3..1293a6c8 100644 --- a/lib/dsv/writer.go +++ b/lib/dsv/writer.go @@ -31,7 +31,7 @@ type Writer struct { fWriter *os.File // BufWriter for buffered writer. - BufWriter *bufio.Writer + BufWriter *bufio.Writer `json:"-"` Config `json:"-"` diff --git a/lib/email/dkim/parser.go b/lib/email/dkim/parser.go index ece104e8..a5523ba5 100644 --- a/lib/email/dkim/parser.go +++ b/lib/email/dkim/parser.go @@ -5,6 +5,7 @@ package dkim import ( + "errors" "fmt" libbytes "git.sr.ht/~shulhan/pakakeh.go/lib/bytes" @@ -60,7 +61,7 @@ func (p *parser) fetchTag() (t *tag, err error) { return nil, nil } if d != '=' { - return nil, fmt.Errorf(`dkim: missing '='`) + return nil, errors.New(`dkim: missing '='`) } t, err = newTag(token) diff --git a/lib/email/dkim/signature.go b/lib/email/dkim/signature.go index acb3a73f..b6f15bfb 100644 --- a/lib/email/dkim/signature.go +++ b/lib/email/dkim/signature.go @@ -269,7 +269,7 @@ func (sig *Signature) SetDefault() { // key and store the base64 result in Signature.Value ("b="). func (sig *Signature) Sign(pk *rsa.PrivateKey, hashHeader []byte) (err error) { if pk == nil { - return fmt.Errorf("email/dkim: empty private key for signing") + return errors.New(`email/dkim: empty private key for signing`) } cryptoHash := crypto.SHA256 @@ -360,10 +360,10 @@ func (sig *Signature) Validate() (err error) { // hash of message header. func (sig *Signature) Verify(key *Key, headerHash []byte) (err error) { if key == nil { - return fmt.Errorf("email/dkim: key record is empty") + return errors.New(`email/dkim: key record is empty`) } if key.RSA == nil { - return fmt.Errorf("email/dkim: public key is empty") + return errors.New(`email/dkim: public key is empty`) } sigValue := make([]byte, base64.StdEncoding.DecodedLen(len(sig.Value))) diff --git a/lib/email/header.go b/lib/email/header.go index 6c31d3d5..7c4db291 100644 --- a/lib/email/header.go +++ b/lib/email/header.go @@ -273,11 +273,12 @@ func (hdr *Header) WriteTo(w io.Writer) (n int64, err error) { m int ) for _, f = range hdr.fields { - if f.Type == FieldTypeContentType { + switch f.Type { + case FieldTypeContentType: m, err = fmt.Fprintf(w, "%s: %s\r\n", f.Name, f.contentType.String()) - } else if f.Type == FieldTypeMessageID { + case FieldTypeMessageID: m, err = fmt.Fprintf(w, "%s: <%s>\r\n", f.Name, f.oriValue) - } else { + default: m, err = fmt.Fprintf(w, "%s: %s", f.Name, f.Value) } if err != nil { diff --git a/lib/email/header_example_test.go b/lib/email/header_example_test.go index 5b3d27b6..e5a3f4d3 100644 --- a/lib/email/header_example_test.go +++ b/lib/email/header_example_test.go @@ -18,7 +18,7 @@ func ExampleHeader_Filter() { toAddresses = []byte("John <john@example.com>, Jane <jane@example.com>") subject = []byte(`Example subject`) bodyText = []byte(`Email body as plain text`) - bodyHtml = []byte(`Email body as <b>HTML</b>`) + bodyHTML = []byte(`Email body as <b>HTML</b>`) msg *email.Message err error @@ -29,7 +29,7 @@ func ExampleHeader_Filter() { toAddresses, subject, bodyText, - bodyHtml, + bodyHTML, ) if err != nil { log.Fatal(err) diff --git a/lib/email/mailbox.go b/lib/email/mailbox.go index 56c9efa8..5e574bd5 100644 --- a/lib/email/mailbox.go +++ b/lib/email/mailbox.go @@ -112,13 +112,15 @@ func ParseMailboxes(raw []byte) (mboxes []*Mailbox, err error) { token = bytes.TrimSpace(token) mbox = &Mailbox{} - if c == ':' { + + switch c { + case ':': // We are parsing group of mailbox. isGroup = true - } else if c == '<' { + case '<': mbox.isAngle = true mbox.Name = string(token) - } else if c == '@' { + case '@': if len(token) == 0 { return nil, fmt.Errorf(`%s: empty local`, logp) } diff --git a/lib/email/mailbox_example_test.go b/lib/email/mailbox_example_test.go index 60914af6..6b38a3fa 100644 --- a/lib/email/mailbox_example_test.go +++ b/lib/email/mailbox_example_test.go @@ -11,9 +11,9 @@ func ExampleParseMailbox() { fmt.Printf("%v\n", ParseMailbox([]byte("Name <domain>"))) fmt.Printf("%v\n", ParseMailbox([]byte("local@domain"))) fmt.Printf("%v\n", ParseMailbox([]byte("Name <local@domain>"))) - //Output: - //<nil> - //Name <@domain> - //<local@domain> - //Name <local@domain> + // Output: + // <nil> + // Name <@domain> + // <local@domain> + // Name <local@domain> } diff --git a/lib/email/maildir/folder.go b/lib/email/maildir/folder.go index 112e3331..fc550abf 100644 --- a/lib/email/maildir/folder.go +++ b/lib/email/maildir/folder.go @@ -188,19 +188,19 @@ func (folder *Folder) initDirs() (err error) { folder.dirCur = filepath.Join(folder.dir, maildirCur) err = os.Mkdir(folder.dirCur, 0700) if err != nil && !errors.Is(err, os.ErrExist) { - return fmt.Errorf(`%s: %s`, logp, err) + return fmt.Errorf(`%s: %w`, logp, err) } folder.dirNew = filepath.Join(folder.dir, maildirNew) err = os.Mkdir(folder.dirNew, 0700) if err != nil && !errors.Is(err, os.ErrExist) { - return fmt.Errorf(`%s: %s`, logp, err) + return fmt.Errorf(`%s: %w`, logp, err) } folder.dirTmp = filepath.Join(folder.dir, maildirTmp) err = os.Mkdir(folder.dirTmp, 0700) if err != nil && !errors.Is(err, os.ErrExist) { - return fmt.Errorf(`%s: %s`, logp, err) + return fmt.Errorf(`%s: %w`, logp, err) } return nil @@ -229,16 +229,16 @@ func checkDir(dir string) (err error) { func sanitizeFolderName(name string) (out string, err error) { out = strings.TrimSpace(name) if len(out) == 0 { - return ``, fmt.Errorf(`folder name is empty`) + return ``, errors.New(`folder name is empty`) } if len(out) == 1 && out[0] == '.' { - return ``, fmt.Errorf(`folder name is empty`) + return ``, errors.New(`folder name is empty`) } if out[0] != '.' { - return ``, fmt.Errorf(`folder name must begin with period`) + return ``, errors.New(`folder name must begin with period`) } if out[1] == '.' { - return ``, fmt.Errorf(`folder name must not begin with ".."`) + return ``, errors.New(`folder name must not begin with ".."`) } var r rune for _, r = range out { @@ -246,7 +246,7 @@ func sanitizeFolderName(name string) (out string, err error) { return ``, fmt.Errorf(`folder name contains unprintable character %q`, r) } if r == '/' { - return ``, fmt.Errorf(`folder name must not contains slash '/'`) + return ``, errors.New(`folder name must not contains slash '/'`) } } return out, nil diff --git a/lib/email/maildir/folder_test.go b/lib/email/maildir/folder_test.go index 2e1b9a3f..7718f12f 100644 --- a/lib/email/maildir/folder_test.go +++ b/lib/email/maildir/folder_test.go @@ -298,15 +298,15 @@ func assertFolder(t *testing.T, folder *Folder) { var err error _, err = os.Stat(folder.dirCur) - if err != err { + if err != nil { t.Fatalf(`want %s, got %s`, folder.dirCur, err) } _, err = os.Stat(folder.dirNew) - if err != err { + if err != nil { t.Fatalf(`want %s, got %s`, folder.dirNew, err) } _, err = os.Stat(folder.dirTmp) - if err != err { + if err != nil { t.Fatalf(`want %s, got %s`, folder.dirTmp, err) } diff --git a/lib/email/message.go b/lib/email/message.go index 9c888f89..86075091 100644 --- a/lib/email/message.go +++ b/lib/email/message.go @@ -7,6 +7,7 @@ package email import ( "bytes" "crypto/rsa" + "errors" "fmt" "os" "strings" @@ -88,7 +89,7 @@ func NewMultipart(from, to, subject, bodyText, bodyHTML []byte) ( func ParseFile(inFile string) (msg *Message, rest []byte, err error) { raw, err := os.ReadFile(inFile) if err != nil { - return nil, nil, fmt.Errorf("email: " + err.Error()) + return nil, nil, fmt.Errorf(`email: %w`, err) } return ParseMessage(raw) @@ -162,10 +163,10 @@ func (msg *Message) addMailboxes(ft FieldType, mailboxes []byte) error { // already encoded. func (msg *Message) DKIMSign(pk *rsa.PrivateKey, sig *dkim.Signature) (err error) { if pk == nil { - return fmt.Errorf("email: empty private key for signing") + return errors.New(`email: empty private key for signing`) } if sig == nil { - return fmt.Errorf("email: empty signature for signing") + return errors.New(`email: empty signature for signing`) } sig.SetDefault() @@ -260,7 +261,7 @@ func (msg *Message) DKIMVerify() (*dkim.Status, error) { from := subHeader.Filter(FieldTypeFrom) if len(from) == 0 { msg.dkimStatus.Type = dkim.StatusPermFail - msg.dkimStatus.Error = fmt.Errorf("email: missing 'From' field") + msg.dkimStatus.Error = errors.New(`email: missing 'From' field`) return msg.dkimStatus, msg.dkimStatus.Error } @@ -283,7 +284,7 @@ func (msg *Message) DKIMVerify() (*dkim.Status, error) { _, bh64 := sig.Hash(canonBody) if !bytes.Equal(sig.BodyHash, bh64) { - err = fmt.Errorf("email: body hash did not verify") + err = errors.New(`email: body hash did not verify`) msg.dkimStatus.Type = dkim.StatusPermFail msg.dkimStatus.Error = err return nil, err diff --git a/lib/errors/errors_example_test.go b/lib/errors/errors_example_test.go index ec5a6eb7..c630fd40 100644 --- a/lib/errors/errors_example_test.go +++ b/lib/errors/errors_example_test.go @@ -22,13 +22,13 @@ func ExampleE_Is() { Message: `resource not found`, } - rawJson = `{"code":400,"name":"ERR_NOT_FOUND","message":"file not found"}` + rawJSON = `{"code":400,"name":"ERR_NOT_FOUND","message":"file not found"}` e *liberrors.E err error ) - err = json.Unmarshal([]byte(rawJson), &e) + err = json.Unmarshal([]byte(rawJSON), &e) if err != nil { log.Fatal(err) } diff --git a/lib/floats64/floats64.go b/lib/floats64/floats64.go index ea86ebdb..397e9a89 100644 --- a/lib/floats64/floats64.go +++ b/lib/floats64/floats64.go @@ -251,9 +251,7 @@ func Swap(d []float64, x, y int) { if x == y || len(d) <= 1 || x > len(d) || y > len(d) { return } - tmp := d[x] - d[x] = d[y] - d[y] = tmp + d[x], d[y] = d[y], d[x] } // Let `x` be the first index of left-side, `y` be the first index of diff --git a/lib/floats64/floats64_test.go b/lib/floats64/floats64_test.go index 84052a67..15d5e2c2 100644 --- a/lib/floats64/floats64_test.go +++ b/lib/floats64/floats64_test.go @@ -175,9 +175,7 @@ func TestSwap(t *testing.T) { Swap(in, 0, len(in)-1) - tmp := exp[0] - exp[0] = exp[len(exp)-1] - exp[len(exp)-1] = tmp + exp[0], exp[len(exp)-1] = exp[len(exp)-1], exp[0] test.Assert(t, "", exp, in) } diff --git a/lib/git/git.go b/lib/git/git.go index af93bb56..0f73b2b7 100644 --- a/lib/git/git.go +++ b/lib/git/git.go @@ -7,6 +7,7 @@ package git import ( "bytes" + "errors" "fmt" "io" "os" @@ -166,10 +167,10 @@ func GetRemoteURL(repoDir, remoteName string) (url string, err error) { url, ok := gitIni.Get("remote", remoteName, "url", "") if !ok { - err = fmt.Errorf("GetRemote: Empty or invalid remote name") + return ``, errors.New(`GetRemote: Empty or invalid remote name`) } - return + return url, nil } // GetTag get the tag from revision. If revision is empty it's default to diff --git a/lib/http/client.go b/lib/http/client.go index 9b59fa6d..2f9c4336 100644 --- a/lib/http/client.go +++ b/lib/http/client.go @@ -10,6 +10,7 @@ import ( "compress/flate" "compress/gzip" "compress/lzw" + "context" "crypto/tls" "encoding/json" "errors" @@ -262,9 +263,12 @@ func (client *Client) GenerateHTTPRequest( } rpath = path.Join(`/`, rpath) - var fullURL = client.opts.ServerURL + rpath + var ( + fullURL = client.opts.ServerURL + rpath + ctx = context.Background() + ) - req, err = http.NewRequest(method.String(), fullURL, body) + req, err = http.NewRequestWithContext(ctx, method.String(), fullURL, body) if err != nil { return nil, fmt.Errorf("%s: %w", logp, err) } @@ -426,9 +430,15 @@ func (client *Client) doRequest( res *http.Response, resBody []byte, err error, ) { rpath = path.Join(`/`, rpath) - var fullURL = client.opts.ServerURL + rpath - httpReq, err := http.NewRequest(httpMethod, fullURL, body) + var ( + fullURL = client.opts.ServerURL + rpath + ctx = context.Background() + + httpReq *http.Request + ) + + httpReq, err = http.NewRequestWithContext(ctx, httpMethod, fullURL, body) if err != nil { return nil, nil, err } @@ -542,11 +552,11 @@ func (client *Client) uncompress(res *http.Response, body []byte) ( // GenerateFormData generate multipart/form-data body from params. func GenerateFormData(params map[string][]byte) (contentType, body string, err error) { var ( - sb = new(strings.Builder) - w = multipart.NewWriter(sb) + sb = new(strings.Builder) + w = multipart.NewWriter(sb) + listKey = make([]string, 0, len(params)) - k string - listKey []string + k string ) for k = range params { listKey = append(listKey, k) diff --git a/lib/http/client_request.go b/lib/http/client_request.go index a1a2d7ec..42b330de 100644 --- a/lib/http/client_request.go +++ b/lib/http/client_request.go @@ -6,6 +6,7 @@ package http import ( "bytes" + "context" "encoding/json" "fmt" "io" @@ -131,7 +132,9 @@ func (creq *ClientRequest) toHTTPRequest(client *Client) (httpReq *http.Request, } } - httpReq, err = http.NewRequest(creq.Method.String(), path.String(), body) + var ctx = context.Background() + + httpReq, err = http.NewRequestWithContext(ctx, creq.Method.String(), path.String(), body) if err != nil { return nil, fmt.Errorf("%s: %w", logp, err) } diff --git a/lib/http/client_test.go b/lib/http/client_test.go index b92b3b11..56ff4333 100644 --- a/lib/http/client_test.go +++ b/lib/http/client_test.go @@ -44,7 +44,7 @@ func TestClient_Download(t *testing.T) { }, Output: &out, }, - expError: fmt.Sprintf("%s: 404 Not Found", logp), + expError: logp + `: 404 Not Found`, }, { desc: "With redirect", req: DownloadRequest{ @@ -82,7 +82,7 @@ func TestClient_Download(t *testing.T) { for _, c := range cases { out.Reset() - _, err = client.Download(c.req) + _, err = client.Download(c.req) //nolint: bodyclose if err != nil { test.Assert(t, c.desc+`: error`, c.expError, err.Error()) continue diff --git a/lib/http/endpoint_example_test.go b/lib/http/endpoint_example_test.go index 6cf9b515..2ca02de3 100644 --- a/lib/http/endpoint_example_test.go +++ b/lib/http/endpoint_example_test.go @@ -5,6 +5,7 @@ package http import ( + "errors" "fmt" "log" "net/http" @@ -26,7 +27,7 @@ func ExampleEndpoint_errorHandler() { RequestType: RequestTypeQuery, ResponseType: ResponseTypePlain, Call: func(epr *EndpointRequest) ([]byte, error) { - return nil, fmt.Errorf(epr.HTTPRequest.Form.Get(`error`)) + return nil, errors.New(epr.HTTPRequest.Form.Get(`error`)) }, ErrorHandler: func(epr *EndpointRequest) { epr.HTTPWriter.Header().Set(HeaderContentType, ContentTypePlain) @@ -59,16 +60,18 @@ func ExampleEndpoint_errorHandler() { params := url.Values{} params.Set("error", "400:error with status code") - httpres, resbody, err := client.Get(`/`, nil, params) + httpres, resbody, err := client.Get(`/`, nil, params) //nolint: bodyclose if err != nil { - log.Fatal(err) + log.Println(err) + return } fmt.Printf("%d: %s\n", httpres.StatusCode, resbody) params.Set("error", "error without status code") - httpres, resbody, err = client.Get(`/`, nil, params) + httpres, resbody, err = client.Get(`/`, nil, params) //nolint: bodyclose if err != nil { - log.Fatal(err) + log.Println(err) + return } fmt.Printf("%d: %s\n", httpres.StatusCode, resbody) diff --git a/lib/http/endpoint_response_example_test.go b/lib/http/endpoint_response_example_test.go index 1fab11a4..e9944edb 100644 --- a/lib/http/endpoint_response_example_test.go +++ b/lib/http/endpoint_response_example_test.go @@ -74,7 +74,7 @@ func ExampleEndpointResponse() { params := url.Values{} // Test call endpoint without "id" parameter. - _, resBody, err := cl.Get("/", nil, params) + _, resBody, err := cl.Get("/", nil, params) //nolint: bodyclose if err != nil { log.Fatal(err) } @@ -83,7 +83,7 @@ func ExampleEndpointResponse() { // Test call endpoint with "id" parameter set to "0", it should return // HTTP status 500 with custom message. params.Set("id", "0") - _, resBody, err = cl.Get("/", nil, params) + _, resBody, err = cl.Get("/", nil, params) //nolint: bodyclose if err != nil { log.Fatal(err) } @@ -91,7 +91,7 @@ func ExampleEndpointResponse() { // Test with "id" parameter is set. params.Set("id", "1000") - _, resBody, err = cl.Get("/", nil, params) + _, resBody, err = cl.Get("/", nil, params) //nolint: bodyclose if err != nil { log.Fatal(err) } diff --git a/lib/http/example_server_test.go b/lib/http/example_server_test.go index c9575172..74a60f2a 100644 --- a/lib/http/example_server_test.go +++ b/lib/http/example_server_test.go @@ -60,7 +60,8 @@ func ExampleServer_customHTTPStatusCode() { err = srv.registerPost(epCustom) if err != nil { - log.Fatal(err) + log.Println(err) + return } // Wait for the server fully started. @@ -71,9 +72,10 @@ func ExampleServer_customHTTPStatusCode() { } client := NewClient(clientOpts) - httpRes, resBody, err := client.PostJSON(epCustom.Path, nil, nil) + httpRes, resBody, err := client.PostJSON(epCustom.Path, nil, nil) //nolint: bodyclose if err != nil { - log.Fatal(err) + log.Println(err) + return } fmt.Printf("%d\n", httpRes.StatusCode) diff --git a/lib/http/form.go b/lib/http/form.go index 329d0557..824a683b 100644 --- a/lib/http/form.go +++ b/lib/http/form.go @@ -190,10 +190,8 @@ func UnmarshalForm(in url.Values, out interface{}) (err error) { } else { vout = vout.Elem() } - } else { - if rkind != reflect.Struct { - return fmt.Errorf("%s: expecting *T or **T got %T", logp, out) - } + } else if rkind != reflect.Struct { + return fmt.Errorf(`%s: expecting *T or **T got %T`, logp, out) } listFields = reflect.VisibleFields(rtype) diff --git a/lib/http/form_example_test.go b/lib/http/form_example_test.go index 02f89c4d..50994fa4 100644 --- a/lib/http/form_example_test.go +++ b/lib/http/form_example_test.go @@ -42,8 +42,8 @@ func ExampleMarshalForm() { fmt.Println(out.Encode()) - //Output: - //Bool=true&Int=1&big.Rat=1.2345&bytes=bytes&f32=3.2&f64=6.4¬set=0&string=a_string&uint8=2 + // Output: + // Bool=true&Int=1&big.Rat=1.2345&bytes=bytes&f32=3.2&f64=6.4¬set=0&string=a_string&uint8=2 } func ExampleUnmarshalForm() { @@ -90,9 +90,9 @@ func ExampleUnmarshalForm() { fmt.Printf("%+v\n", ptrOut) } - //Output: - //{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true} - //&{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true} + // Output: + // {Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true} + // &{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true} } func ExampleUnmarshalForm_error() { @@ -133,10 +133,10 @@ func ExampleUnmarshalForm_error() { fmt.Println(out) } - //Output: - //UnmarshalForm: expecting *T got http.T - //UnmarshalForm: *http.T is not initialized - //{0} + // Output: + // UnmarshalForm: expecting *T got http.T + // UnmarshalForm: *http.T is not initialized + // {0} } @@ -176,9 +176,9 @@ func ExampleUnmarshalForm_slice() { fmt.Printf("%+v\n", ptrSliceOut) } - //Output: - //{NotSlice:first SliceString:[multi value] SliceInt:[123 456]} - //&{NotSlice:first SliceString:[multi value] SliceInt:[123 456]} + // Output: + // {NotSlice:first SliceString:[multi value] SliceInt:[123 456]} + // &{NotSlice:first SliceString:[multi value] SliceInt:[123 456]} } func ExampleUnmarshalForm_zero() { @@ -232,7 +232,7 @@ func ExampleUnmarshalForm_zero() { fmt.Printf("%+v\n", out) } - //Output: - //{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true} - //{Rat:0 String: Bytes:[] Int:0 F64:0 F32:0 NotSet:0 Uint8:0 Bool:false} + // Output: + // {Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true} + // {Rat:0 String: Bytes:[] Int:0 F64:0 F32:0 NotSet:0 Uint8:0 Bool:false} } diff --git a/lib/http/http_test.go b/lib/http/http_test.go index 47c03894..21e22216 100644 --- a/lib/http/http_test.go +++ b/lib/http/http_test.go @@ -68,7 +68,7 @@ func TestMain(m *testing.M) { Address: serverAddress, } - testServerURL = fmt.Sprintf("http://" + serverAddress) + testServerURL = `http://` + serverAddress testServer, err = NewServer(opts) if err != nil { @@ -166,7 +166,8 @@ func registerEndpoints() { // skip certain header keys. func dumpHTTPResponse(httpRes *http.Response, skipHeaders []string) string { var ( - keys []string + keys = make([]string, 0, len(httpRes.Header)) + hkey string ) for hkey = range httpRes.Header { diff --git a/lib/http/range.go b/lib/http/range.go index 3292ccb0..03a7d484 100644 --- a/lib/http/range.go +++ b/lib/http/range.go @@ -214,15 +214,16 @@ func (r *Range) Add(start, end *int64) bool { if start == nil && end == nil { return false } - if start == nil { + switch { + case start == nil: if *end <= 0 { return false } - } else if end == nil { + case end == nil: if *start < 0 { return false } - } else { + default: if *start < 0 || *end < 0 || *end < *start { return false } diff --git a/lib/http/response.go b/lib/http/response.go index c46972ee..9525799d 100644 --- a/lib/http/response.go +++ b/lib/http/response.go @@ -6,6 +6,7 @@ package http import ( "bytes" + "errors" "fmt" "net/http" "strconv" @@ -22,7 +23,7 @@ func ParseResponseHeader(raw []byte) (resp *http.Response, rest []byte, err erro // The minimum HTTP response without header is 16 bytes: // "HTTP/X.X" SP 3DIGITS CRLF CRLF if len(raw) < 16 { - return nil, raw, fmt.Errorf("http: invalid response header length") + return nil, raw, errors.New(`http: invalid response header length`) } // The HTTP-name is case sensitive: "HTTP". if !bytes.Equal(raw[:4], []byte("HTTP")) { @@ -36,7 +37,7 @@ func ParseResponseHeader(raw []byte) (resp *http.Response, rest []byte, err erro } ilf := bytes.Index(raw, []byte{'\n'}) if ilf < 0 || raw[ilf-1] != '\r' { - return nil, raw, fmt.Errorf("http: missing CRLF on status line") + return nil, raw, errors.New(`http: missing CRLF on status line`) } resp = &http.Response{ @@ -55,7 +56,7 @@ func ParseResponseHeader(raw []byte) (resp *http.Response, rest []byte, err erro resp.StatusCode, err = strconv.Atoi(string(raw[9:12])) if err != nil { - return nil, raw, fmt.Errorf("http: status code: " + err.Error()) + return nil, raw, fmt.Errorf(`http: status code: %w`, err) } if resp.StatusCode < 100 || resp.StatusCode >= 600 { return nil, raw, fmt.Errorf("http: invalid status code '%s'", raw[9:12]) @@ -87,7 +88,7 @@ func parseHeaders(raw []byte) (header http.Header, rest []byte, err error) { for len(rest) > 0 { switch len(rest) { case 1: - return nil, rest, fmt.Errorf(`http: missing CRLF at the end`) + return nil, rest, errors.New(`http: missing CRLF at the end`) default: if rest[0] == '\r' && rest[1] == '\n' { rest = rest[2:] @@ -105,10 +106,10 @@ func parseHeaders(raw []byte) (header http.Header, rest []byte, err error) { tok, c = parser.Read() if c != '\n' { - return nil, nil, fmt.Errorf(`http: missing CRLF at the end of field line`) + return nil, nil, errors.New(`http: missing CRLF at the end of field line`) } if tok[len(tok)-1] != '\r' { - return nil, nil, fmt.Errorf(`http: missing CR at the end of line`) + return nil, nil, errors.New(`http: missing CR at the end of line`) } tok = bytes.TrimSpace(tok) diff --git a/lib/http/response_test.go b/lib/http/response_test.go index bd9ccbd8..5f1c55bf 100644 --- a/lib/http/response_test.go +++ b/lib/http/response_test.go @@ -103,7 +103,7 @@ func TestParseResponseHeader(t *testing.T) { for _, c := range cases { t.Log(c.desc) - got, rest, err := ParseResponseHeader([]byte(c.raw)) + got, rest, err := ParseResponseHeader([]byte(c.raw)) //nolint: bodyclose if err != nil { test.Assert(t, "error", c.expErr, err.Error()) continue diff --git a/lib/http/server.go b/lib/http/server.go index 4d9a627f..a1695a36 100644 --- a/lib/http/server.go +++ b/lib/http/server.go @@ -100,12 +100,12 @@ func (srv *Server) RegisterEndpoint(ep *Endpoint) (err error) { return nil } if ep.Call == nil { - return fmt.Errorf("http.RegisterEndpoint: empty Call field") + return errors.New(`http.RegisterEndpoint: empty Call field`) } switch ep.Method { case RequestMethodConnect: - return fmt.Errorf("http.RegisterEndpoint: can't handle CONNECT method yet") + return errors.New(`http.RegisterEndpoint: can't handle CONNECT method yet`) case RequestMethodDelete: err = srv.registerDelete(ep) case RequestMethodHead: @@ -119,7 +119,7 @@ func (srv *Server) RegisterEndpoint(ep *Endpoint) (err error) { case RequestMethodPut: err = srv.registerPut(ep) case RequestMethodTrace: - return fmt.Errorf("http.RegisterEndpoint: can't handle TRACE method yet") + return errors.New(`http.RegisterEndpoint: can't handle TRACE method yet`) default: ep.Method = RequestMethodGet err = srv.registerGet(ep) diff --git a/lib/http/server_test.go b/lib/http/server_test.go index 4d573540..eee0144c 100644 --- a/lib/http/server_test.go +++ b/lib/http/server_test.go @@ -6,8 +6,8 @@ package http import ( "bytes" + "context" "errors" - "fmt" "io" "log" "mime" @@ -136,7 +136,7 @@ func TestRegisterDelete(t *testing.T) { for _, c := range cases { t.Log(c.desc) - err := testServer.RegisterEndpoint(c.ep) + var err = testServer.RegisterEndpoint(c.ep) if err != nil { if !errors.Is(ErrEndpointAmbiguous, err) { test.Assert(t, "error", c.expError, err.Error()) @@ -148,9 +148,14 @@ func TestRegisterDelete(t *testing.T) { continue } - req, e := http.NewRequest(http.MethodDelete, c.reqURL, nil) - if e != nil { - t.Fatal(e) + var ( + ctx = context.Background() + req *http.Request + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodDelete, c.reqURL, nil) + if err != nil { + t.Fatal(err) } res, e := client.Do(req) @@ -228,9 +233,15 @@ func TestRegisterEvaluator(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, e := http.NewRequest(http.MethodDelete, c.reqURL, nil) - if e != nil { - t.Fatal(e) + var ( + ctx = context.Background() + req *http.Request + err error + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodDelete, c.reqURL, nil) + if err != nil { + t.Fatal(err) } res, e := client.Do(req) @@ -298,9 +309,15 @@ func TestRegisterGet(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, e := http.NewRequest(http.MethodGet, c.reqURL, nil) - if e != nil { - t.Fatal(e) + var ( + ctx = context.Background() + req *http.Request + err error + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodGet, c.reqURL, nil) + if err != nil { + t.Fatal(err) } res, e := client.Do(req) @@ -365,9 +382,15 @@ func TestRegisterHead(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, e := http.NewRequest(http.MethodHead, c.reqURL, nil) - if e != nil { - t.Fatal(e) + var ( + ctx = context.Background() + req *http.Request + err error + ) + + req, err = http.NewRequestWithContext(ctx, http.MethodHead, c.reqURL, nil) + if err != nil { + t.Fatal(err) } res, e := client.Do(req) @@ -431,7 +454,9 @@ func TestRegisterPatch(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, e := http.NewRequest(http.MethodPatch, c.reqURL, nil) + var ctx = context.Background() + + req, e := http.NewRequestWithContext(ctx, http.MethodPatch, c.reqURL, nil) if e != nil { t.Fatal(e) } @@ -503,7 +528,9 @@ k=vv`, var buf bytes.Buffer _, _ = buf.WriteString(c.reqBody) - req, e := http.NewRequest(http.MethodPost, c.reqURL, &buf) + var ctx = context.Background() + + req, e := http.NewRequestWithContext(ctx, http.MethodPost, c.reqURL, &buf) if e != nil { t.Fatal(e) } @@ -566,7 +593,9 @@ func TestRegisterPut(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, e := http.NewRequest(http.MethodPut, c.reqURL, nil) + var ctx = context.Background() + + req, e := http.NewRequestWithContext(ctx, http.MethodPut, c.reqURL, nil) if e != nil { t.Fatal(e) } @@ -643,7 +672,9 @@ func TestServeHTTPOptions(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, err := http.NewRequest(http.MethodOptions, c.reqURL, nil) + var ctx = context.Background() + + req, err := http.NewRequestWithContext(ctx, http.MethodOptions, c.reqURL, nil) if err != nil { t.Fatal(err) } @@ -652,6 +683,7 @@ func TestServeHTTPOptions(t *testing.T) { if err != nil { t.Fatal(err) } + _ = res.Body.Close() gotAllow := res.Header.Get("Allow") @@ -672,7 +704,7 @@ func TestStatusError(t *testing.T) { return nil, liberrors.Internal(nil) } cbCustomErr = func(_ *EndpointRequest) ([]byte, error) { - return nil, fmt.Errorf("Custom error") + return nil, errors.New(`Custom error`) } err error @@ -796,7 +828,9 @@ func TestStatusError(t *testing.T) { for _, c := range cases { t.Log(c.desc) - req, e := http.NewRequest(http.MethodPost, c.reqURL, nil) + var ctx = context.Background() + + req, e := http.NewRequestWithContext(ctx, http.MethodPost, c.reqURL, nil) if e != nil { t.Fatal(e) } @@ -882,7 +916,9 @@ func TestServer_Options_HandleFS(t *testing.T) { }} for _, c = range cases { - req, err = http.NewRequest(http.MethodGet, testServerURL+c.reqPath, nil) + var ctx = context.Background() + + req, err = http.NewRequestWithContext(ctx, http.MethodGet, testServerURL+c.reqPath, nil) if err != nil { t.Fatalf("%s: %s", c.desc, err) } @@ -902,6 +938,10 @@ func TestServer_Options_HandleFS(t *testing.T) { if err != nil { t.Fatalf("%s: %s", c.desc, err) } + err = res.Body.Close() + if err != nil { + t.Fatalf("%s: %s", c.desc, err) + } test.Assert(t, "response body", c.expResBody, string(gotBody)) } @@ -937,7 +977,7 @@ func TestServer_handleRange(t *testing.T) { header.Set(HeaderRange, string(headerRange)) - httpRes, resBody, err = cl.Get(`/index.html`, header, nil) + httpRes, resBody, err = cl.Get(`/index.html`, header, nil) //nolint: bodyclose if err != nil { t.Fatal(err) } @@ -999,9 +1039,24 @@ func TestServer_handleRange_HEAD(t *testing.T) { t.Fatal(err) } + var ( + ctx = context.Background() + url = testServerURL + `/index.html` + httpReq *http.Request + ) + + httpReq, err = http.NewRequestWithContext(ctx, http.MethodHead, url, nil) + if err != nil { + t.Fatal(err) + } + var httpRes *http.Response - httpRes, err = cl.Client.Head(testServerURL + `/index.html`) + httpRes, err = cl.Client.Do(httpReq) + if err != nil { + t.Fatal(err) + } + err = httpRes.Body.Close() if err != nil { t.Fatal(err) } @@ -1090,7 +1145,7 @@ func TestServerHandleRangeBig(t *testing.T) { resBody []byte ) - httpRes, resBody, err = cl.Head(pathBig, nil, nil) + httpRes, resBody, err = cl.Head(pathBig, nil, nil) //nolint: bodyclose if err != nil { t.Fatal(err) } @@ -1106,7 +1161,7 @@ func TestServerHandleRangeBig(t *testing.T) { headers.Set(HeaderRange, `bytes=0-`) - httpRes, resBody, err = cl.Get(pathBig, headers, nil) + httpRes, resBody, err = cl.Get(pathBig, headers, nil) //nolint: bodyclose if err != nil { t.Fatal(err) } diff --git a/lib/http/sseclient/sseclient.go b/lib/http/sseclient/sseclient.go index 04cd1bbf..a9004005 100644 --- a/lib/http/sseclient/sseclient.go +++ b/lib/http/sseclient/sseclient.go @@ -227,7 +227,7 @@ func (cl *Client) handshake() (packet []byte, err error) { var httpRes *http.Response - httpRes, packet, err = libhttp.ParseResponseHeader(packet) + httpRes, packet, err = libhttp.ParseResponseHeader(packet) //nolint: bodyclose if err != nil { return nil, err } diff --git a/lib/hunspell/dictionary.go b/lib/hunspell/dictionary.go index 243f2349..b8a531e2 100644 --- a/lib/hunspell/dictionary.go +++ b/lib/hunspell/dictionary.go @@ -5,6 +5,7 @@ package hunspell import ( + "errors" "fmt" "log" "os" @@ -40,7 +41,7 @@ func (dict *dictionary) load(content string, opts *affixOptions) (err error) { // The string splitted into lines and then parsed one by one. lines := p.Lines() if len(lines) == 0 { - return fmt.Errorf("empty file") + return errors.New(`empty file`) } // The first line is approximately number of words. diff --git a/lib/hunspell/options.go b/lib/hunspell/options.go index a12c7cfc..9712a678 100644 --- a/lib/hunspell/options.go +++ b/lib/hunspell/options.go @@ -5,6 +5,7 @@ package hunspell import ( + "errors" "fmt" "log" "os" @@ -597,7 +598,7 @@ func (opts *affixOptions) parseAM(args []string) (err error) { func (opts *affixOptions) parseRep(args []string) (err error) { if cap(opts.reps) == 0 { if len(args) != 1 { - return fmt.Errorf("REP: missing number of replacement") + return errors.New(`REP: missing number of replacement`) } n, err := strconv.Atoi(args[0]) @@ -608,7 +609,7 @@ func (opts *affixOptions) parseRep(args []string) (err error) { opts.reps = make([]replacement, 0, n) } else { if len(args) != 2 { - return fmt.Errorf("REP: invalid arguments") + return errors.New(`REP: invalid arguments`) } rep, err := newReplacement(args[0], args[1]) @@ -683,7 +684,7 @@ func (opts *affixOptions) parseBreak(arg string) (err error) { arg = arg[:len(arg)-1] } if len(arg) == 0 { - return fmt.Errorf("BREAK: empty character sequences") + return errors.New(`BREAK: empty character sequences`) } breakrole.token = arg diff --git a/lib/hunspell/tests/all_test.go b/lib/hunspell/tests/all_test.go index ab9dd6fd..43d21b28 100644 --- a/lib/hunspell/tests/all_test.go +++ b/lib/hunspell/tests/all_test.go @@ -8,7 +8,6 @@ package tests import ( "errors" "os" - "path/filepath" "testing" "git.sr.ht/~shulhan/pakakeh.go/lib/hunspell" @@ -28,10 +27,12 @@ func TestHunspell(t *testing.T) { for _, file := range testFiles { t.Logf("test file: %s", file) - affFile := filepath.Join(file + ".aff") - dicFile := filepath.Join(file + ".dic") - goodFile := filepath.Join(file + ".good") - morphFile := filepath.Join(file + ".morph") + var ( + affFile = file + `.aff` + dicFile = file + `.dic` + goodFile = file + `.good` + morphFile = file + `.morph` + ) spell, err := hunspell.Open(affFile, dicFile) if err != nil { diff --git a/lib/ini/common_example_test.go b/lib/ini/common_example_test.go index 4c216880..3ac59457 100644 --- a/lib/ini/common_example_test.go +++ b/lib/ini/common_example_test.go @@ -10,12 +10,12 @@ func ExampleIsValidVarName() { fmt.Println(IsValidVarName(".abcd")) fmt.Println(IsValidVarName("a@bcd")) fmt.Println(IsValidVarName("a-b_c.d")) - //Output: - //false - //false - //false - //false - //false - //false - //true + // Output: + // false + // false + // false + // false + // false + // false + // true } diff --git a/lib/ini/ini.go b/lib/ini/ini.go index b6dc22b5..c233b892 100644 --- a/lib/ini/ini.go +++ b/lib/ini/ini.go @@ -271,8 +271,7 @@ func (in *Ini) marshalStruct( ftype = ftype.Elem() fvalue = fvalue.Elem() } - switch ftype.Kind() { - case reflect.Struct: + if ftype.Kind() == reflect.Struct { vi := fvalue.Interface() t, ok := vi.(time.Time) if ok { diff --git a/lib/ini/ini_example_test.go b/lib/ini/ini_example_test.go index 4bd3b98f..f625f552 100644 --- a/lib/ini/ini_example_test.go +++ b/lib/ini/ini_example_test.go @@ -82,9 +82,9 @@ key=value2 fmt.Println(inis.Gets("section", "", "key")) fmt.Println(inis.Gets("section", "sub", "key")) - //Output: - //[value1 value3] - //[value2 value4 value2] + // Output: + // [value1 value3] + // [value2 value4 value2] } func ExampleIni_GetsUniq() { @@ -107,9 +107,9 @@ key=value2 fmt.Println(inis.GetsUniq("section", "", "key", true)) fmt.Println(inis.GetsUniq("section", "sub", "key", true)) - //Output: - //[value1 value3] - //[value2 value4] + // Output: + // [value1 value3] + // [value2 value4] } func ExampleIni_AsMap() { @@ -361,44 +361,44 @@ func ExampleMarshal_map() { } fmt.Println(string(iniText)) - //Output: - //[map "subString"] - //k = v - //k2 = v2 + // Output: + // [map "subString"] + // k = v + // k2 = v2 // - //[map "subPtrString"] - //k = v - //k2 = v2 + // [map "subPtrString"] + // k = v + // k2 = v2 // - //[map "subInt"] - //keyint = 6 + // [map "subInt"] + // keyint = 6 // - //[map "subPtrInt"] - //keyint = 6 + // [map "subPtrInt"] + // keyint = 6 // - //[mapstruct "struct-key-1"] - //string = struct-1-string - //slice_string = str-1 - //slice_string = str-2 - //int = 1 + // [mapstruct "struct-key-1"] + // string = struct-1-string + // slice_string = str-1 + // slice_string = str-2 + // int = 1 // - //[mapstruct "struct-key-2"] - //string = struct-2-string - //slice_string = str-3 - //slice_string = str-4 - //int = 2 + // [mapstruct "struct-key-2"] + // string = struct-2-string + // slice_string = str-3 + // slice_string = str-4 + // int = 2 // - //[mapptrstruct "ptr-struct-key-1"] - //string = struct-1-string - //slice_string = str-5 - //slice_string = str-6 - //int = 1 + // [mapptrstruct "ptr-struct-key-1"] + // string = struct-1-string + // slice_string = str-5 + // slice_string = str-6 + // int = 1 // - //[mapptrstruct "ptr-struct-key-2"] - //string = struct-2-string - //slice_string = str-7 - //slice_string = str-8 - //int = 2 + // [mapptrstruct "ptr-struct-key-2"] + // string = struct-2-string + // slice_string = str-7 + // slice_string = str-8 + // int = 2 } func ExampleMarshal_struct() { @@ -447,25 +447,25 @@ func ExampleMarshal_struct() { } fmt.Println(string(iniText)) - //Output: - //[section] - //time = 2006-01-02 15:04:05 + // Output: + // [section] + // time = 2006-01-02 15:04:05 // - //[pointer "struct"] - //string = PtrStruct.String - //int = 1 + // [pointer "struct"] + // string = PtrStruct.String + // int = 1 // - //[slice "OfStruct"] - //string = slice-struct-1 - //int = 2 + // [slice "OfStruct"] + // string = slice-struct-1 + // int = 2 // - //[slice "OfStruct"] - //string = slice-struct-2 - //int = 3 + // [slice "OfStruct"] + // string = slice-struct-2 + // int = 3 // - //[section "struct"] - //string = b - //int = 4 + // [section "struct"] + // string = b + // int = 4 } func ExampleUnmarshal() { @@ -626,12 +626,12 @@ int = 2 fmt.Printf("MapStruct: %v\n", t.MapStruct) fmt.Printf("MapPtrStruct: struct-key-1: %v\n", t.MapPtrStruct["struct-key-1"]) fmt.Printf("MapPtrStruct: struct-key-2: %v\n", t.MapPtrStruct["struct-key-2"]) - //Output: - //MapString: map[k:v k2:v2] - //MapInt: map[k:6 k2:7] - //MapStruct: map[struct-key-1:{struct-1-string [str-1 str-2] 1} struct-key-2:{struct-2-string [str-3 str-4] 2}] - //MapPtrStruct: struct-key-1: &{struct-1-string [str-5 str-6] 1} - //MapPtrStruct: struct-key-2: &{struct-2-string [str-7 str-8] 2} + // Output: + // MapString: map[k:v k2:v2] + // MapInt: map[k:6 k2:7] + // MapStruct: map[struct-key-1:{struct-1-string [str-1 str-2] 1} struct-key-2:{struct-2-string [str-3 str-4] 2}] + // MapPtrStruct: struct-key-1: &{struct-1-string [str-5 str-6] 1} + // MapPtrStruct: struct-key-2: &{struct-2-string [str-7 str-8] 2} } func ExampleUnmarshal_struct() { @@ -687,12 +687,12 @@ int = 5 fmt.Printf("SliceStruct: %v\n", t.SliceStruct) fmt.Printf("Struct: %v\n", t.Struct) fmt.Printf("unexported: %v\n", t.unexported) - //Output: - //Time: 2006-01-02 15:04:05 +0000 UTC - //PtrStruct: &{PtrStruct.String 1} - //SliceStruct: [{slice-struct-1 2} {slice-struct-2 3}] - //Struct: {struct 4} - //unexported: { 0} + // Output: + // Time: 2006-01-02 15:04:05 +0000 UTC + // PtrStruct: &{PtrStruct.String 1} + // SliceStruct: [{slice-struct-1 2} {slice-struct-2 3}] + // Struct: {struct 4} + // unexported: { 0} } func ExampleIni_Prune() { @@ -945,20 +945,20 @@ key=value1 log.Fatal(err) } - //Output: - //[section] - //key=value1 # comment - //key2= ; another comment + // Output: + // [section] + // key=value1 # comment + // key2= ; another comment // - //[section "sub"] - //key=value1 + // [section "sub"] + // key=value1 // - //; here is comment on section - //[section] - //key2=false + // ; here is comment on section + // [section] + // key2=false // - //[section "sub"] - //key=value2 + // [section "sub"] + // key=value2 } func ExampleIni_Val() { diff --git a/lib/ini/ini_test.go b/lib/ini/ini_test.go index e4f0709d..2056bece 100644 --- a/lib/ini/ini_test.go +++ b/lib/ini/ini_test.go @@ -278,7 +278,7 @@ func TestIni_Get(t *testing.T) { def = tags[3] got, _ = cfg.Get(tags[0], tags[1], tags[2], def) - got = got + "." + got += `.` testName = fmt.Sprintf("%s: key #%d: Get", tdata.Name, x) diff --git a/lib/ini/reader.go b/lib/ini/reader.go index 794ad6cf..129d701b 100644 --- a/lib/ini/reader.go +++ b/lib/ini/reader.go @@ -540,15 +540,16 @@ func parseRawValue(raw []byte) (out string) { continue } if isEsc { - if b == 'b' { + switch b { + case 'b': sb.WriteByte(tokBackspace) - } else if b == 'n' { + case 'n': sb.WriteByte(tokNewLine) - } else if b == 't' { + case 't': sb.WriteByte(tokTab) - } else if b == '\\' { + case '\\': sb.WriteByte(tokBackslash) - } else if b == '"' { + case '"': sb.WriteByte(tokDoubleQuote) } isEsc = false diff --git a/lib/ints/ints.go b/lib/ints/ints.go index c75c2f9b..4e252420 100644 --- a/lib/ints/ints.go +++ b/lib/ints/ints.go @@ -282,9 +282,7 @@ func Swap(d []int, x, y int) { if x == y || len(d) <= 1 || x > len(d) || y > len(d) { return } - tmp := d[x] - d[x] = d[y] - d[y] = tmp + d[x], d[y] = d[y], d[x] } // To64 convert slice of integer to 64 bit values. diff --git a/lib/ints/ints_test.go b/lib/ints/ints_test.go index 85d91ed1..a0d6c90d 100644 --- a/lib/ints/ints_test.go +++ b/lib/ints/ints_test.go @@ -175,9 +175,7 @@ func TestSwap(t *testing.T) { Swap(in, 0, len(in)-1) - tmp := exp[0] - exp[0] = exp[len(exp)-1] - exp[len(exp)-1] = tmp + exp[0], exp[len(exp)-1] = exp[len(exp)-1], exp[0] test.Assert(t, "", exp, in) } diff --git a/lib/ints64/ints64.go b/lib/ints64/ints64.go index 5c1b24e2..812096f8 100644 --- a/lib/ints64/ints64.go +++ b/lib/ints64/ints64.go @@ -247,9 +247,7 @@ func Swap(d []int64, x, y int) { if x == y || len(d) <= 1 || x > len(d) || y > len(d) { return } - tmp := d[x] - d[x] = d[y] - d[y] = tmp + d[x], d[y] = d[y], d[x] } // Let `x` be the first index of left-side, `y` be the first index of diff --git a/lib/ints64/ints64_test.go b/lib/ints64/ints64_test.go index 1dc0c378..828e5b35 100644 --- a/lib/ints64/ints64_test.go +++ b/lib/ints64/ints64_test.go @@ -174,9 +174,7 @@ func TestSwap(t *testing.T) { Swap(in, 0, len(in)-1) - tmp := exp[0] - exp[0] = exp[len(exp)-1] - exp[len(exp)-1] = tmp + exp[0], exp[len(exp)-1] = exp[len(exp)-1], exp[0] test.Assert(t, "", exp, in) } diff --git a/lib/math/big/rat_example_test.go b/lib/math/big/rat_example_test.go index 7ad61ffb..fb6a8208 100644 --- a/lib/math/big/rat_example_test.go +++ b/lib/math/big/rat_example_test.go @@ -17,12 +17,13 @@ func ExampleAddRat() { fmt.Println(AddRat("a")) fmt.Println(AddRat(0, 0.0001)) fmt.Println(AddRat("1.007", "a", "2.003")) // Invalid parameter "a" is ignored. - //Output: - //0 - //0 - //0 - //0.0001 - //3.01 + + // Output: + // 0 + // 0 + // 0 + // 0.0001 + // 3.01 } func ExampleMulRat() { @@ -31,12 +32,13 @@ func ExampleMulRat() { fmt.Println(MulRat("a")) fmt.Println(MulRat(0, 1)) fmt.Println(MulRat(6, "a", "0.3")) // Invalid parameter "a" is ignored. - //Output: - //0 - //0 - //0 - //0 - //1.8 + + // Output: + // 0 + // 0 + // 0 + // 0 + // 1.8 } func ExampleNewRat() { @@ -72,27 +74,28 @@ func ExampleNewRat() { for _, v := range inputs { fmt.Println(NewRat(v)) } - //Output: - //0 - //0 - //0 - //0 - //0 - //0.00000001 - //14687233442.06916608 - //14687233442.06916608 - //0 - //14687233442.06916608 - //14687233442.06916608 - //0 - //0 - //146.87233442 - //146.87233442 - //65535 - //4294967295 - //18446744073709551615 - //0 - //100000000 + + // Output: + // 0 + // 0 + // 0 + // 0 + // 0 + // 0.00000001 + // 14687233442.06916608 + // 14687233442.06916608 + // 0 + // 14687233442.06916608 + // 14687233442.06916608 + // 0 + // 0 + // 146.87233442 + // 146.87233442 + // 65535 + // 4294967295 + // 18446744073709551615 + // 0 + // 100000000 } func ExampleQuoRat() { @@ -107,17 +110,17 @@ func ExampleQuoRat() { fmt.Println(QuoRat(int64(1815507979407), NewRat(100000000))) fmt.Println(QuoRat("25494300", "25394000000")) - //Output: - //0 - //0 - //0 - //0 - //0 - //0 - //0 - //17.0992647 - //18155.07979407 - //0.00100395 + // Output: + // 0 + // 0 + // 0 + // 0 + // 0 + // 0 + // 0 + // 17.0992647 + // 18155.07979407 + // 0.00100395 } func ExampleSubRat() { @@ -126,12 +129,13 @@ func ExampleSubRat() { fmt.Println(SubRat("a")) fmt.Println(SubRat(0, 1)) fmt.Println(SubRat(6, "a", "0.3")) - //Output: - //0 - //0 - //0 - //-1 - //5.7 + + // Output: + // 0 + // 0 + // 0 + // -1 + // 5.7 } func ExampleRat_Abs() { @@ -139,21 +143,23 @@ func ExampleRat_Abs() { fmt.Println(NewRat("-1").Abs()) fmt.Println(NewRat("-0.00001").Abs()) fmt.Println(NewRat("1").Abs()) - //Output: - //0 - //1 - //0.00001 - //1 + + // Output: + // 0 + // 1 + // 0.00001 + // 1 } func ExampleRat_Add() { fmt.Println(NewRat(nil).Add(nil)) fmt.Println(NewRat(1).Add(nil)) fmt.Println(NewRat(1).Add(1)) - //Output: - //0 - //1 - //2 + + // Output: + // 0 + // 1 + // 2 } func ExampleRat_Humanize() { @@ -170,16 +176,17 @@ func ExampleRat_Humanize() { fmt.Printf("%s\n", NewRat("1000.2").Humanize(thousandSep, decimalSep)) fmt.Printf("%s\n", NewRat("10000.23").Humanize(thousandSep, decimalSep)) fmt.Printf("%s\n", NewRat("100000.234").Humanize(thousandSep, decimalSep)) - //Output: - //0 - //0 - //0,1234 - //100 - //100,1234 - //1.000 - //1.000,2 - //10.000,23 - //100.000,234 + + // Output: + // 0 + // 0 + // 0,1234 + // 100 + // 100,1234 + // 1.000 + // 1.000,2 + // 10.000,23 + // 100.000,234 } func ExampleRat_Int64() { @@ -197,19 +204,19 @@ func ExampleRat_Int64() { fmt.Println(QuoRat(128900, 3220).Mul(100000000).Int64()) fmt.Println(QuoRat(25494300, QuoRat(25394000000, 100000000)).Int64()) - //Output: - //MaxInt64: 9223372036854775807 - //MaxInt64+1: 9223372036854775807 - //MinInt64: -9223372036854775808 - //MinInt64-1: -9223372036854775808 - //0 - //0 - //0 - //0 - //401114490002438879 - //4003105590 - //4003105590 - //100394 + // Output: + // MaxInt64: 9223372036854775807 + // MaxInt64+1: 9223372036854775807 + // MinInt64: -9223372036854775808 + // MinInt64-1: -9223372036854775808 + // 0 + // 0 + // 0 + // 0 + // 401114490002438879 + // 4003105590 + // 4003105590 + // 100394 } func ExampleRat_IsEqual() { @@ -227,17 +234,17 @@ func ExampleRat_IsEqual() { // Equal due to String() truncation to DefaultDigitPrecision (8) digits. fmt.Println(NewRat("0.1234567890123").IsEqual("0.12345678")) - //Output: - //false - //false - //true - //false - //true - //true - //true - //true - //true - //true + // Output: + // false + // false + // true + // false + // true + // true + // true + // true + // true + // true } func ExampleRat_IsGreater() { @@ -248,11 +255,11 @@ func ExampleRat_IsGreater() { fmt.Println(r.IsGreater("0.000_000_5")) fmt.Println(r.IsGreater("0.000_000_49999")) - //Output: - //false - //false - //false - //true + // Output: + // false + // false + // false + // true } func ExampleRat_IsGreaterOrEqual() { @@ -264,12 +271,12 @@ func ExampleRat_IsGreaterOrEqual() { fmt.Println(r.IsGreaterOrEqual("0.000_000_5")) fmt.Println(r.IsGreaterOrEqual("0.000_000_49999")) - //Output: - //false - //false - //false - //true - //true + // Output: + // false + // false + // false + // true + // true } func ExampleRat_IsGreaterThanZero() { @@ -278,11 +285,11 @@ func ExampleRat_IsGreaterThanZero() { fmt.Println(NewRat("-0.000_000_000_000_000_001").IsGreaterThanZero()) fmt.Println(NewRat("0.000_000_000_000_000_001").IsGreaterThanZero()) - //Output: - //false - //false - //false - //true + // Output: + // false + // false + // false + // true } func ExampleRat_IsLess() { @@ -294,12 +301,12 @@ func ExampleRat_IsLess() { fmt.Println(r.IsLess("0.000_000_49")) fmt.Println(r.IsLess("0.000_000_500_000_000_001")) - //Output: - //false - //false - //false - //false - //true + // Output: + // false + // false + // false + // false + // true } func ExampleRat_IsLessOrEqual() { @@ -311,12 +318,12 @@ func ExampleRat_IsLessOrEqual() { fmt.Println(r.IsLessOrEqual("0.000_000_49")) fmt.Println(r.IsLessOrEqual("0.000_000_500_000_000_001")) - //Output: - //false - //false - //true - //false - //true + // Output: + // false + // false + // true + // false + // true } func ExampleRat_IsLessThanZero() { @@ -325,11 +332,11 @@ func ExampleRat_IsLessThanZero() { fmt.Println(NewRat("-0.000_000_000_000_000_001").IsLessThanZero()) fmt.Println(NewRat("0.000_000_000_000_000_001").IsLessThanZero()) - //Output: - //false - //false - //true - //false + // Output: + // false + // false + // true + // false } func ExampleRat_IsZero() { @@ -339,12 +346,12 @@ func ExampleRat_IsZero() { fmt.Println(NewRat("-0.000_000_000_000_000_001").IsZero()) fmt.Println(NewRat("0.000_000_000_000_000_001").IsZero()) - //Output: - //false - //true - //true - //false - //false + // Output: + // false + // true + // true + // false + // false } func ExampleRat_MarshalJSON() { @@ -377,31 +384,31 @@ func ExampleRat_MarshalJSON() { fmt.Printf("%s\n", out) } - //Output: - //"0" - //"0" - //"0" - //"0.1" - //"0.00000001" - //"0" - //"1234567890" - //"64.23738872" - //"0.12345678" - //"142660378.65368736" - //"9193394308.8577137" - //"14687233442.06916608" - //0 - //0 - //0 - //0.1 - //0.00000001 - //0 - //1234567890 - //64.23738872 - //0.12345678 - //142660378.65368736 - //9193394308.8577137 - //14687233442.06916608 + // Output: + // "0" + // "0" + // "0" + // "0.1" + // "0.00000001" + // "0" + // "1234567890" + // "64.23738872" + // "0.12345678" + // "142660378.65368736" + // "9193394308.8577137" + // "14687233442.06916608" + // 0 + // 0 + // 0 + // 0.1 + // 0.00000001 + // 0 + // 1234567890 + // 64.23738872 + // 0.12345678 + // 142660378.65368736 + // 9193394308.8577137 + // 14687233442.06916608 } func ExampleRat_MarshalJSON_withStruct() { @@ -417,7 +424,7 @@ func ExampleRat_MarshalJSON_withStruct() { MarshalJSONAsString = true for _, in := range inputs { - out, _ := json.Marshal(&in) + out, _ := json.Marshal(in) fmt.Printf("%s\n", out) } @@ -427,13 +434,13 @@ func ExampleRat_MarshalJSON_withStruct() { fmt.Printf("%s\n", out) } - //Output: - //{"V":null} - //{"V":"0"} - //{"V":"0.12345678"} - //{"V":null} - //{"V":0} - //{"V":0.12345678} + // Output: + // {"V":null} + // {"V":"0"} + // {"V":"0.12345678"} + // {"V":null} + // {"V":0} + // {"V":0.12345678} } func ExampleRat_Mul() { @@ -445,11 +452,12 @@ func ExampleRat_Mul() { fmt.Println(NewRat(defValue).Mul("0")) fmt.Println(NewRat(defValue).Mul(defValue)) fmt.Println(NewRat("1.06916608").Mul("1.06916608")) - //Output: - //0 - //0 - //215714826181834884090.46087866 - //1.1431161 + + // Output: + // 0 + // 0 + // 215714826181834884090.46087866 + // 1.1431161 } func ExampleRat_Quo() { @@ -461,11 +469,12 @@ func ExampleRat_Quo() { fmt.Println(NewRat(defValue).Quo(nil)) fmt.Println(NewRat(defValue).Quo("a")) fmt.Println(NewRat(defValue).Quo("100_000_000")) - //Output: - //0 - //0 - //0 - //146.87233442 + + // Output: + // 0 + // 0 + // 0 + // 146.87233442 } func ExampleRat_RoundNearestFraction() { @@ -481,19 +490,20 @@ func ExampleRat_RoundNearestFraction() { fmt.Printf("-0.5: %s\n", NewRat("-0.5").RoundNearestFraction()) fmt.Printf("-0.555: %s\n", NewRat("-0.555").RoundNearestFraction()) fmt.Printf("-0.545: %s\n", NewRat("-0.545").RoundNearestFraction()) - //Output: - //nil: 0 - //0.000000001: 0 - //0.00545: 0.005 - //0.00555: 0.006 - //0.0545: 0.05 - //0.0555: 0.06 - //0.545: 0.5 - //0.555: 0.6 - //0.5: 0.5 - //-0.5: -0.5 - //-0.555: -0.6 - //-0.545: -0.5 + + // Output: + // nil: 0 + // 0.000000001: 0 + // 0.00545: 0.005 + // 0.00555: 0.006 + // 0.0545: 0.05 + // 0.0555: 0.06 + // 0.545: 0.5 + // 0.555: 0.6 + // 0.5: 0.5 + // -0.5: -0.5 + // -0.555: -0.6 + // -0.545: -0.5 } func ExampleRat_RoundToNearestAway() { @@ -512,20 +522,21 @@ func ExampleRat_RoundToNearestAway() { fmt.Printf("0.5: %s\n", NewRat("0.5").RoundToNearestAway(0)) fmt.Printf("-0.5: %s\n", NewRat("-0.5").RoundToNearestAway(0)) - //Output: - //nil: 0 - //0.0054: 0.01 - //0.0054: 0 - //0.5455: 0.55 - //0.5555: 0.56 - //0.5566: 0.56 - //0.5566: 1 - //0.02514135: 0.025141 - //0.02514145: 0.025141 - //0.02514155: 0.025142 - //0.02514165: 0.025142 - //0.5: 1 - //-0.5: -1 + + // Output: + // nil: 0 + // 0.0054: 0.01 + // 0.0054: 0 + // 0.5455: 0.55 + // 0.5555: 0.56 + // 0.5566: 0.56 + // 0.5566: 1 + // 0.02514135: 0.025141 + // 0.02514145: 0.025141 + // 0.02514155: 0.025142 + // 0.02514165: 0.025142 + // 0.5: 1 + // -0.5: -1 } func ExampleRat_RoundToZero() { @@ -537,13 +548,14 @@ func ExampleRat_RoundToZero() { // In Go <= 1.18, this will print "-0", but on Go tip "0". // So to make test success on all versions, we multiple it to 1. fmt.Println(NewRat("-0.5").RoundToZero(0).Mul(1)) - //Output: - //0 - //0.54 - //0.55 - //0.55 - //0 - //0 + + // Output: + // 0 + // 0.54 + // 0.55 + // 0.55 + // 0 + // 0 } func ExampleRat_Scan() { @@ -566,12 +578,12 @@ func ExampleRat_Scan() { fmt.Println(r) } - //Output: - //1234 - //error: Rat.Scan: unknown type <nil> - //1234 - //0.0001 - //0.0001 + // Output: + // 1234 + // error: Rat.Scan: unknown type <nil> + // 1234 + // 0.0001 + // 0.0001 } func ExampleRat_String() { @@ -588,32 +600,33 @@ func ExampleRat_String() { "64.23738872403", float64(64.23738872403), } - //Output: - //0 - //12345 - //0 - //0 - //0.1 - //0.1 - //0.0000001 - //0.0000001 - //0 - //64.23738872 - //64.23738872 - for _, in := range inputs { fmt.Println(NewRat(in).String()) } + + // Output: + // 0 + // 12345 + // 0 + // 0 + // 0.1 + // 0.1 + // 0.0000001 + // 0.0000001 + // 0 + // 64.23738872 + // 64.23738872 } func ExampleRat_Sub() { fmt.Println(NewRat(nil).Sub(1)) fmt.Println(NewRat(1).Sub(nil)) fmt.Println(NewRat(1).Sub(1)) - //Output: - //0 - //1 - //0 + + // Output: + // 0 + // 1 + // 0 } func ExampleRat_UnmarshalJSON_withStruct() { @@ -640,14 +653,15 @@ func ExampleRat_UnmarshalJSON_withStruct() { } fmt.Printf("%s %s\n", t.V, t.W) } - //Output: - //Rat.UnmarshalJSON: cannot convert []uint8([97 98]) to Rat - //0 0 - //invalid character '}' looking for beginning of value - //0 0 - //1 0 - //0.12345678 0 - //0.1234 0.5678 + + // Output: + // Rat.UnmarshalJSON: cannot convert []uint8([97 98]) to Rat + // 0 0 + // invalid character '}' looking for beginning of value + // 0 0 + // 1 0 + // 0.12345678 0 + // 0.1234 0.5678 } func ExampleRat_Value() { @@ -661,9 +675,10 @@ func ExampleRat_Value() { out, _ := NewRat(in).Value() fmt.Printf("%s\n", out) } - //Output: - //0 - //0 - //1.2345 - //12345.67891234 + + // Output: + // 0 + // 0 + // 1.2345 + // 12345.67891234 } diff --git a/lib/memfs/dirwatcher_example_test.go b/lib/memfs/dirwatcher_example_test.go index ef4c3c57..0720cc84 100644 --- a/lib/memfs/dirwatcher_example_test.go +++ b/lib/memfs/dirwatcher_example_test.go @@ -142,24 +142,24 @@ func ExampleDirWatcher() { dw.Stop() - //Output: - //Deleting the root directory: - //-- FileStateDeleted / - //Re-create root directory with sub-directory: - //-- FileStateCreated / - //Chmod on root directory: - //-- FileStateUpdateMode / drwx------ - //Create new file on root directory: /new.adoc - //-- FileStateCreated /new.adoc -rw------- - //Remove file on root directory: /new.adoc - //-- FileStateDeleted /new.adoc -rw------- - //Create new sub-directory: /subdir - //-- FileStateCreated /subdir drwxr-x--- - //Create new file in sub directory: /subdir/new.adoc - //-- FileStateCreated /subdir/new.adoc -rw------- - //Remove file in sub directory: /subdir/new.adoc - //-- FileStateDeleted /subdir/new.adoc -rw------- - //Create excluded file in sub directory: /subdir/new.html - //Create new file under assets: /assets/new - //-- FileStateCreated /assets/new -rw------- + // Output: + // Deleting the root directory: + // -- FileStateDeleted / + // Re-create root directory with sub-directory: + // -- FileStateCreated / + // Chmod on root directory: + // -- FileStateUpdateMode / drwx------ + // Create new file on root directory: /new.adoc + // -- FileStateCreated /new.adoc -rw------- + // Remove file on root directory: /new.adoc + // -- FileStateDeleted /new.adoc -rw------- + // Create new sub-directory: /subdir + // -- FileStateCreated /subdir drwxr-x--- + // Create new file in sub directory: /subdir/new.adoc + // -- FileStateCreated /subdir/new.adoc -rw------- + // Remove file in sub directory: /subdir/new.adoc + // -- FileStateDeleted /subdir/new.adoc -rw------- + // Create excluded file in sub directory: /subdir/new.html + // Create new file under assets: /assets/new + // -- FileStateCreated /assets/new -rw------- } diff --git a/lib/memfs/memfs.go b/lib/memfs/memfs.go index 8077ae41..2548dced 100644 --- a/lib/memfs/memfs.go +++ b/lib/memfs/memfs.go @@ -54,7 +54,7 @@ type MemFS struct { // If there are two instance of Node that have the same path, the last // instance will be ignored. // -// DEPRECATED: use [MemFS.Merge] instead. +// Deprecated: use [MemFS.Merge] instead. // TODO: Remove in the next three release cycles, v0.53.0. func Merge(params ...*MemFS) (merged *MemFS) { merged = &MemFS{ @@ -604,7 +604,7 @@ func (mfs *MemFS) mount() (err error) { return fmt.Errorf("%s: %w", logp, err) } - _, err = mfs.scanDir(mfs.Root) + err = mfs.scanDir(mfs.Root) if err != nil { return fmt.Errorf("%s: %w", logp, err) } @@ -622,7 +622,7 @@ func (mfs *MemFS) Remount() (err error) { // scanDir scan the content of node directory and add them to mfs. // It returns number of childs added to the node or an error. -func (mfs *MemFS) scanDir(node *Node) (n int, err error) { +func (mfs *MemFS) scanDir(node *Node) (err error) { var ( logp = "scanDir" child *Node @@ -635,14 +635,14 @@ func (mfs *MemFS) scanDir(node *Node) (n int, err error) { if err != nil { if os.IsPermission(err) { // Ignore error due to permission - return 0, nil + return nil } - return 0, fmt.Errorf(`%s %q: %w`, logp, node.SysPath, err) + return fmt.Errorf(`%s %q: %w`, logp, node.SysPath, err) } fis, err = f.Readdir(0) if err != nil { - return 0, fmt.Errorf(`%s %q: %w`, logp, node.SysPath, err) + return fmt.Errorf(`%s %q: %w`, logp, node.SysPath, err) } sort.SliceStable(fis, func(x, y int) bool { @@ -661,12 +661,11 @@ func (mfs *MemFS) scanDir(node *Node) (n int, err error) { if child == nil { continue } - n++ if !child.mode.IsDir() { continue } - _, err = mfs.scanDir(child) + err = mfs.scanDir(child) if err != nil { err = fmt.Errorf(`%s %q: %w`, logp, node.SysPath, err) goto out @@ -682,7 +681,7 @@ out: } } - return n, err + return err } // refresh the tree by rescanning from the root. @@ -710,7 +709,7 @@ func (mfs *MemFS) refresh(url string) (node *Node, err error) { node = mfs.PathNodes.Get(dir) } - _, err = mfs.scanDir(node) + err = mfs.scanDir(node) if err != nil { return nil, err } @@ -765,7 +764,7 @@ func (mfs *MemFS) Watch(opts WatchOptions) (dw *DirWatcher, err error) { Options: *mfs.Opts, } - _, err = mfs.scanDir(mfs.Root) + err = mfs.scanDir(mfs.Root) if err != nil { return nil, fmt.Errorf("%s: %w", logp, err) } diff --git a/lib/memfs/memfs_example_test.go b/lib/memfs/memfs_example_test.go index 22dbe450..a24ea8ca 100644 --- a/lib/memfs/memfs_example_test.go +++ b/lib/memfs/memfs_example_test.go @@ -113,7 +113,8 @@ func ExampleMemFS_Watch() { opts.Root, err = os.MkdirTemp(``, `memfs_watch`) if err != nil { - log.Fatal(err) + log.Println(err) + return } defer func() { @@ -122,12 +123,14 @@ func ExampleMemFS_Watch() { mfs, err = memfs.New(&opts) if err != nil { - log.Fatal(err) + log.Println(err) + return } dw, err = mfs.Watch(watchOpts) if err != nil { - log.Fatal(err) + log.Println(err) + return } // Wait for the goroutine on Watch run. @@ -136,20 +139,23 @@ func ExampleMemFS_Watch() { testFile := filepath.Join(opts.Root, `file`) err = os.WriteFile(testFile, []byte(`dummy content`), 0700) if err != nil { - log.Fatal(err) + log.Println(err) + return } ns = <-dw.C node, err = mfs.Get(`/file`) if err != nil { - log.Fatal(err) + log.Println(err) + return } fmt.Printf("Node: %s: %s\n", node.Path, ns.State) err = os.Remove(testFile) if err != nil { - log.Fatal(err) + log.Println(err) + return } ns = <-dw.C diff --git a/lib/memfs/memfs_test.go b/lib/memfs/memfs_test.go index 422db274..abd5847d 100644 --- a/lib/memfs/memfs_test.go +++ b/lib/memfs/memfs_test.go @@ -7,7 +7,9 @@ package memfs import ( "bytes" "encoding/json" + "errors" "fmt" + "io/fs" "log" "os" "path/filepath" @@ -32,8 +34,8 @@ func TestMain(m *testing.M) { err = os.MkdirAll(filepath.Join(_testWD, "testdata/exclude/dir"), 0700) if err != nil { - perr, ok := err.(*os.PathError) - if !ok { + var perr *fs.PathError + if !errors.As(err, &perr) { log.Fatal("!ok:", err) } if perr.Err != os.ErrExist { @@ -43,8 +45,8 @@ func TestMain(m *testing.M) { err = os.MkdirAll(filepath.Join(_testWD, "testdata/include/dir"), 0700) if err != nil { - perr, ok := err.(*os.PathError) - if !ok { + var perr *fs.PathError + if !errors.As(err, &perr) { log.Fatal(err) } if perr.Err != os.ErrExist { diff --git a/lib/memfs/watcher_example_test.go b/lib/memfs/watcher_example_test.go index b08b1080..456db6f3 100644 --- a/lib/memfs/watcher_example_test.go +++ b/lib/memfs/watcher_example_test.go @@ -70,14 +70,14 @@ func ExampleNewWatcher() { fmt.Printf("File mode: %s\n", ns.Node.Mode()) fmt.Printf("File size: %d\n", ns.Node.Size()) - //Output: - //State: FileStateUpdateMode - //File mode: -rwx------ - //File size: 0 - //State: FileStateUpdateContent - //File mode: -rwx------ - //File size: 15 - //State: FileStateDeleted - //File mode: -rwx------ - //File size: 15 + // Output: + // State: FileStateUpdateMode + // File mode: -rwx------ + // File size: 0 + // State: FileStateUpdateContent + // File mode: -rwx------ + // File size: 15 + // State: FileStateDeleted + // File mode: -rwx------ + // File size: 15 } diff --git a/lib/mining/classifier/cart/node.go b/lib/mining/classifier/cart/node.go index b995b182..0317704d 100644 --- a/lib/mining/classifier/cart/node.go +++ b/lib/mining/classifier/cart/node.go @@ -36,7 +36,7 @@ type NodeValue struct { // String will return the value of node for printable. func (nodev *NodeValue) String() (s string) { if nodev.IsLeaf { - s = fmt.Sprintf("Class: %s", nodev.Class) + s = `Class: ` + nodev.Class } else { s = fmt.Sprintf("(SplitValue: %v)", reflect.ValueOf(nodev.SplitV)) diff --git a/lib/mlog/benchmark_test.go b/lib/mlog/benchmark_test.go index 46261e84..25138d24 100644 --- a/lib/mlog/benchmark_test.go +++ b/lib/mlog/benchmark_test.go @@ -26,7 +26,6 @@ func BenchmarkMultiLogger(b *testing.B) { for pb.Next() { mlog.Errf("err") mlog.Outf("out") - //mlog.Flush() } }) } diff --git a/lib/net/html/example_node_iterator_test.go b/lib/net/html/example_node_iterator_test.go index 18eb9832..94ece050 100644 --- a/lib/net/html/example_node_iterator_test.go +++ b/lib/net/html/example_node_iterator_test.go @@ -34,22 +34,23 @@ func ExampleParse() { fmt.Printf("\t%s\n", node.Data) } } - //Output: - //html - //head - //body - //ul - //li - //b - // item - //b - //span - // one - //span - //li - //ul - //body - //html + + // Output: + // html + // head + // body + // ul + // li + // b + // item + // b + // span + // one + // span + // li + // ul + // body + // html } func ExampleNodeIterator_SetNext() { @@ -82,13 +83,14 @@ func ExampleNodeIterator_SetNext() { fmt.Printf("\t%s\n", node.Data) } } - //Output: - //html - //head - //body - //h2 - // Jump here - //h2 - //body - //html + + // Output: + // html + // head + // body + // h2 + // Jump here + // h2 + // body + // html } diff --git a/lib/net/html/example_test.go b/lib/net/html/example_test.go index e06f6da4..d0582555 100644 --- a/lib/net/html/example_test.go +++ b/lib/net/html/example_test.go @@ -15,15 +15,15 @@ func ExampleNormalizeForID() { fmt.Println(NormalizeForID(".123 ABC def")) fmt.Println(NormalizeForID("test 123")) fmt.Println(NormalizeForID("⌘")) - //Output: - //_ - //_id_ - //_id_ - //_id_1 - //_1-d - //_123_abc_def - //test_123 - //___ + // Output: + // _ + // _id_ + // _id_ + // _id_1 + // _1-d + // _123_abc_def + // test_123 + // ___ } func ExampleSanitize() { diff --git a/lib/net/html/html.go b/lib/net/html/html.go index 69fb371a..9f5324ab 100644 --- a/lib/net/html/html.go +++ b/lib/net/html/html.go @@ -57,7 +57,7 @@ func NormalizeForID(in string) (out string) { bin = append(bin, '_') } else if !ascii.IsAlpha(bin[0]) && bin[0] != '_' { bin = append(bin, '_') - copy(bin[1:], bin[:]) + copy(bin[1:], bin) bin[0] = '_' } @@ -86,6 +86,9 @@ func Sanitize(in []byte) (plain []byte) { for { tokenType = htmlToken.Next() switch tokenType { + case html.EndTagToken, html.SelfClosingTagToken, html.CommentToken, html.DoctypeToken: + // NOOP. + case html.ErrorToken: goto out diff --git a/lib/net/net.go b/lib/net/net.go index 09f99837..4add0435 100644 --- a/lib/net/net.go +++ b/lib/net/net.go @@ -143,12 +143,8 @@ func Read(conn net.Conn, bufsize int, timeout time.Duration) (packet []byte, err for { n, err = conn.Read(buf) if err != nil { - var ( - neterr net.Error - ok bool - ) - neterr, ok = err.(net.Error) - if ok && neterr.Timeout() { + var neterr net.Error + if errors.As(err, &neterr) && neterr.Timeout() { return nil, ErrReadTimeout } return nil, fmt.Errorf(`%s: %w`, logp, err) diff --git a/lib/net/poll_linux.go b/lib/net/poll_linux.go index 9d85acdc..210ec6d8 100644 --- a/lib/net/poll_linux.go +++ b/lib/net/poll_linux.go @@ -8,6 +8,7 @@ package net import ( + "errors" "fmt" "log" @@ -77,7 +78,7 @@ func (poll *epoll) WaitRead() (fds []int, err error) { for { n, err = unix.EpollWait(poll.read, poll.events[:], -1) if err != nil { - if err == unix.EINTR { + if errors.Is(err, unix.EINTR) { continue } return nil, fmt.Errorf(`%s: %w`, logp, err) @@ -118,7 +119,7 @@ func (poll *epoll) WaitReadEvents() (events []PollEvent, err error) { for n == 0 { n, err = unix.EpollWait(poll.read, poll.events[:], -1) if err != nil { - if err == unix.EINTR { + if errors.Is(err, unix.EINTR) { continue } return nil, fmt.Errorf(`%s: %w`, logp, err) diff --git a/lib/net/resolvconf_example_test.go b/lib/net/resolvconf_example_test.go index 0eedcb31..9d81ea83 100644 --- a/lib/net/resolvconf_example_test.go +++ b/lib/net/resolvconf_example_test.go @@ -27,9 +27,9 @@ func ExampleResolvConf_PopulateQuery() { queries = resconf.PopulateQuery(`a.machine`) fmt.Println(queries) - //Output: - //[vpn vpn.my.internal] - //[a.machine] + // Output: + // [vpn vpn.my.internal] + // [a.machine] } func ExampleResolvConf_WriteTo() { diff --git a/lib/os/exec/exec.go b/lib/os/exec/exec.go index c67640b3..b7c44c5c 100644 --- a/lib/os/exec/exec.go +++ b/lib/os/exec/exec.go @@ -27,7 +27,8 @@ func ParseCommandArgs(in string) (cmd string, args []string) { for _, r := range in { if quote > 0 { - if r == quote { + switch r { + case quote: if prev == '\\' { sb.WriteRune(r) prev = r @@ -39,14 +40,14 @@ func ParseCommandArgs(in string) (cmd string, args []string) { sb.Reset() quote = 0 } - } else if r == '\\' { + case '\\': if prev == '\\' { sb.WriteRune(r) prev = 0 } else { prev = r } - } else { + default: if prev == '\\' { sb.WriteRune('\\') } diff --git a/lib/os/extract.go b/lib/os/extract.go index becead88..1d7841f5 100644 --- a/lib/os/extract.go +++ b/lib/os/extract.go @@ -379,7 +379,6 @@ func (xtrk *extractor) unzip(fin *os.File) (err error) { inFile io.ReadCloser filePath string outFile *os.File - fileTimes []archiveTimes ) fi, err = fin.Stat() @@ -392,6 +391,8 @@ func (xtrk *extractor) unzip(fin *os.File) (err error) { return fmt.Errorf("%s: %w", logp, err) } + var fileTimes = make([]archiveTimes, 0, len(zipReader.File)) + for _, zipFile := range zipReader.File { inFile, err = zipFile.Open() if err != nil { diff --git a/lib/paseto/paseto.go b/lib/paseto/paseto.go index a3b2ebf6..31fc8281 100644 --- a/lib/paseto/paseto.go +++ b/lib/paseto/paseto.go @@ -109,7 +109,6 @@ import ( "encoding/base64" "encoding/binary" "errors" - "fmt" "strings" "golang.org/x/crypto/blake2b" @@ -174,7 +173,7 @@ func encrypt(aead cipher.AEAD, nonce, plain, footer []byte) (token string, err e base64.RawURLEncoding.Encode(dst, sc) _, err = buf.Write(dst) if err != nil { - return "", nil + return ``, err } if len(footer) > 0 { @@ -185,7 +184,7 @@ func encrypt(aead cipher.AEAD, nonce, plain, footer []byte) (token string, err e base64.RawURLEncoding.Encode(dst, footer) _, err = buf.Write(dst) if err != nil { - return "", nil + return ``, err } } @@ -200,10 +199,10 @@ func Decrypt(aead cipher.AEAD, token string) (plain, footer []byte, err error) { return nil, nil, errors.New("invalid token format") } if pieces[0] != "v2" { - return nil, nil, fmt.Errorf("unsupported protocol version " + pieces[0]) + return nil, nil, errors.New(`unsupported protocol version ` + pieces[0]) } if pieces[1] != "local" { - return nil, nil, fmt.Errorf("expecting local mode, got " + pieces[1]) + return nil, nil, errors.New(`expecting local mode, got ` + pieces[1]) } if len(pieces) == 4 { @@ -292,7 +291,7 @@ func Sign(sk ed25519.PrivateKey, m, f []byte) (token string, err error) { // from base64 string); verify that the signature is valid for the message. func Verify(pk ed25519.PublicKey, sm, f []byte) (msg []byte, err error) { if len(sm) <= 64 { - return nil, fmt.Errorf("invalid signed message length") + return nil, errors.New(`invalid signed message length`) } msg = sm[:len(sm)-64] @@ -305,7 +304,7 @@ func Verify(pk ed25519.PublicKey, sm, f []byte) (msg []byte, err error) { } if !ed25519.Verify(pk, msg2, sig) { - return nil, fmt.Errorf("invalid message signature") + return nil, errors.New(`invalid message signature`) } return msg, nil diff --git a/lib/paseto/public_mode.go b/lib/paseto/public_mode.go index 7dc8d511..46177ba7 100644 --- a/lib/paseto/public_mode.go +++ b/lib/paseto/public_mode.go @@ -7,6 +7,7 @@ package paseto import ( "encoding/base64" "encoding/json" + "errors" "fmt" "net/http" "strings" @@ -37,10 +38,10 @@ type PublicMode struct { // outgoing token. func NewPublicMode(our Key) (auth *PublicMode, err error) { if len(our.ID) == 0 { - return nil, fmt.Errorf("empty key ID") + return nil, errors.New(`empty key ID`) } if len(our.Private) == 0 { - return nil, fmt.Errorf("empty private key") + return nil, errors.New(`empty private key`) } auth = &PublicMode{ our: our, @@ -55,7 +56,7 @@ func (auth *PublicMode) UnpackHTTPRequest(req *http.Request) ( publicToken *PublicToken, err error, ) { if req == nil { - return nil, fmt.Errorf("empty HTTP request") + return nil, errors.New(`empty HTTP request`) } var token string @@ -64,7 +65,7 @@ func (auth *PublicMode) UnpackHTTPRequest(req *http.Request) ( if len(headerAuth) == 0 { token = req.Form.Get(paramNameAccessToken) if len(token) == 0 { - return nil, fmt.Errorf("missing access token") + return nil, errors.New(`missing access token`) } } else { vals := strings.Fields(headerAuth) @@ -85,10 +86,10 @@ func (auth *PublicMode) UnpackHTTPRequest(req *http.Request) ( // The only required fields in Key is ID and Public. func (auth *PublicMode) AddPeer(k Key) (err error) { if len(k.ID) == 0 { - return fmt.Errorf("empty key ID") + return errors.New(`empty key ID`) } if len(k.Public) == 0 { - return fmt.Errorf("empty public key") + return errors.New(`empty public key`) } auth.peers.upsert(k) return nil @@ -142,13 +143,13 @@ func (auth *PublicMode) Pack(audience, subject string, data []byte, footer map[s func (auth *PublicMode) Unpack(token string) (publicToken *PublicToken, err error) { pieces := strings.Split(token, ".") if len(pieces) != 4 { - return nil, fmt.Errorf("invalid token format") + return nil, errors.New(`invalid token format`) } if pieces[0] != "v2" { - return nil, fmt.Errorf("unsupported protocol version " + pieces[0]) + return nil, errors.New(`unsupported protocol version ` + pieces[0]) } if pieces[1] != "public" { - return nil, fmt.Errorf("expecting public mode, got " + pieces[1]) + return nil, errors.New(`expecting public mode, got ` + pieces[1]) } publicToken = &PublicToken{} diff --git a/lib/reflect/example_test.go b/lib/reflect/example_test.go index 1b2efb72..f69c45d1 100644 --- a/lib/reflect/example_test.go +++ b/lib/reflect/example_test.go @@ -104,7 +104,7 @@ func ExampleIsNil() { fmt.Printf("%19T: v == nil is %5t, IsNil() is %5t\n", c.v, c.v == nil, libreflect.IsNil(c.v)) } - //Output: + // Output: // <nil>: v == nil is true, IsNil() is true // bool: v == nil is false, IsNil() is false // chan int: v == nil is false, IsNil() is true @@ -127,20 +127,20 @@ func (imt *InvalidMarshalText) MarshalText() (string, error) { return "", nil } -type ErrorMarshalJson struct{} +type ErrorMarshalJSON struct{} -func (emj *ErrorMarshalJson) MarshalJSON() ([]byte, error) { - return nil, errors.New("ErrorMarshalJson: test") +func (emj *ErrorMarshalJSON) MarshalJSON() ([]byte, error) { + return nil, errors.New(`ErrorMarshalJSON: test`) } func ExampleMarshal() { var ( vint = 1 - vUrl, _ = url.Parse("https://example.org") + vURL, _ = url.Parse("https://example.org") bigRat = big.NewRat(100, 2) bigInt = big.NewInt(50) imt = &InvalidMarshalText{} - emj = &ErrorMarshalJson{} + emj = &ErrorMarshalJSON{} out []byte err error @@ -152,7 +152,7 @@ func ExampleMarshal() { out, err = libreflect.Marshal(&vint) fmt.Println(out, err) - out, err = libreflect.Marshal(vUrl) + out, err = libreflect.Marshal(vURL) fmt.Println(string(out), err) out, err = libreflect.Marshal(bigRat) @@ -167,14 +167,14 @@ func ExampleMarshal() { out, err = libreflect.Marshal(emj) fmt.Println(string(out), err) - //Output: - //[] <nil> - //[] <nil> - //https://example.org <nil> - //50 <nil> - //50 <nil> + // Output: + // [] <nil> + // [] <nil> + // https://example.org <nil> + // 50 <nil> + // 50 <nil> // Marshal: expecting first return as []byte got string - // Marshal: ErrorMarshalJson: test + // Marshal: ErrorMarshalJSON: test } func ExampleSet_bool() { @@ -221,12 +221,12 @@ func ExampleSet_bool() { fmt.Println("true:", mybool) } - //Output: - //YES: true - //TRUE: true - //False: false - //1: true - //true: true + // Output: + // YES: true + // TRUE: true + // False: false + // 1: true + // true: true } func ExampleSet_float() { @@ -252,9 +252,9 @@ func ExampleSet_float() { fmt.Println(myfloat) } - //Output: - //1.223 - //999.999 + // Output: + // 1.223 + // 999.999 } func ExampleSet_int() { @@ -304,12 +304,12 @@ func ExampleSet_int() { fmt.Println(vmyint) } - //Output: - //0 - //1 - //-128 - //error: Set: int16 value is overflow: 32768 - //32768 + // Output: + // 0 + // 1 + // -128 + // error: Set: int16 value is overflow: 32768 + // 32768 } func ExampleSet_sliceByte() { @@ -349,11 +349,11 @@ func ExampleSet_sliceByte() { fmt.Println(string(vmyBytes)) } - //Output: - //error: Set: object []uint8 is not setable - //a hero + // Output: + // error: Set: object []uint8 is not setable + // a hero // - //and I will write you a tragedy + // and I will write you a tragedy } func ExampleSet_sliceString() { @@ -383,16 +383,16 @@ func ExampleSet_sliceString() { fmt.Println(vstring) } - //Output: - //error: Set: object []string is not setable - //[a hero] - //[a hero and I will write you a tragedy] + // Output: + // error: Set: object []string is not setable + // [a hero] + // [a hero and I will write you a tragedy] } func ExampleSet_unmarshal() { var ( rat = big.NewRat(0, 1) - myUrl = &url.URL{} + myURL = &url.URL{} bigInt = big.NewInt(1) err error @@ -414,11 +414,11 @@ func ExampleSet_unmarshal() { } // This Set will call UnmarshalBinary on url.URL. - err = libreflect.Set(reflect.ValueOf(myUrl), "https://kilabit.info") + err = libreflect.Set(reflect.ValueOf(myURL), "https://kilabit.info") if err != nil { fmt.Println("error:", err) } else { - fmt.Println(myUrl) + fmt.Println(myURL) } // This Set will call UnmarshalJSON. @@ -436,12 +436,12 @@ func ExampleSet_unmarshal() { fmt.Println(bigInt) } - //Output: - //1.2340 - //0.0000 - //https://kilabit.info - //123456 - //0 + // Output: + // 1.2340 + // 0.0000 + // https://kilabit.info + // 123456 + // 0 } func ExampleTag() { @@ -469,10 +469,10 @@ func ExampleTag() { val, opts, hasTag = libreflect.Tag(field, "atag") fmt.Println(val, opts, hasTag) } - //Output: - //f1 [opt1 opt2 ] true - //F2 [opt1] false - //F3 [] false + // Output: + // f1 [opt1 opt2 ] true + // F2 [opt1] false + // F3 [] false // [] false } @@ -521,12 +521,12 @@ func ExampleUnmarshal_unmarshalBinary() { } fmt.Println(ptrB, ok) - //Output: - // false - //https://kilabit.info true - //<nil> false - //https://kilabit.info true - //https://kilabit.info true + // Output: + // false + // https://kilabit.info true + // <nil> false + // https://kilabit.info true + // https://kilabit.info true } func ExampleUnmarshal_unmarshalText() { @@ -551,11 +551,11 @@ func ExampleUnmarshal_unmarshalText() { fmt.Println(r) } } - //Output: - //0/1 - //15432/125 - //123456/1 - //123456/1 + // Output: + // 0/1 + // 15432/125 + // 123456/1 + // 123456/1 } func ExampleUnmarshal_unmarshalJSON() { @@ -579,8 +579,8 @@ func ExampleUnmarshal_unmarshalJSON() { fmt.Println(bigInt) } } - //Output: - //Unmarshal: math/big: cannot unmarshal "123.456" into a *big.Int - //123456 - //123456 + // Output: + // Unmarshal: math/big: cannot unmarshal "123.456" into a *big.Int + // 123456 + // 123456 } diff --git a/lib/reflect/reflect.go b/lib/reflect/reflect.go index ae0238d7..41790c55 100644 --- a/lib/reflect/reflect.go +++ b/lib/reflect/reflect.go @@ -60,10 +60,14 @@ func IsEqual(x, y interface{}) bool { // or slice and its value is `nil`; otherwise it will return false. func IsNil(v interface{}) bool { var val = reflect.ValueOf(v) + var kind = val.Kind() - switch val.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice: + if kind == reflect.Chan || + kind == reflect.Func || + kind == reflect.Interface || + kind == reflect.Map || + kind == reflect.Ptr || + kind == reflect.Slice { return val.IsNil() } return v == nil @@ -188,14 +192,17 @@ func Set(obj reflect.Value, val string) (err error) { } } - switch objKind { - case reflect.Invalid: + if objKind == reflect.Invalid { return fmt.Errorf("%s: object %T is invalid", logp, obj) - - case reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.UnsafePointer: + } + if objKind == reflect.Array || + objKind == reflect.Chan || + objKind == reflect.Func || + objKind == reflect.Map || + objKind == reflect.UnsafePointer { return fmt.Errorf("%s: object %T is not setable", logp, obj.Interface()) - - case reflect.Slice: + } + if objKind == reflect.Slice { objType = objType.Elem() objKind = objType.Kind() if objKind == reflect.Uint8 { @@ -210,12 +217,12 @@ func Set(obj reflect.Value, val string) (err error) { } objValue.Elem().Set(obj) } + return nil + } - default: - err = setValue(objValue, val) - if err != nil { - return fmt.Errorf("%s: %w", logp, err) - } + err = setValue(objValue, val) + if err != nil { + return fmt.Errorf(`%s: %w`, logp, err) } return nil } @@ -385,7 +392,10 @@ func setValue(obj reflect.Value, val string) (err error) { } return nil - default: + case reflect.Invalid, reflect.Uintptr, + reflect.Complex64, reflect.Complex128, + reflect.Array, reflect.Chan, reflect.Func, reflect.Map, + reflect.Pointer, reflect.UnsafePointer: return fmt.Errorf("cannot convert %s to %s", val, objType) } @@ -586,6 +596,12 @@ func doEqual(v1, v2 reflect.Value) (err error) { } switch k1 { + case reflect.Invalid: + if k2 == reflect.Invalid { + return nil + } + return fmt.Errorf("expecting %s(%v), got %s(%v)", name1, k1, name2, k2) + case reflect.Bool: if v1.Bool() == v2.Bool() { return nil @@ -623,7 +639,7 @@ func doEqual(v1, v2 reflect.Value) (err error) { for x = 0; x < v1.Len(); x++ { err = doEqual(v1.Index(x), v2.Index(x)) if err != nil { - return fmt.Errorf("%s[%d]: %s", name1, x, err) + return fmt.Errorf(`%s[%d]: %w`, name1, x, err) } } return nil @@ -694,7 +710,7 @@ func doEqual(v1, v2 reflect.Value) (err error) { s2 = v2.Index(x) err = doEqual(s1, s2) if err != nil { - return fmt.Errorf("%s[%d]: %s", name1, x, err) + return fmt.Errorf(`%s[%d]: %w`, name1, x, err) } } return nil @@ -741,7 +757,7 @@ func doEqualMap(v1, v2 reflect.Value) (err error) { name = tipe.Name() err = doEqual(v1.MapIndex(keys[x]), v2.MapIndex(keys[x])) if err != nil { - return fmt.Errorf("Map[%s(%v)] %s", name, keys[x].Interface(), err) + return fmt.Errorf(`Map[%s(%v)] %w`, name, keys[x].Interface(), err) } } return nil @@ -792,7 +808,7 @@ func doEqualStruct(v1, v2 reflect.Value) (err error) { err = doEqual(f1, f2) if err != nil { - return fmt.Errorf("%s.%s: %s", v1Name, f1Name, err) + return fmt.Errorf(`%s.%s: %w`, v1Name, f1Name, err) } } return nil diff --git a/lib/smtp/client.go b/lib/smtp/client.go index 8e393bc2..d2310818 100644 --- a/lib/smtp/client.go +++ b/lib/smtp/client.go @@ -130,7 +130,7 @@ func (cl *Client) Authenticate(mech SaslMechanism, username, password string) ( initialResponse := base64.StdEncoding.EncodeToString(b) cmd = []byte("AUTH PLAIN " + initialResponse + "\r\n") default: - return nil, fmt.Errorf("client.Authenticate: unknown mechanism") + return nil, errors.New(`client.Authenticate: unknown mechanism`) } return cl.SendCommand(cmd) diff --git a/lib/smtp/mail_tx_example_test.go b/lib/smtp/mail_tx_example_test.go index f0032f22..7e824b26 100644 --- a/lib/smtp/mail_tx_example_test.go +++ b/lib/smtp/mail_tx_example_test.go @@ -31,22 +31,24 @@ func ExampleNewMailTx() { toAddresses = []byte("John <john@example.com>, Jane <jane@example.com>") subject = []byte(`Example subject`) bodyText = []byte(`Email body as plain text`) - bodyHtml = []byte(`Email body as <b>HTML</b>`) + bodyHTML = []byte(`Email body as <b>HTML</b>`) timeNowUtc = time.Unix(email.Epoch(), 0).UTC() dateNowUtc = timeNowUtc.Format(email.DateFormat) - recipients []string - mboxes []*email.Mailbox - msg *email.Message - mailtx *smtp.MailTx - data []byte - err error + mboxes []*email.Mailbox + msg *email.Message + mailtx *smtp.MailTx + data []byte + err error ) mboxes, err = email.ParseMailboxes(toAddresses) if err != nil { log.Fatal(err) } + + var recipients = make([]string, 0, len(mboxes)) + for _, mbox := range mboxes { recipients = append(recipients, mbox.Address) } @@ -56,7 +58,7 @@ func ExampleNewMailTx() { toAddresses, subject, bodyText, - bodyHtml, + bodyHTML, ) if err != nil { log.Fatal(err) @@ -95,29 +97,29 @@ func ExampleNewMailTx() { data = bytes.ReplaceAll(data, []byte(msgBoundary), []byte(fixedBoundary)) fmt.Printf("Tx Data:\n%s", data) - //Output: - //Tx From: Postmaster <postmaster@mail.example.com> - //Tx Recipients: [john@example.com jane@example.com] - //Tx Data: - //date: Wed, 23 Feb 2022 07:06:40 +0000 - //from: Noreply <noreply@example.com> - //to: John <john@example.com>, Jane <jane@example.com> - //subject: Example subject - //mime-version: 1.0 - //content-type: multipart/alternative; boundary=QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf - //message-id: <1645600000.QoqDPQfz@hostname> + // Output: + // Tx From: Postmaster <postmaster@mail.example.com> + // Tx Recipients: [john@example.com jane@example.com] + // Tx Data: + // date: Wed, 23 Feb 2022 07:06:40 +0000 + // from: Noreply <noreply@example.com> + // to: John <john@example.com>, Jane <jane@example.com> + // subject: Example subject + // mime-version: 1.0 + // content-type: multipart/alternative; boundary=QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf + // message-id: <1645600000.QoqDPQfz@hostname> // - //--QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf - //mime-version: 1.0 - //content-type: text/plain; charset="utf-8" - //content-transfer-encoding: quoted-printable + // --QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf + // mime-version: 1.0 + // content-type: text/plain; charset="utf-8" + // content-transfer-encoding: quoted-printable // - //Email body as plain text - //--QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf - //mime-version: 1.0 - //content-type: text/html; charset="utf-8" - //content-transfer-encoding: quoted-printable + // Email body as plain text + // --QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf + // mime-version: 1.0 + // content-type: text/html; charset="utf-8" + // content-transfer-encoding: quoted-printable // - //Email body as <b>HTML</b> - //--QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf-- + // Email body as <b>HTML</b> + // --QoqDPQfzDVkv5R49vrA78GmqPmlfmBHf-- } diff --git a/lib/smtp/receiver.go b/lib/smtp/receiver.go index 6a0fa92c..905f2bbc 100644 --- a/lib/smtp/receiver.go +++ b/lib/smtp/receiver.go @@ -6,6 +6,7 @@ package smtp import ( "bytes" + "errors" "fmt" "io" "log" @@ -126,8 +127,7 @@ func (recv *receiver) readCommand() (cmd *Command, err error) { if err == io.EOF { break } - err = fmt.Errorf("smtp: recv: readCommand: " + err.Error()) - return nil, err + return nil, fmt.Errorf(`smtp: recv: readCommand: %w`, err) } if n == cap(recv.data) { continue @@ -137,8 +137,7 @@ func (recv *receiver) readCommand() (cmd *Command, err error) { err = cmd.unpack(recv.buff.Bytes()) if err != nil { - err = fmt.Errorf("smtp: cmd.unpack: " + err.Error()) - return nil, err + return nil, fmt.Errorf(`smtp: cmd.unpack: %w`, err) } return cmd, nil @@ -177,8 +176,9 @@ func (recv *receiver) reset() { } func (recv *receiver) sendError(errRes error) (err error) { - reply, ok := errRes.(*liberrors.E) - if !ok { + var reply *liberrors.E + + if !errors.As(errRes, &reply) { reply = &liberrors.E{} reply.Code = StatusLocalError reply.Message = errRes.Error() diff --git a/lib/smtp/server.go b/lib/smtp/server.go index 61279172..5459f6f0 100644 --- a/lib/smtp/server.go +++ b/lib/smtp/server.go @@ -8,6 +8,7 @@ import ( "bytes" "crypto/tls" "encoding/base64" + "errors" "fmt" "log" "net" @@ -78,7 +79,7 @@ type Server struct { func (srv *Server) LoadCertificate(certFile, keyFile string) (err error) { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { - return fmt.Errorf("smtp: LoadCertificate: " + err.Error()) + return fmt.Errorf(`smtp: LoadCertificate: %w`, err) } srv.TLSCert = &cert @@ -519,10 +520,10 @@ func (srv *Server) handleVRFY(recv *receiver, cmd *Command) (err error) { // initialize handler, storage, extensions, and listeners. func (srv *Server) initialize() (err error) { if srv.Env == nil { - return fmt.Errorf("smtp: server environment is not defined") + return errors.New(`smtp: server environment is not defined`) } if srv.Env.PrimaryDomain == nil { - return fmt.Errorf("smtp: server primary domain is not defined") + return errors.New(`smtp: server primary domain is not defined`) } if srv.Handler == nil { @@ -563,7 +564,7 @@ func (srv *Server) initListener() (err error) { } if srv.TLSCert == nil { - return fmt.Errorf("smtp: server certificate is not defined") + return errors.New(`smtp: server certificate is not defined`) } tlsCfg := &tls.Config{ diff --git a/lib/spf/macro.go b/lib/spf/macro.go index e8c816ee..8a6e32d8 100644 --- a/lib/spf/macro.go +++ b/lib/spf/macro.go @@ -6,6 +6,7 @@ package spf import ( "bytes" + "errors" "fmt" "net" "strconv" @@ -164,14 +165,14 @@ func (m *macro) parse(data []byte) (err error) { } if x == len(data) { - return fmt.Errorf("missing closing '}'") + return errors.New(`missing closing '}'`) } } if data[x] == 'r' { m.isReversed = true x++ if x == len(data) { - return fmt.Errorf("missing closing '}'") + return errors.New(`missing closing '}'`) } } if data[x] != '}' { @@ -183,7 +184,7 @@ func (m *macro) parse(data []byte) (err error) { break } if x == len(data) { - return fmt.Errorf("missing closing '}'") + return errors.New(`missing closing '}'`) } if data[x] != '}' { return fmt.Errorf("missing closing '}', got '%c'", data[x]) @@ -263,8 +264,10 @@ func (m *macro) expandLetter() (value []byte) { case macroExpDomain: value = m.ref.Hostname case macroExpCurTime: - now := time.Now() - strNow := fmt.Sprintf("%d", now.Unix()) + var ( + now = time.Now() + strNow = strconv.FormatInt(now.Unix(), 10) + ) value = []byte(strNow) } return value diff --git a/lib/sql/client.go b/lib/sql/client.go index c281dab8..344ed76b 100644 --- a/lib/sql/client.go +++ b/lib/sql/client.go @@ -49,6 +49,7 @@ func NewClient(opts ClientOptions) (cl *Client, err error) { // FetchTableNames return the table names in current database schema sorted // in ascending order. func (cl *Client) FetchTableNames() (tableNames []string, err error) { + var logp = `FetchTableNames` var q, v string switch cl.DriverName { @@ -63,27 +64,31 @@ func (cl *Client) FetchTableNames() (tableNames []string, err error) { ` } - rows, err := cl.DB.Query(q) + var rows *sql.Rows + + rows, err = cl.DB.Query(q) if err != nil { - return nil, fmt.Errorf("FetchTableNames: " + err.Error()) + return nil, fmt.Errorf(`%s: %w`, logp, err) } if len(cl.TableNames) > 0 { cl.TableNames = cl.TableNames[:0] } + defer func() { + _ = rows.Close() + }() for rows.Next() { err = rows.Scan(&v) if err != nil { - _ = rows.Close() - return cl.TableNames, err + return cl.TableNames, fmt.Errorf(`%s: %w`, logp, err) } cl.TableNames = append(cl.TableNames, v) } err = rows.Err() if err != nil { - return nil, err + return nil, fmt.Errorf(`%s: %w`, logp, err) } return cl.TableNames, nil @@ -313,7 +318,7 @@ func (cl *Client) TruncateTable(tableName string) (err error) { _, err = cl.DB.Exec(q) if err != nil { - return fmt.Errorf("TruncateTable %q: %s", tableName, err) + return fmt.Errorf(`TruncateTable %q: %w`, tableName, err) } return nil } diff --git a/lib/sql/row.go b/lib/sql/row.go index 1fdbfb7b..693ee51e 100644 --- a/lib/sql/row.go +++ b/lib/sql/row.go @@ -14,7 +14,7 @@ import ( // the column's value. // This type can be used to create dynamic insert-update fields. // -// DEPRECATED: use [Meta] instead. +// Deprecated: use [Meta] instead. type Row map[string]interface{} // Meta convert the Row into Meta. diff --git a/lib/ssh/client.go b/lib/ssh/client.go index 68276dce..ff4f9a6e 100644 --- a/lib/ssh/client.go +++ b/lib/ssh/client.go @@ -293,9 +293,11 @@ func (cl *Client) Close() (err error) { // Execute a command on remote server. func (cl *Client) Execute(ctx context.Context, cmd string) (err error) { - sess, err := cl.Client.NewSession() + var sess *ssh.Session + + sess, err = cl.Client.NewSession() if err != nil { - return fmt.Errorf("ssh: NewSession: " + err.Error()) + return fmt.Errorf(`ssh: NewSession: %w`, err) } sess.Stdout = cl.stdout diff --git a/lib/ssh/config/config.go b/lib/ssh/config/config.go index 98a8fb34..dfc64086 100644 --- a/lib/ssh/config/config.go +++ b/lib/ssh/config/config.go @@ -88,10 +88,7 @@ func Load(file string) (cfg *Config, err error) { var p *parser - p, err = newParser(cfg) - if err != nil { - return nil, fmt.Errorf("%s %s: %w", logp, file, err) - } + p = newParser(cfg) var lines []string diff --git a/lib/ssh/config/config_test.go b/lib/ssh/config/config_test.go index 6ba52c53..1e5a8cf8 100644 --- a/lib/ssh/config/config_test.go +++ b/lib/ssh/config/config_test.go @@ -27,10 +27,7 @@ func TestMain(m *testing.M) { log.Fatal(err) } - testParser, err = newParser(dummyConfig) - if err != nil { - log.Fatal(err) - } + testParser = newParser(dummyConfig) testDefaultSection = NewSection(dummyConfig, ``) testDefaultSection.setDefaults() diff --git a/lib/ssh/config/match_criteria.go b/lib/ssh/config/match_criteria.go index f07b4fcf..1dc7f55c 100644 --- a/lib/ssh/config/match_criteria.go +++ b/lib/ssh/config/match_criteria.go @@ -99,11 +99,11 @@ func (mcriteria *matchCriteria) isMatch(s string) bool { } return true case criteriaCanonical: - //TODO + // TODO case criteriaExec: - //TODO + // TODO case criteriaFinal: - //TODO + // TODO case criteriaHost, criteriaLocalUser, criteriaOriginalHost, criteriaUser: for _, pat := range mcriteria.patterns { if pat.isMatch(s) { diff --git a/lib/ssh/config/parser.go b/lib/ssh/config/parser.go index 3ffef0a7..48f232f4 100644 --- a/lib/ssh/config/parser.go +++ b/lib/ssh/config/parser.go @@ -21,14 +21,14 @@ type parser struct { homeDir string } -func newParser(cfg *Config) (p *parser, err error) { +func newParser(cfg *Config) (p *parser) { p = &parser{ files: make(map[string]struct{}), workDir: cfg.workDir, homeDir: cfg.homeDir, } - return p, nil + return p } // load the config file(s) using glob(7) pattern and convert them into lines. diff --git a/lib/ssh/config/parser_test.go b/lib/ssh/config/parser_test.go index a3a40222..311b9534 100644 --- a/lib/ssh/config/parser_test.go +++ b/lib/ssh/config/parser_test.go @@ -137,10 +137,7 @@ func TestConfigParser_load(t *testing.T) { }} for _, c := range cases { - p, err := newParser(dummyConfig) - if err != nil { - t.Fatal(err) - } + var p = newParser(dummyConfig) got, err := p.load(c.dir, c.pattern) if err != nil { diff --git a/lib/ssh/config/section.go b/lib/ssh/config/section.go index 37e7d90a..5a104587 100644 --- a/lib/ssh/config/section.go +++ b/lib/ssh/config/section.go @@ -349,12 +349,11 @@ func (section *Section) Signers() (signers []ssh.Signer, err error) { var ( logp = `Signers` - pkeyFile string - pkeyPem []byte - pass []byte - signer ssh.Signer - pkey any - isMissingPass bool + pkeyFile string + pkeyPem []byte + pass []byte + signer ssh.Signer + pkey any ) for _, pkeyFile = range section.IdentityFile { @@ -368,8 +367,9 @@ func (section *Section) Signers() (signers []ssh.Signer, err error) { pkey, err = ssh.ParseRawPrivateKey(pkeyPem) if err != nil { - _, isMissingPass = err.(*ssh.PassphraseMissingError) - if !isMissingPass { + var errMissingPass *ssh.PassphraseMissingError + + if !errors.As(err, &errMissingPass) { return nil, fmt.Errorf(`%s: %w`, logp, err) } diff --git a/lib/ssh/sftp/sftp_test.go b/lib/ssh/sftp/sftp_test.go index 7b9f3dd3..7b9c1228 100644 --- a/lib/ssh/sftp/sftp_test.go +++ b/lib/ssh/sftp/sftp_test.go @@ -57,14 +57,14 @@ func TestMain(m *testing.M) { fmt.Printf("Server version: %d\n", testClient.version) fmt.Printf("Server extensions: %v\n", testClient.exts) - defer func() { - var errClose = testClient.Close() - if errClose != nil { - log.Printf(`TestMain: %s`, errClose) - } - }() + var status = m.Run() - os.Exit(m.Run()) + err = testClient.Close() + if err != nil { + log.Printf(`TestMain: %s`, err) + } + + os.Exit(status) } func TestErrFailure(t *testing.T) { diff --git a/lib/strings/strings.go b/lib/strings/strings.go index 33726f81..4c9dd027 100644 --- a/lib/strings/strings.go +++ b/lib/strings/strings.go @@ -258,9 +258,7 @@ func Swap(ss []string, x, y int) { return } - tmp := ss[x] - ss[x] = ss[y] - ss[y] = tmp + ss[x], ss[y] = ss[y], ss[x] } // TotalFrequencyOfTokens return total frequency of list of token in words. diff --git a/lib/strings/to.go b/lib/strings/to.go index 662c37c9..a00f8df1 100644 --- a/lib/strings/to.go +++ b/lib/strings/to.go @@ -5,6 +5,7 @@ package strings import ( + "errors" "fmt" "strconv" ) @@ -47,8 +48,9 @@ func ToInt64(ss []string) (sv []int64) { } // Handle error, try to convert to float64 first. - ev := e.(*strconv.NumError) - if ev.Err == strconv.ErrSyntax { + var ev *strconv.NumError + + if errors.As(e, &ev) && ev.Err == strconv.ErrSyntax { f, e := strconv.ParseFloat(s, 64) if e == nil { v = int64(f) diff --git a/lib/telemetry/buffer_forwarder_example_test.go b/lib/telemetry/buffer_forwarder_example_test.go index 0ad80c38..6f043ca3 100644 --- a/lib/telemetry/buffer_forwarder_example_test.go +++ b/lib/telemetry/buffer_forwarder_example_test.go @@ -47,7 +47,8 @@ func ExampleBufferForwarder() { ) err = agent.Forward(ctx, m) if err != nil { - log.Fatal(err) + log.Println(err) + return } fmt.Printf(`%s`, bufFwd.Bytes()) @@ -59,7 +60,8 @@ func ExampleBufferForwarder() { } err = agent.BulkForward(ctx, list) if err != nil { - log.Fatal(err) + log.Println(err) + return } fmt.Printf(`%s`, bufFwd.Bytes()) diff --git a/lib/telemetry/internal/cmd/agent-example/main.go b/lib/telemetry/internal/cmd/agent-example/main.go index 1c78d99d..fc407741 100644 --- a/lib/telemetry/internal/cmd/agent-example/main.go +++ b/lib/telemetry/internal/cmd/agent-example/main.go @@ -6,7 +6,6 @@ package main import ( - "log" "os" "os/signal" "regexp" @@ -55,12 +54,8 @@ func main() { func createGoMetricsCollector() (col *telemetry.GoMetricsCollector) { var ( metricsFilter *regexp.Regexp - err error ) - metricsFilter, err = regexp.Compile(`^go_(cpu|gc|memory|sched)_.*$`) - if err != nil { - log.Fatal(err) - } + metricsFilter = regexp.MustCompile(`^go_(cpu|gc|memory|sched)_.*$`) col = telemetry.NewGoMetricsCollector(metricsFilter) return col } @@ -68,12 +63,8 @@ func createGoMetricsCollector() (col *telemetry.GoMetricsCollector) { func createGoMemStatsCollector() (col *telemetry.GoMemStatsCollector) { var ( metricsFilter *regexp.Regexp - err error ) - metricsFilter, err = regexp.Compile(`^.*$`) - if err != nil { - log.Fatal(err) - } + metricsFilter = regexp.MustCompile(`^.*$`) col = telemetry.NewGoMemStatsCollector(metricsFilter) return col } diff --git a/lib/test/data.go b/lib/test/data.go index a280b94e..4ef71877 100644 --- a/lib/test/data.go +++ b/lib/test/data.go @@ -133,7 +133,6 @@ func LoadDataDir(path string) (listData []*Data, err error) { dir *os.File listfi []os.FileInfo - listTestTxt []string fi os.FileInfo data *Data name string @@ -150,6 +149,8 @@ func LoadDataDir(path string) (listData []*Data, err error) { return nil, fmt.Errorf("%s: %w", logp, err) } + var listTestTxt = make([]string, 0, len(listfi)) + for _, fi = range listfi { if fi.Size() == 0 || fi.IsDir() { continue @@ -164,7 +165,6 @@ func LoadDataDir(path string) (listData []*Data, err error) { pathTestTxt = filepath.Join(path, name) listTestTxt = append(listTestTxt, pathTestTxt) } - if len(listTestTxt) == 0 { return listData, nil } diff --git a/lib/text/diff/diffinterface.go b/lib/text/diff/diffinterface.go index f8c89767..58fd88d1 100644 --- a/lib/text/diff/diffinterface.go +++ b/lib/text/diff/diffinterface.go @@ -6,6 +6,7 @@ package diff import ( "bufio" + "errors" "io" "os" @@ -47,7 +48,7 @@ func ReadLines(f string) (lines text.Lines, e error) { for { line, e = reader.ReadBytes(DefDelimiter) if e != nil { - if e == io.EOF { + if errors.Is(e, io.EOF) { break } return lines, e diff --git a/lib/time/time.go b/lib/time/time.go index 2a67c2db..221b0691 100644 --- a/lib/time/time.go +++ b/lib/time/time.go @@ -13,9 +13,7 @@ import ( // timeNow returns the current local time. // This is a variable that can be override to mock the current time during // testing. -var timeNow = func() time.Time { - return time.Now() -} +var timeNow = time.Now // ShortDayNames contains list of day name in English, in shorter. var ShortDayNames = []string{`Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`, `Sun`} diff --git a/lib/time/time_example_test.go b/lib/time/time_example_test.go index c0926ec1..7060d47c 100644 --- a/lib/time/time_example_test.go +++ b/lib/time/time_example_test.go @@ -12,13 +12,13 @@ import ( func ExampleMicrosecond() { nano := time.Unix(1612331000, 123456789) fmt.Printf("%d", Microsecond(&nano)) - //Output: - //123456 + // Output: + // 123456 } func ExampleUnixMilliString() { nano := time.Unix(1612331000, 123456789) fmt.Printf("%s", UnixMilliString(nano)) - //Output: - //1612331000123 + // Output: + // 1612331000123 } diff --git a/lib/totp/totp.go b/lib/totp/totp.go index 77e90a00..8a472b4a 100644 --- a/lib/totp/totp.go +++ b/lib/totp/totp.go @@ -211,7 +211,7 @@ func (p *Protocol) generateWithTimestamp(mac hash.Hash, time int64) (otp string, binary |= int(vbytes[offset+2]&0xff) << 8 binary |= int(vbytes[offset+3] & 0xff) - binary = binary % _digitsPower[p.codeDigits] + binary %= _digitsPower[p.codeDigits] fmtZeroPadding = fmt.Sprintf(`%%0%dd`, p.codeDigits) diff --git a/lib/websocket/client.go b/lib/websocket/client.go index 858255c5..7a8d07b7 100644 --- a/lib/websocket/client.go +++ b/lib/websocket/client.go @@ -610,7 +610,7 @@ func (cl *Client) handleFrame(frame *Frame) (isClosing bool) { func (cl *Client) handleHandshake(keyAccept string, resp []byte) (rest []byte, err error) { var httpRes *http.Response - httpRes, rest, err = libhttp.ParseResponseHeader(resp) + httpRes, rest, err = libhttp.ParseResponseHeader(resp) //nolint: bodyclose if err != nil { return nil, err } diff --git a/lib/websocket/server_bench_test.go b/lib/websocket/server_bench_test.go index 7a854191..d63b7c57 100644 --- a/lib/websocket/server_bench_test.go +++ b/lib/websocket/server_bench_test.go @@ -6,6 +6,7 @@ package websocket import ( + "context" "crypto/rand" "encoding/base64" "fmt" @@ -245,10 +246,11 @@ func BenchmarkUpgrader(b *testing.B) { func mustMakeRequest(method string, headers http.Header) (req *http.Request) { var ( + ctx = context.Background() err error ) - req, err = http.NewRequest(method, "ws://example.org", nil) + req, err = http.NewRequestWithContext(ctx, method, `ws://example.org`, nil) if err != nil { panic(err) } diff --git a/lib/websocket/server_test.go b/lib/websocket/server_test.go index d6987843..fe8d640a 100644 --- a/lib/websocket/server_test.go +++ b/lib/websocket/server_test.go @@ -6,6 +6,7 @@ package websocket import ( "bytes" + "context" "fmt" "net" "net/http" @@ -273,14 +274,25 @@ func TestServerHandshake(t *testing.T) { func TestServer_Health(t *testing.T) { var ( - res *http.Response - err error + ctx = context.Background() + url = `http://` + _testAddr + `/status` + + httpReq *http.Request + err error ) - res, err = http.Get("http://" + _testAddr + "/status") + httpReq, err = http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + t.Fatal(err) + } + + var res *http.Response + + res, err = http.DefaultClient.Do(httpReq) if err != nil { t.Fatal(err) } + _ = res.Body.Close() test.Assert(t, "/status response code", http.StatusOK, res.StatusCode) } diff --git a/lib/websocket/websocket_test.go b/lib/websocket/websocket_test.go index fed5fef6..ed205692 100644 --- a/lib/websocket/websocket_test.go +++ b/lib/websocket/websocket_test.go @@ -6,7 +6,7 @@ package websocket import ( "context" - "fmt" + "errors" "log" "os" "strconv" @@ -85,7 +85,7 @@ func testHandleAuth(req *Handshake) (ctx context.Context, err error) { extJWT = q.Get(_qKeyTicket) if len(extJWT) == 0 { - return nil, fmt.Errorf("Missing authorization") + return nil, errors.New(`Missing authorization`) } ctx = context.WithValue(context.Background(), CtxKeyExternalJWT, extJWT) diff --git a/lib/xmlrpc/client.go b/lib/xmlrpc/client.go index 1ea5c6b0..47af5c44 100644 --- a/lib/xmlrpc/client.go +++ b/lib/xmlrpc/client.go @@ -6,6 +6,7 @@ package xmlrpc import ( "bytes" + "context" "fmt" "net/http" "net/url" @@ -75,19 +76,27 @@ func (cl *Client) Close() { func (cl *Client) Send(req Request) (resp Response, err error) { var ( logp = "Client.Send" + + xmlbin []byte ) - xmlbin, _ := req.MarshalText() - reqBody := bytes.NewReader(xmlbin) + xmlbin, _ = req.MarshalText() + var reqBody = bytes.NewReader(xmlbin) + + var ( + ctx = context.Background() + + httpRequest *http.Request + ) - httpRequest, err := http.NewRequest("POST", cl.url.String(), reqBody) + httpRequest, err = http.NewRequestWithContext(ctx, `POST`, cl.url.String(), reqBody) if err != nil { return resp, fmt.Errorf("%s: %w", logp, err) } httpRequest.Header.Set(libhttp.HeaderContentType, libhttp.ContentTypeXML) - _, resBody, err := cl.conn.Do(httpRequest) + _, resBody, err := cl.conn.Do(httpRequest) //nolint: bodyclose if err != nil { return resp, fmt.Errorf("%s: %w", logp, err) } diff --git a/lib/xmlrpc/value.go b/lib/xmlrpc/value.go index 51894573..9144c22c 100644 --- a/lib/xmlrpc/value.go +++ b/lib/xmlrpc/value.go @@ -185,6 +185,8 @@ func (v *Value) String() string { buf.WriteString("<value>") switch v.Kind { + case Unset: + // NOOP. case String: fmt.Fprintf(&buf, "<string>%s</string>", v.In.(string)) case Boolean: diff --git a/lib/xmlrpc/value_example_test.go b/lib/xmlrpc/value_example_test.go index bdfafdfc..5933e5b8 100644 --- a/lib/xmlrpc/value_example_test.go +++ b/lib/xmlrpc/value_example_test.go @@ -58,14 +58,14 @@ func ExampleValue_GetFieldAsBoolean() { fmt.Println("Get string field as boolean:") fmt.Println(res.Param.GetFieldAsBoolean("string_0")) fmt.Println(res.Param.GetFieldAsBoolean("string_1")) - //Output: - //Get boolean field as string: - //false - //true - //Get boolean field as boolean: - //false - //true - //Get string field as boolean: - //false - //false + // Output: + // Get boolean field as string: + // false + // true + // Get boolean field as boolean: + // false + // true + // Get string field as boolean: + // false + // false } |
