diff options
| author | Shulhan <ms@kilabit.info> | 2023-12-13 01:20:26 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2023-12-13 01:20:26 +0700 |
| commit | 77c0cbe885985e6ccaf530226a34b24fef65b27e (patch) | |
| tree | bf43f4b7cd879561fc837315a53cf815da473244 | |
| parent | bb198ad2d7a3f26c8ee0f32abfc8384c79df404f (diff) | |
| download | pakakeh.go-77c0cbe885985e6ccaf530226a34b24fef65b27e.tar.xz | |
all: fix linter warnings reported by revive
There are some reports that I disagree with revive, in example, code
should not declare the type after variables.
In my opinion, on some cases, declaring the type make the code more
readable and explicit.
Since I did not want to add new configuration file, we changes it and
follow revive for now.
77 files changed, 401 insertions, 416 deletions
diff --git a/api/slack/message.go b/api/slack/message.go index 6325f0d4..2a62c200 100644 --- a/api/slack/message.go +++ b/api/slack/message.go @@ -9,6 +9,6 @@ type Message struct { Channel string `json:"channel,omitempty"` Username string `json:"username,omitempty"` IconEmoji string `json:"icon_emoji,omitempty"` - IconUrl string `json:"icon_url,omitempty"` + IconUrl string `json:"icon_url,omitempty"` //revive:disable-line Text string `json:"text"` } diff --git a/api/slack/slack.go b/api/slack/slack.go index dca2e3b1..6ed1906e 100644 --- a/api/slack/slack.go +++ b/api/slack/slack.go @@ -15,7 +15,7 @@ import ( ) // PostWebhook send a message using "Incoming Webhook". -func PostWebhook(webhookUrl string, msg *Message) (err error) { +func PostWebhook(webhookURL string, msg *Message) (err error) { var ( logp = `PostWebhook` @@ -29,7 +29,7 @@ func PostWebhook(webhookUrl string, msg *Message) (err error) { var res *http.Response - res, err = http.DefaultClient.Post(webhookUrl, `application/json`, bytes.NewReader(payload)) + res, err = http.DefaultClient.Post(webhookURL, `application/json`, bytes.NewReader(payload)) if err != nil { return fmt.Errorf(`%s: %w`, logp, err) } diff --git a/cmd/sendemail/main.go b/cmd/sendemail/main.go index 3289b7d0..1738af6a 100644 --- a/cmd/sendemail/main.go +++ b/cmd/sendemail/main.go @@ -13,8 +13,8 @@ import ( ) const ( - envSmtpUsername = "SMTP_USERNAME" - envSmtpPassword = "SMTP_PASSWORD" + envSMTPUsername = `SMTP_USERNAME` + envSMTPPassword = `SMTP_PASSWORD` ) func main() { @@ -30,8 +30,8 @@ func main() { to string subject string fileBodyText string - fileBodyHtml string - serverUrl string + fileBodyHTML string + serverURL string content []byte mailb []byte @@ -47,7 +47,7 @@ func main() { flag.StringVar(&to, "to", "", "Set the recipients.") flag.StringVar(&subject, "subject", "", "Set the subject.") flag.StringVar(&fileBodyText, "bodytext", "", "Set the text body from content of file.") - flag.StringVar(&fileBodyHtml, "bodyhtml", "", "Set the HTML body from content of file.") + flag.StringVar(&fileBodyHTML, `bodyhtml`, ``, `Set the HTML body from content of file.`) flag.Usage = usage flag.Parse() @@ -56,8 +56,8 @@ func main() { os.Exit(1) } - serverUrl = flag.Arg(0) - if len(serverUrl) == 0 { + serverURL = flag.Arg(0) + if len(serverURL) == 0 { log.Printf("missing server URL") os.Exit(1) } @@ -88,7 +88,7 @@ func main() { } msg.SetSubject(subject) - if len(fileBodyText) == 0 && len(fileBodyHtml) == 0 { + if len(fileBodyText) == 0 && len(fileBodyHTML) == 0 { log.Printf("missing -bodytext or -bodyhtml") os.Exit(1) } @@ -101,8 +101,8 @@ func main() { _ = msg.SetBodyText(content) } - if len(fileBodyHtml) > 0 { - content, err = os.ReadFile(fileBodyHtml) + if len(fileBodyHTML) > 0 { + content, err = os.ReadFile(fileBodyHTML) if err != nil { log.Println(err) } @@ -120,9 +120,9 @@ func main() { mailtx = smtp.NewMailTx(from, []string{to}, mailb) clientOpts = smtp.ClientOptions{ - ServerUrl: serverUrl, - AuthUser: os.Getenv(envSmtpUsername), - AuthPass: os.Getenv(envSmtpPassword), + ServerUrl: serverURL, + AuthUser: os.Getenv(envSMTPUsername), + AuthPass: os.Getenv(envSMTPPassword), AuthMechanism: smtp.SaslMechanismPlain, } diff --git a/lib/clise/clise.go b/lib/clise/clise.go index 61a7bb99..a3acbbdd 100644 --- a/lib/clise/clise.go +++ b/lib/clise/clise.go @@ -114,8 +114,9 @@ func (c *Clise) Reset() { // last item to the recent item. func (c *Clise) Slice() (dst []interface{}) { var ( + end = c.size + start int - end int = c.size ) c.Lock() diff --git a/lib/clise/clise_example_test.go b/lib/clise/clise_example_test.go index 99fad29b..de2cd5ed 100644 --- a/lib/clise/clise_example_test.go +++ b/lib/clise/clise_example_test.go @@ -4,7 +4,7 @@ import "fmt" func ExampleClise_Pop() { var ( - c *Clise = New(5) + c = New(5) item interface{} ) @@ -23,7 +23,7 @@ func ExampleClise_Pop() { } func ExampleClise_RecentSlice() { - var c *Clise = New(5) + var c = New(5) c.Push(1, 2, 3) fmt.Println(c.RecentSlice()) c.Push(4, 5, 6, 7) @@ -34,7 +34,7 @@ func ExampleClise_RecentSlice() { } func ExampleClise_Reset() { - var c *Clise = New(5) + var c = New(5) c.Push(1, 2, 3, 4, 5) fmt.Println(c.Slice()) c.Reset() @@ -46,7 +46,7 @@ func ExampleClise_Reset() { } func ExampleClise_Slice() { - var c *Clise = New(5) + var c = New(5) c.Push(1, 2) fmt.Println(c.Slice()) c.Push(3, 4, 5) diff --git a/lib/clise/example_test.go b/lib/clise/example_test.go index df647390..d37cbd1a 100644 --- a/lib/clise/example_test.go +++ b/lib/clise/example_test.go @@ -54,7 +54,7 @@ func ExampleClise_MarshalJSON() { func ExampleClise_UnmarshalJSON() { var ( - clise *Clise = New(3) + clise = New(3) cases = []string{ `{"k":1}`, // Non array. @@ -64,12 +64,12 @@ func ExampleClise_UnmarshalJSON() { `["MarshalJSON",{"Int":1,"String":"Hello"},{"Int":2,"String":"world"}]`, } - rawJson string + rawJSON string err error ) - for _, rawJson = range cases { - err = clise.UnmarshalJSON([]byte(rawJson)) + for _, rawJSON = range cases { + err = clise.UnmarshalJSON([]byte(rawJSON)) if err != nil { fmt.Println(err) } else { diff --git a/lib/crypto/crypto.go b/lib/crypto/crypto.go index 3b45258e..bf78d376 100644 --- a/lib/crypto/crypto.go +++ b/lib/crypto/crypto.go @@ -39,8 +39,8 @@ var ErrStdinPassphrase = errors.New(`cannot read passhprase from stdin`) // List of environment variables reads when reading passphrase // interactively. const ( - envKeySshAskpassRequire = `SSH_ASKPASS_REQUIRE` - envKeySshAskpass = `SSH_ASKPASS` + envKeySSHAskpassRequire = `SSH_ASKPASS_REQUIRE` + envKeySSHAskpass = `SSH_ASKPASS` envKeyDisplay = `DISPLAY` ) @@ -186,7 +186,7 @@ func LoadPrivateKeyInteractive(termrw io.ReadWriter, file string) (pkey crypto.P } var ( - askpassRequire = os.Getenv(envKeySshAskpassRequire) + askpassRequire = os.Getenv(envKeySSHAskpassRequire) pass string ) @@ -280,7 +280,7 @@ func sshAskpass(askpassRequire string) (pass string, err error) { } } - val = os.Getenv(envKeySshAskpass) + val = os.Getenv(envKeySSHAskpass) if len(val) == 0 { return ``, ErrStdinPassphrase } diff --git a/lib/crypto/crypto_test.go b/lib/crypto/crypto_test.go index b069849c..72c9aec9 100644 --- a/lib/crypto/crypto_test.go +++ b/lib/crypto/crypto_test.go @@ -89,8 +89,8 @@ func TestLoadPrivateKeyInteractive(t *testing.T) { // Environment variables for testing with SSH_ASKPASS and // SSH_ASKPASS_REQUIRE. envDisplay string - envSshAskpass string - envSshAskpassRequire string + envSSHAskpass string + envSSHAskpassRequire string } var ( @@ -130,41 +130,41 @@ func TestLoadPrivateKeyInteractive(t *testing.T) { desc: `withAskpassRequire=prefer`, file: `testdata/openssl_rsa_pass.key`, envDisplay: `:0`, - envSshAskpass: askpassProgram, - envSshAskpassRequire: `prefer`, + envSSHAskpass: askpassProgram, + envSSHAskpassRequire: `prefer`, }, { desc: `withAskpassRequire=prefer, no DISPLAY`, file: `testdata/openssl_rsa_pass.key`, - envSshAskpass: askpassProgram, - envSshAskpassRequire: `prefer`, + envSSHAskpass: askpassProgram, + envSSHAskpassRequire: `prefer`, expError: `LoadPrivateKeyInteractive: cannot read passhprase from stdin`, }, { desc: `withAskpassRequire=prefer, empty SSH_ASKPASS`, file: `testdata/openssl_rsa_pass.key`, envDisplay: `:0`, - envSshAskpassRequire: `prefer`, + envSSHAskpassRequire: `prefer`, expError: `LoadPrivateKeyInteractive: cannot read passhprase from stdin`, }, { desc: `withAskpassRequire=prefer, invalid program`, file: `testdata/openssl_rsa_pass.key`, envDisplay: `:0`, - envSshAskpass: `/invalid/program`, - envSshAskpassRequire: `prefer`, + envSSHAskpass: `/invalid/program`, + envSSHAskpassRequire: `prefer`, expError: `LoadPrivateKeyInteractive: fork/exec /invalid/program: no such file or directory`, }, { desc: `withAskpassRequire=force`, file: `testdata/openssl_rsa_pass.key`, envDisplay: `:0`, - envSshAskpass: askpassProgram, - envSshAskpassRequire: `force`, + envSSHAskpass: askpassProgram, + envSSHAskpassRequire: `force`, }} var c testCase for _, c = range cases { os.Setenv(envKeyDisplay, c.envDisplay) - os.Setenv(envKeySshAskpass, c.envSshAskpass) - os.Setenv(envKeySshAskpassRequire, c.envSshAskpassRequire) + os.Setenv(envKeySSHAskpass, c.envSSHAskpass) + os.Setenv(envKeySSHAskpassRequire, c.envSSHAskpassRequire) _, err = mockrw.BufRead.WriteString(c.secret) if err != nil { diff --git a/lib/dns/client.go b/lib/dns/client.go index 4abb4a9a..972fdd60 100644 --- a/lib/dns/client.go +++ b/lib/dns/client.go @@ -34,7 +34,7 @@ type Client interface { // - "tcp://127.0.0.1:53" for TCP client. // - "https://127.0.0.1:853" (HTTPS with IP address) for DoT. // - "https://localhost/dns-query" (HTTPS with domain name) for DoH. -func NewClient(nsUrl string, isInsecure bool) (cl Client, err error) { +func NewClient(nsURL string, isInsecure bool) (cl Client, err error) { var ( logp = "NewClient" @@ -45,9 +45,9 @@ func NewClient(nsUrl string, isInsecure bool) (cl Client, err error) { ipport []string ) - urlNS, err = url.Parse(nsUrl) + urlNS, err = url.Parse(nsURL) if err != nil { - return nil, fmt.Errorf("%s: invalid name server URL: %q", logp, nsUrl) + return nil, fmt.Errorf(`%s: invalid name server URL: %q`, logp, nsURL) } ipport = strings.Split(urlNS.Host, ":") @@ -58,7 +58,7 @@ func NewClient(nsUrl string, isInsecure bool) (cl Client, err error) { iphost = ipport[0] port = ipport[1] default: - return nil, fmt.Errorf("%s: invalid name server URL: %q", logp, nsUrl) + return nil, fmt.Errorf(`%s: invalid name server URL: %q`, logp, nsURL) } switch urlNS.Scheme { @@ -69,7 +69,7 @@ func NewClient(nsUrl string, isInsecure bool) (cl Client, err error) { case "https": ip = net.ParseIP(iphost) if ip == nil { - cl, err = NewDoHClient(nsUrl, isInsecure) + cl, err = NewDoHClient(nsURL, isInsecure) } else { if len(port) == 0 { port = "853" diff --git a/lib/dns/dns.go b/lib/dns/dns.go index 31bfec8d..014cb587 100644 --- a/lib/dns/dns.go +++ b/lib/dns/dns.go @@ -39,8 +39,8 @@ const ( maskOPTDO uint32 = 0x00008000 maxLabelSize = 63 - maxUdpPacketSize = 1232 - maxTcpPacketSize = 4096 + maxUDPPacketSize = 1232 + maxTCPPacketSize = 4096 rdataIPv4Size = 4 rdataIPv6Size = 16 // sectionHeaderSize define the size of section header in DNS message. diff --git a/lib/dns/dot_client.go b/lib/dns/dot_client.go index 316ab59b..865e6872 100644 --- a/lib/dns/dot_client.go +++ b/lib/dns/dot_client.go @@ -130,7 +130,7 @@ func (cl *DoTClient) recv(msg *Message) (n int, err error) { return } - var packet = make([]byte, maxTcpPacketSize) + var packet = make([]byte, maxTCPPacketSize) n, err = cl.conn.Read(packet) if err != nil { diff --git a/lib/dns/message_test.go b/lib/dns/message_test.go index 8becd30a..b9f9032a 100644 --- a/lib/dns/message_test.go +++ b/lib/dns/message_test.go @@ -996,7 +996,7 @@ func TestMessageSetAuthoritativeAnswer(t *testing.T) { IsRD: true, }, Question: MessageQuestion{}, - packet: make([]byte, maxUdpPacketSize), + packet: make([]byte, maxUDPPacketSize), dnameOff: make(map[string]uint16), } msgResponse = &Message{ @@ -1007,7 +1007,7 @@ func TestMessageSetAuthoritativeAnswer(t *testing.T) { IsRA: true, }, Question: MessageQuestion{}, - packet: make([]byte, maxUdpPacketSize), + packet: make([]byte, maxUDPPacketSize), dnameOff: make(map[string]uint16), } @@ -1072,7 +1072,7 @@ func TestMessageSetQuery(t *testing.T) { IsRD: true, }, Question: MessageQuestion{}, - packet: make([]byte, maxUdpPacketSize), + packet: make([]byte, maxUDPPacketSize), dnameOff: make(map[string]uint16), } @@ -1123,7 +1123,7 @@ func TestMessageSetRecursionDesired(t *testing.T) { IsRD: true, }, Question: MessageQuestion{}, - packet: make([]byte, maxUdpPacketSize), + packet: make([]byte, maxUDPPacketSize), dnameOff: make(map[string]uint16), } @@ -1174,7 +1174,7 @@ func TestMessageSetResponseCode(t *testing.T) { IsRD: true, }, Question: MessageQuestion{}, - packet: make([]byte, maxUdpPacketSize), + packet: make([]byte, maxUDPPacketSize), dnameOff: make(map[string]uint16), } diff --git a/lib/dns/rdata_soa.go b/lib/dns/rdata_soa.go index 86a8c02f..6c195f6a 100644 --- a/lib/dns/rdata_soa.go +++ b/lib/dns/rdata_soa.go @@ -10,10 +10,12 @@ import ( // Default SOA record value. const ( - DefaultSoaRName string = `root` - DefaultSoaRefresh int32 = 1 * 24 * 60 * 60 // 1 Day. - DefaultSoaRetry int32 = 1 * 60 * 60 // 1 Hour. - DefaultSoaMinimumTtl uint32 = 1 * 60 * 60 // 1 Hour. + DefaultSoaRName string = `root` + DefaultSoaRefresh int32 = 1 * 24 * 60 * 60 // 1 Day. + DefaultSoaRetry int32 = 1 * 60 * 60 // 1 Hour. + + //revive:disable-next-line + DefaultSoaMinimumTtl uint32 = 1 * 60 * 60 // 1 Hour. ) // RDataSOA contains the authority of zone. diff --git a/lib/dns/server.go b/lib/dns/server.go index bc865d56..c4c5ba1d 100644 --- a/lib/dns/server.go +++ b/lib/dns/server.go @@ -341,7 +341,7 @@ func (srv *Server) serveTCP() { func (srv *Server) serveUDP() { var ( n int - packet = make([]byte, maxUdpPacketSize) + packet = make([]byte, maxUDPPacketSize) raddr *net.UDPAddr req *request err error diff --git a/lib/dns/tcp_client.go b/lib/dns/tcp_client.go index ba3878ec..195cf397 100644 --- a/lib/dns/tcp_client.go +++ b/lib/dns/tcp_client.go @@ -187,7 +187,7 @@ func (cl *TCPClient) recv() (res *Message, err error) { } var ( - packet = make([]byte, maxTcpPacketSize) + packet = make([]byte, maxTCPPacketSize) n int ) diff --git a/lib/dns/udp_client.go b/lib/dns/udp_client.go index 52c9da7a..9f40363e 100644 --- a/lib/dns/udp_client.go +++ b/lib/dns/udp_client.go @@ -132,7 +132,7 @@ func (cl *UDPClient) Query(req *Message) (res *Message, err error) { return nil, fmt.Errorf("%s: %w", logp, err) } - packet = make([]byte, maxUdpPacketSize) + packet = make([]byte, maxUDPPacketSize) n, _, err = cl.conn.ReadFromUDP(packet) if err != nil { diff --git a/lib/email/contenttype.go b/lib/email/contenttype.go index cdfa43eb..d5002110 100644 --- a/lib/email/contenttype.go +++ b/lib/email/contenttype.go @@ -15,7 +15,7 @@ import ( var ( topText = `text` subPlain = `plain` - subHtml = `html` + subHTML = `html` ) // ContentType represent MIME header "Content-Type" field. diff --git a/lib/email/message.go b/lib/email/message.go index 7df94ee4..d2883795 100644 --- a/lib/email/message.go +++ b/lib/email/message.go @@ -305,7 +305,7 @@ func (msg *Message) DKIMVerify() (*dkim.Status, error) { } // SetBodyHtml set or replace the message's body HTML content. -func (msg *Message) SetBodyHtml(content []byte) (err error) { +func (msg *Message) SetBodyHtml(content []byte) (err error) { //revive:disable-line err = msg.setBody([]byte(contentTypeTextHTML), content) if err != nil { return fmt.Errorf("SetBodyHtml: %w", err) @@ -567,7 +567,7 @@ func (msg *Message) packMultipartAlternative() (out []byte, err error) { } } - mime = msg.Body.getPart(topText, subHtml) + mime = msg.Body.getPart(topText, subHTML) if mime != nil { fmt.Fprintf(&buf, "--%s\r\n", boundary) _, err = mime.WriteTo(&buf) @@ -581,7 +581,7 @@ func (msg *Message) packMultipartAlternative() (out []byte, err error) { if mime.isContentType(topText, subPlain) { continue } - if mime.isContentType(topText, subHtml) { + if mime.isContentType(topText, subHTML) { continue } diff --git a/lib/email/message_test.go b/lib/email/message_test.go index 55b4286e..eb58809f 100644 --- a/lib/email/message_test.go +++ b/lib/email/message_test.go @@ -309,7 +309,7 @@ func TestMessage_packSingle(t *testing.T) { type testCase struct { bodyText string - bodyHtml string + bodyHTML string outputTag string } @@ -322,7 +322,7 @@ func TestMessage_packSingle(t *testing.T) { bodyText: `this is a body text`, outputTag: `body.txt`, }, { - bodyHtml: `<p>this is an HTML body</p>`, + bodyHTML: `<p>this is an HTML body</p>`, outputTag: `body.html`, }} @@ -335,8 +335,8 @@ func TestMessage_packSingle(t *testing.T) { t.Fatal(err) } } - if len(c.bodyHtml) > 0 { - err = msg.SetBodyHtml([]byte(c.bodyHtml)) + if len(c.bodyHTML) > 0 { + err = msg.SetBodyHtml([]byte(c.bodyHTML)) if err != nil { t.Fatal(err) } diff --git a/lib/http/client.go b/lib/http/client.go index 2b231cb8..8243bc05 100644 --- a/lib/http/client.go +++ b/lib/http/client.go @@ -141,7 +141,7 @@ func (client *Client) Download(req DownloadRequest) (httpRes *http.Response, err return nil, fmt.Errorf("%s: %w", logp, ErrClientDownloadNoOutput) } - httpReq, err = req.toHttpRequest(client) + httpReq, err = req.toHTTPRequest(client) if err != nil { return nil, fmt.Errorf("%s: %s", logp, err) } @@ -192,7 +192,7 @@ out: // body. // - If requestType is RequestTypeJSON and params is not nil, the params will // be encoded as JSON in body. -func (client *Client) GenerateHttpRequest( +func (client *Client) GenerateHttpRequest( //revive:disable-line method RequestMethod, requestPath string, requestType RequestType, @@ -201,15 +201,15 @@ func (client *Client) GenerateHttpRequest( ) (httpRequest *http.Request, err error) { var ( logp = "GenerateHttpRequest" - paramsAsUrlValues url.Values - isParamsUrlValues bool + paramsAsURLValues url.Values + isParamsURLValues bool paramsAsJSON []byte contentType = requestType.String() strBody string body io.Reader ) - paramsAsUrlValues, isParamsUrlValues = params.(url.Values) + paramsAsURLValues, isParamsURLValues = params.(url.Values) switch method { case RequestMethodGet, @@ -219,8 +219,8 @@ func (client *Client) GenerateHttpRequest( RequestMethodOptions, RequestMethodTrace: - if isParamsUrlValues { - requestPath += `?` + paramsAsUrlValues.Encode() + if isParamsURLValues { + requestPath += `?` + paramsAsURLValues.Encode() } case RequestMethodPatch, @@ -228,13 +228,13 @@ func (client *Client) GenerateHttpRequest( RequestMethodPut: switch requestType { case RequestTypeQuery: - if isParamsUrlValues { - requestPath += `?` + paramsAsUrlValues.Encode() + if isParamsURLValues { + requestPath += `?` + paramsAsURLValues.Encode() } case RequestTypeForm: - if isParamsUrlValues { - strBody = paramsAsUrlValues.Encode() + if isParamsURLValues { + strBody = paramsAsURLValues.Encode() body = strings.NewReader(strBody) } @@ -363,9 +363,7 @@ func (client *Client) Put(requestPath string, headers http.Header, body []byte) func (client *Client) PutForm(requestPath string, headers http.Header, params url.Values) ( httpRes *http.Response, resBody []byte, err error, ) { - var ( - body *strings.Reader = strings.NewReader(params.Encode()) - ) + var body = strings.NewReader(params.Encode()) return client.doRequest(http.MethodPut, headers, requestPath, ContentTypeForm, body) } diff --git a/lib/http/client_options.go b/lib/http/client_options.go index 1f40c5bd..8e573d70 100644 --- a/lib/http/client_options.go +++ b/lib/http/client_options.go @@ -21,7 +21,7 @@ type ClientOptions struct { // "https://example.com" or "http://10.148.0.12:8080". // This value should not changed during call of client's method. // This field is required. - ServerUrl string + ServerUrl string //revive:disable-line // Timeout affect the http Transport Timeout and TLSHandshakeTimeout. // This field is optional, if not set it will set to 10 seconds. diff --git a/lib/http/client_request.go b/lib/http/client_request.go index d672758b..03496e45 100644 --- a/lib/http/client_request.go +++ b/lib/http/client_request.go @@ -62,24 +62,24 @@ type ClientRequest struct { Type RequestType } -// toHttpRequest convert the ClientRequest into the standard http.Request. -func (creq *ClientRequest) toHttpRequest(client *Client) (httpReq *http.Request, err error) { +// toHTTPRequest convert the ClientRequest into the standard http.Request. +func (creq *ClientRequest) toHTTPRequest(client *Client) (httpReq *http.Request, err error) { var ( - logp = "toHttpRequest" - paramsAsUrlValues url.Values + logp = `toHTTPRequest` + paramsAsURLValues url.Values paramsAsJSON []byte contentType = creq.Type.String() path strings.Builder body io.Reader strBody string - isParamsUrlValues bool + isParamsURLValues bool ) if client != nil { path.WriteString(client.opts.ServerUrl) } path.WriteString(creq.Path) - paramsAsUrlValues, isParamsUrlValues = creq.Params.(url.Values) + paramsAsURLValues, isParamsURLValues = creq.Params.(url.Values) switch creq.Method { case RequestMethodGet, @@ -89,9 +89,9 @@ func (creq *ClientRequest) toHttpRequest(client *Client) (httpReq *http.Request, RequestMethodOptions, RequestMethodTrace: - if isParamsUrlValues { + if isParamsURLValues { path.WriteString("?") - path.WriteString(paramsAsUrlValues.Encode()) + path.WriteString(paramsAsURLValues.Encode()) } case RequestMethodPatch, @@ -99,14 +99,14 @@ func (creq *ClientRequest) toHttpRequest(client *Client) (httpReq *http.Request, RequestMethodPut: switch creq.Type { case RequestTypeQuery: - if isParamsUrlValues { + if isParamsURLValues { path.WriteString("?") - path.WriteString(paramsAsUrlValues.Encode()) + path.WriteString(paramsAsURLValues.Encode()) } case RequestTypeForm: - if isParamsUrlValues { - strBody = paramsAsUrlValues.Encode() + if isParamsURLValues { + strBody = paramsAsURLValues.Encode() body = strings.NewReader(strBody) } diff --git a/lib/http/endpoint_request.go b/lib/http/endpoint_request.go index b6ce99ee..36dd30ab 100644 --- a/lib/http/endpoint_request.go +++ b/lib/http/endpoint_request.go @@ -14,9 +14,9 @@ import "net/http" // // The Error field is used by CallbackErrorHandler. type EndpointRequest struct { - HttpWriter http.ResponseWriter + HttpWriter http.ResponseWriter //revive:disable-line Error error Endpoint *Endpoint - HttpRequest *http.Request + HttpRequest *http.Request //revive:disable-line RequestBody []byte } diff --git a/lib/http/form.go b/lib/http/form.go index edfd13f2..edd751b2 100644 --- a/lib/http/form.go +++ b/lib/http/form.go @@ -25,10 +25,10 @@ const ( // It will return an error if the input is not pointer to or a struct. func MarshalForm(in any) (out url.Values, err error) { var ( - logp = `MarshalForm` - inValue reflect.Value = reflect.ValueOf(in) - inType reflect.Type = inValue.Type() - inKind reflect.Kind = inType.Kind() + logp = `MarshalForm` + inValue = reflect.ValueOf(in) + inType = inValue.Type() + inKind = inType.Kind() listField []reflect.StructField x int @@ -65,9 +65,7 @@ func MarshalForm(in any) (out url.Values, err error) { continue } - var ( - fval reflect.Value = inValue.FieldByIndex(field.Index) - ) + var fval = inValue.FieldByIndex(field.Index) if libstrings.IsContain(opts, `omitempty`) { if libreflect.IsNil(fval) { @@ -79,7 +77,7 @@ func MarshalForm(in any) (out url.Values, err error) { } var ( - fkind reflect.Kind = fval.Kind() + fkind = fval.Kind() val string valb []byte @@ -98,8 +96,8 @@ func MarshalForm(in any) (out url.Values, err error) { if fkind == reflect.Slice { var ( - sliceType reflect.Type = fval.Type() - elType = sliceType.Elem() + sliceType = fval.Type() + elType = sliceType.Elem() ) fkind = elType.Kind() @@ -153,10 +151,10 @@ func MarshalForm(in any) (out url.Values, err error) { // field type. func UnmarshalForm(in url.Values, out interface{}) (err error) { var ( - logp = "UnmarshalForm" - vout reflect.Value = reflect.ValueOf(out) - rtype reflect.Type = vout.Type() - rkind reflect.Kind = rtype.Kind() + logp = `UnmarshalForm` + vout = reflect.ValueOf(out) + rtype = vout.Type() + rkind = rtype.Kind() field reflect.StructField fval reflect.Value diff --git a/lib/http/http.go b/lib/http/http.go index 8136ffa9..eb1b8799 100644 --- a/lib/http/http.go +++ b/lib/http/http.go @@ -267,7 +267,7 @@ const ( HeaderRange = `Range` HeaderUserAgent = "User-Agent" HeaderXForwardedFor = "X-Forwarded-For" // https://en.wikipedia.org/wiki/X-Forwarded-For - HeaderXRealIp = "X-Real-Ip" + HeaderXRealIp = `X-Real-Ip` //revive:disable-line ) var ( diff --git a/lib/http/http_test.go b/lib/http/http_test.go index ea5ace48..caceedf2 100644 --- a/lib/http/http_test.go +++ b/lib/http/http_test.go @@ -24,7 +24,7 @@ import ( var ( testServer *Server - testServerUrl string + testServerURL string client = &http.Client{} @@ -68,7 +68,7 @@ func TestMain(m *testing.M) { Address: serverAddress, } - testServerUrl = fmt.Sprintf("http://" + serverAddress) + testServerURL = fmt.Sprintf("http://" + serverAddress) testServer, err = NewServer(opts) if err != nil { @@ -162,9 +162,9 @@ func registerEndpoints() { } } -// dumpHttpResponse write headers ordered by key in ascending with option to +// dumpHTTPResponse write headers ordered by key in ascending with option to // skip certain header keys. -func dumpHttpResponse(httpRes *http.Response, skipHeaders []string) string { +func dumpHTTPResponse(httpRes *http.Response, skipHeaders []string) string { var ( keys []string hkey string diff --git a/lib/http/route.go b/lib/http/route.go index 2a06e458..6898dcd3 100644 --- a/lib/http/route.go +++ b/lib/http/route.go @@ -11,7 +11,7 @@ import ( // List of kind for route. const ( - routeKindHttp int = iota // Normal routing. + routeKindHTTP int = iota // Normal routing. routeKindSSE // Routing for Server-Sent Events (SSE). ) diff --git a/lib/http/server.go b/lib/http/server.go index f0f6f409..55674038 100644 --- a/lib/http/server.go +++ b/lib/http/server.go @@ -337,8 +337,8 @@ func (srv *Server) Stop(wait time.Duration) (err error) { // index.html. func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) { var ( - nodeIndexHtml *memfs.Node - pathHtml string + nodeIndexHTML *memfs.Node + pathHTML string err error ) @@ -346,7 +346,7 @@ func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) { return nil, false } - pathHtml = path.Join(reqPath, `index.html`) + pathHTML = path.Join(reqPath, `index.html`) node, err = srv.Options.Memfs.Get(reqPath) if err != nil { @@ -354,10 +354,10 @@ func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) { return nil, false } - node, err = srv.Options.Memfs.Get(pathHtml) + node, err = srv.Options.Memfs.Get(pathHTML) if err != nil { - pathHtml = reqPath + `.html` - node, err = srv.Options.Memfs.Get(pathHtml) + pathHTML = reqPath + `.html` + node, err = srv.Options.Memfs.Get(pathHTML) if err != nil { return nil, false } @@ -366,9 +366,9 @@ func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) { } if node.IsDir() { - nodeIndexHtml, err = srv.Options.Memfs.Get(pathHtml) + nodeIndexHTML, err = srv.Options.Memfs.Get(pathHTML) if err == nil { - return nodeIndexHtml, true + return nodeIndexHTML, true } if !srv.Options.EnableIndexHtml { @@ -599,7 +599,7 @@ func (srv *Server) handleGet(res http.ResponseWriter, req *http.Request) { if !ok { continue } - if rute.kind == routeKindHttp { + if rute.kind == routeKindHTTP { rute.endpoint.call(res, req, srv.evals, vals) return } diff --git a/lib/http/server_test.go b/lib/http/server_test.go index 7c4f2087..664f57e9 100644 --- a/lib/http/server_test.go +++ b/lib/http/server_test.go @@ -46,11 +46,11 @@ func TestRegisterDelete(t *testing.T) { expError: ErrEndpointAmbiguous.Error(), }, { desc: "With unknown path", - reqURL: testServerUrl, + reqURL: testServerURL, expStatusCode: http.StatusNotFound, }, { desc: "With known path and subtree root", - reqURL: testServerUrl + "/delete/", + reqURL: testServerURL + `/delete/`, expStatusCode: http.StatusOK, expContentType: ContentTypePlain, expBody: "map[]\nmap[]\n<nil>\n", @@ -62,7 +62,7 @@ func TestRegisterDelete(t *testing.T) { ResponseType: ResponseTypeNone, Call: cbNone, }, - reqURL: testServerUrl + "/delete/none?k=v", + reqURL: testServerURL + `/delete/none?k=v`, expStatusCode: http.StatusNoContent, }, { desc: "With response type binary", @@ -72,13 +72,13 @@ func TestRegisterDelete(t *testing.T) { ResponseType: ResponseTypeBinary, Call: cbPlain, }, - reqURL: testServerUrl + "/delete/bin?k=v", + reqURL: testServerURL + `/delete/bin?k=v`, expStatusCode: http.StatusOK, expContentType: ContentTypeBinary, expBody: "map[k:[v]]\nmap[]\n<nil>\n", }, { desc: "With response type plain", - reqURL: testServerUrl + "/delete?k=v", + reqURL: testServerURL + `/delete?k=v`, expStatusCode: http.StatusOK, expContentType: ContentTypePlain, expBody: "map[k:[v]]\nmap[]\n<nil>\n", @@ -90,7 +90,7 @@ func TestRegisterDelete(t *testing.T) { ResponseType: ResponseTypeJSON, Call: cbJSON, }, - reqURL: testServerUrl + "/delete/json?k=v", + reqURL: testServerURL + `/delete/json?k=v`, expStatusCode: http.StatusOK, expContentType: ContentTypeJSON, expBody: `{ @@ -115,13 +115,13 @@ func TestRegisterDelete(t *testing.T) { ResponseType: ResponseTypePlain, Call: cbPlain, }, - reqURL: testServerUrl + "/delete/1/x?k=v", + reqURL: testServerURL + `/delete/1/x?k=v`, expStatusCode: http.StatusOK, expContentType: ContentTypePlain, expBody: "map[id:[1] k:[v]]\nmap[]\n<nil>\n", }, { desc: "With duplicate key in query", - reqURL: testServerUrl + "/delete/1/x?id=v", + reqURL: testServerURL + `/delete/1/x?id=v`, expStatusCode: http.StatusOK, expContentType: ContentTypePlain, expBody: "map[id:[1]]\nmap[]\n<nil>\n", @@ -211,11 +211,11 @@ func TestRegisterEvaluator(t *testing.T) { expStatusCode int }{{ desc: "With invalid evaluate", - reqURL: testServerUrl + "/evaluate", + reqURL: testServerURL + `/evaluate`, expStatusCode: http.StatusBadRequest, }, { desc: "With valid evaluate", - reqURL: testServerUrl + "/evaluate?k=v", + reqURL: testServerURL + `/evaluate?k=v`, expStatusCode: http.StatusOK, }} @@ -269,22 +269,22 @@ func TestRegisterGet(t *testing.T) { expStatusCode int }{{ desc: "With root path", - reqURL: testServerUrl, + reqURL: testServerURL, expStatusCode: http.StatusOK, expBody: "<html><body>Hello, world!</body></html>\n", }, { desc: "With known path", - reqURL: testServerUrl + "/index.js", + reqURL: testServerURL + `/index.js`, expStatusCode: http.StatusOK, expBody: "var a = \"Hello, world!\"\n", }, { desc: "With known path and subtree root", - reqURL: testServerUrl + "/get/", + reqURL: testServerURL + `/get/`, expStatusCode: http.StatusOK, expBody: "map[]\nmap[]\n<nil>\n", }, { desc: "With known path", - reqURL: testServerUrl + "/get?k=v", + reqURL: testServerURL + `/get?k=v`, expStatusCode: http.StatusOK, expBody: "map[k:[v]]\nmap[]\n<nil>\n", }} @@ -340,18 +340,18 @@ func TestRegisterHead(t *testing.T) { expStatusCode int }{{ desc: "With root path", - reqURL: testServerUrl + "/", + reqURL: testServerURL + `/`, expStatusCode: http.StatusOK, expContentType: []string{"text/html; charset=utf-8"}, expContentLength: []string{"40"}, }, { desc: "With registered GET and subtree root", - reqURL: testServerUrl + "/api/", + reqURL: testServerURL + `/api/`, expStatusCode: http.StatusOK, expContentType: []string{ContentTypeJSON}, }, { desc: "With registered GET", - reqURL: testServerUrl + "/api?k=v", + reqURL: testServerURL + `/api?k=v`, expStatusCode: http.StatusOK, expContentType: []string{ContentTypeJSON}, }} @@ -408,16 +408,16 @@ func TestRegisterPatch(t *testing.T) { expStatusCode int }{{ desc: "With root path", - reqURL: testServerUrl + "/", + reqURL: testServerURL + `/`, expStatusCode: http.StatusNotFound, }, { desc: "With registered PATCH and subtree root", - reqURL: testServerUrl + "/patch/", + reqURL: testServerURL + `/patch/`, expStatusCode: http.StatusOK, expBody: "map[]\nmap[]\n<nil>\n", }, { desc: "With registered PATCH and query", - reqURL: testServerUrl + "/patch?k=v", + reqURL: testServerURL + `/patch?k=v`, expStatusCode: http.StatusOK, expBody: "map[k:[v]]\nmap[]\n<nil>\n", }} @@ -473,16 +473,16 @@ func TestRegisterPost(t *testing.T) { expStatusCode int }{{ desc: "With root path", - reqURL: testServerUrl + "/", + reqURL: testServerURL + `/`, expStatusCode: http.StatusNotFound, }, { desc: "With registered POST and subtree root", - reqURL: testServerUrl + "/post/", + reqURL: testServerURL + `/post/`, expStatusCode: http.StatusOK, expBody: "map[]\nmap[]\n<nil>\n", }, { desc: "With registered POST and query", - reqURL: testServerUrl + "/post?k=v", + reqURL: testServerURL + `/post?k=v`, reqBody: "k=vv", expStatusCode: http.StatusOK, expBody: `map[k:[vv v]] @@ -545,15 +545,15 @@ func TestRegisterPut(t *testing.T) { expStatusCode int }{{ desc: "With root path", - reqURL: testServerUrl + "/", + reqURL: testServerURL + `/`, expStatusCode: http.StatusNotFound, }, { desc: "With registered PUT and subtree root", - reqURL: testServerUrl + "/put/", + reqURL: testServerURL + `/put/`, expStatusCode: http.StatusNoContent, }, { desc: "With registered PUT and query", - reqURL: testServerUrl + "/put?k=v", + reqURL: testServerURL + `/put?k=v`, expStatusCode: http.StatusNoContent, }} @@ -619,17 +619,17 @@ func TestServeHTTPOptions(t *testing.T) { expStatusCode int }{{ desc: "With root path", - reqURL: testServerUrl + "/", + reqURL: testServerURL + `/`, expStatusCode: http.StatusOK, expAllow: "GET, HEAD, OPTIONS", }, { desc: "With registered PATCH and subtree root", - reqURL: testServerUrl + "/options/", + reqURL: testServerURL + `/options/`, expStatusCode: http.StatusOK, expAllow: "DELETE, OPTIONS, PATCH", }, { desc: "With registered PATCH and query", - reqURL: testServerUrl + "/options?k=v", + reqURL: testServerURL + `/options?k=v`, expStatusCode: http.StatusOK, expAllow: "DELETE, OPTIONS, PATCH", }} @@ -757,32 +757,32 @@ func TestStatusError(t *testing.T) { expStatusCode int }{{ desc: "With registered error no body", - reqURL: testServerUrl + "/error/no-body?k=v", + reqURL: testServerURL + `/error/no-body?k=v`, expStatusCode: http.StatusLengthRequired, expBody: `{"message":"Length required","code":411}`, }, { desc: "With registered error binary", - reqURL: testServerUrl + "/error/binary?k=v", + reqURL: testServerURL + `/error/binary?k=v`, expStatusCode: http.StatusLengthRequired, expBody: `{"message":"Length required","code":411}`, }, { desc: "With registered error plain", - reqURL: testServerUrl + "/error/plain?k=v", + reqURL: testServerURL + `/error/plain?k=v`, expStatusCode: http.StatusLengthRequired, expBody: `{"message":"Length required","code":411}`, }, { desc: "With registered error plain", - reqURL: testServerUrl + "/error/json?k=v", + reqURL: testServerURL + `/error/json?k=v`, expStatusCode: http.StatusLengthRequired, expBody: `{"message":"Length required","code":411}`, }, { desc: "With registered error plain", - reqURL: testServerUrl + "/error/no-code?k=v", + reqURL: testServerURL + `/error/no-code?k=v`, expStatusCode: http.StatusInternalServerError, expBody: `{"message":"internal server error","name":"ERR_INTERNAL","code":500}`, }, { desc: "With registered error plain", - reqURL: testServerUrl + "/error/custom?k=v", + reqURL: testServerURL + `/error/custom?k=v`, expStatusCode: http.StatusInternalServerError, expBody: `{"message":"internal server error","name":"ERR_INTERNAL","code":500}`, }} @@ -876,7 +876,7 @@ func TestServer_Options_HandleFS(t *testing.T) { }} for _, c = range cases { - req, err = http.NewRequest(http.MethodGet, testServerUrl+c.reqPath, nil) + req, err = http.NewRequest(http.MethodGet, testServerURL+c.reqPath, nil) if err != nil { t.Fatalf("%s: %s", c.desc, err) } @@ -904,7 +904,7 @@ func TestServer_Options_HandleFS(t *testing.T) { func TestServer_handleRange(t *testing.T) { var ( clOpts = &ClientOptions{ - ServerUrl: testServerUrl, + ServerUrl: testServerURL, } cl = NewClient(clOpts) skipHeaders = []string{HeaderDate, HeaderETag} @@ -949,7 +949,7 @@ func TestServer_handleRange(t *testing.T) { var ( tag = `http_headers` exp = tdata.Output[tag] - got = dumpHttpResponse(httpRes, skipHeaders) + got = dumpHTTPResponse(httpRes, skipHeaders) ) if len(boundary) != 0 { @@ -980,7 +980,7 @@ func TestServer_handleRange(t *testing.T) { func TestServer_handleRange_HEAD(t *testing.T) { var ( clOpts = &ClientOptions{ - ServerUrl: testServerUrl, + ServerUrl: testServerURL, } cl = NewClient(clOpts) @@ -995,14 +995,14 @@ func TestServer_handleRange_HEAD(t *testing.T) { var httpRes *http.Response - httpRes, err = cl.Client.Head(testServerUrl + `/index.html`) + httpRes, err = cl.Client.Head(testServerURL + `/index.html`) if err != nil { t.Fatal(err) } var ( skipHeaders = []string{HeaderDate, HeaderETag} - got = dumpHttpResponse(httpRes, skipHeaders) + got = dumpHTTPResponse(httpRes, skipHeaders) tag = `http_headers` exp = tdata.Output[tag] ) diff --git a/lib/http/serveroptions.go b/lib/http/serveroptions.go index 89da8b3e..ce0d1219 100644 --- a/lib/http/serveroptions.go +++ b/lib/http/serveroptions.go @@ -53,7 +53,7 @@ type ServerOptions struct { // exist in the directory. // The index.html contains the list of files inside the requested // path. - EnableIndexHtml bool + EnableIndexHtml bool //revive:disable-line } func (opts *ServerOptions) init() { diff --git a/lib/http/sse_conn.go b/lib/http/sse_conn.go index a39b7817..d812ac4b 100644 --- a/lib/http/sse_conn.go +++ b/lib/http/sse_conn.go @@ -25,7 +25,7 @@ type SSECallback func(sse *SSEConn) // SSEConn define the connection when the SSE request accepted by server. type SSEConn struct { - HttpRequest *http.Request + HttpRequest *http.Request //revive:disable-line bufrw *bufio.ReadWriter conn net.Conn diff --git a/lib/http/sseclient/sseclient.go b/lib/http/sseclient/sseclient.go index 681b9ea8..4ee7dc4d 100644 --- a/lib/http/sseclient/sseclient.go +++ b/lib/http/sseclient/sseclient.go @@ -47,7 +47,7 @@ type Client struct { C <-chan Event event chan Event - serverUrl *url.URL + serverURL *url.URL header http.Header conn net.Conn @@ -152,34 +152,34 @@ func (cl *Client) connect() (err error) { // init validate and set default field values. func (cl *Client) init(header http.Header) (err error) { - cl.serverUrl, err = url.Parse(cl.Endpoint) + cl.serverURL, err = url.Parse(cl.Endpoint) if err != nil { return err } var host, port string - host, port, err = net.SplitHostPort(cl.serverUrl.Host) + host, port, err = net.SplitHostPort(cl.serverURL.Host) if err != nil { return err } if len(port) == 0 { - switch cl.serverUrl.Scheme { + switch cl.serverURL.Scheme { case `http`: port = `80` case `https`: port = `443` default: - return fmt.Errorf(`unknown scheme %q`, cl.serverUrl.Scheme) + return fmt.Errorf(`unknown scheme %q`, cl.serverURL.Scheme) } } - cl.serverUrl.Host = net.JoinHostPort(host, port) + cl.serverURL.Host = net.JoinHostPort(host, port) cl.header = header if cl.header == nil { cl.header = http.Header{} } - cl.header.Set(libhttp.HeaderHost, cl.serverUrl.Host) + cl.header.Set(libhttp.HeaderHost, cl.serverURL.Host) cl.header.Set(libhttp.HeaderUserAgent, `libhttp/`+share.Version) cl.header.Set(libhttp.HeaderAccept, libhttp.ContentTypeEventStream) @@ -195,13 +195,13 @@ func (cl *Client) init(header http.Header) (err error) { } func (cl *Client) dial() (err error) { - if cl.serverUrl.Scheme == `https` { + if cl.serverURL.Scheme == `https` { var tlsConfig = &tls.Config{ InsecureSkipVerify: cl.Insecure, } - cl.conn, err = tls.Dial(`tcp`, cl.serverUrl.Host, tlsConfig) + cl.conn, err = tls.Dial(`tcp`, cl.serverURL.Host, tlsConfig) } else { - cl.conn, err = net.Dial(`tcp`, cl.serverUrl.Host) + cl.conn, err = net.Dial(`tcp`, cl.serverURL.Host) } if err != nil { return err @@ -247,10 +247,10 @@ func (cl *Client) handshake() (packet []byte, err error) { func (cl *Client) handshakeRequest() (err error) { var buf bytes.Buffer - fmt.Fprintf(&buf, `GET %s`, cl.serverUrl.Path) - if len(cl.serverUrl.RawQuery) != 0 { + fmt.Fprintf(&buf, `GET %s`, cl.serverURL.Path) + if len(cl.serverURL.RawQuery) != 0 { buf.WriteByte('?') - buf.WriteString(cl.serverUrl.RawQuery) + buf.WriteString(cl.serverURL.RawQuery) } buf.WriteString(" HTTP/1.1\r\n") diff --git a/lib/hunspell/stem.go b/lib/hunspell/stem.go index 70e1f086..4ebb38db 100644 --- a/lib/hunspell/stem.go +++ b/lib/hunspell/stem.go @@ -260,9 +260,10 @@ func (stem *Stem) applySuffixes( func parseWordFlags(in string) (word, flags string, err error) { var ( - end int = -1 - esc bool + end = -1 v = make([]rune, 0, len(in)) + + esc bool ) for x, c := range in { if esc { diff --git a/lib/ini/ini.go b/lib/ini/ini.go index a663b72f..47ffb448 100644 --- a/lib/ini/ini.go +++ b/lib/ini/ini.go @@ -140,7 +140,7 @@ func (in *Ini) marshalStruct( rtipe reflect.Type, rvalue reflect.Value, parentSec, parentSub string, ) { - var numField int = rtipe.NumField() + var numField = rtipe.NumField() if numField == 0 { return } @@ -341,7 +341,8 @@ func (in *Ini) Unmarshal(v interface{}) (err error) { return fmt.Errorf("ini: Unmarshal: expecting pointer to struct, got %v", kind) } - var tagField *tagStructField = unpackTagStructField(rtipe, rvalue) + var tagField = unpackTagStructField(rtipe, rvalue) + in.unmarshal(tagField) return nil diff --git a/lib/ini/ini_unmarshal.go b/lib/ini/ini_unmarshal.go index 35ca532a..c6e3a175 100644 --- a/lib/ini/ini_unmarshal.go +++ b/lib/ini/ini_unmarshal.go @@ -161,7 +161,7 @@ func unmarshalToMap(sec *Section, rtype reflect.Type, rval reflect.Value) bool { func unmarshalToStruct(sec *Section, rtype reflect.Type, rval reflect.Value) { var ( - tagField *tagStructField = unpackTagStructField(rtype, rval) + tagField = unpackTagStructField(rtype, rval) v *variable sfield *structField diff --git a/lib/math/big/big.go b/lib/math/big/big.go index c2c63990..411a8f61 100644 --- a/lib/math/big/big.go +++ b/lib/math/big/big.go @@ -20,4 +20,4 @@ var DefaultDigitPrecision = 8 // MarshalJSONAsString define the default return behaviour of MarshalJSON(). // If its true (the default) the returned JSON format will encapsulated in // double quote, as string instead of as numeric. -var MarshalJSONAsString bool = true +var MarshalJSONAsString = true diff --git a/lib/math/big/int.go b/lib/math/big/int.go index 7fa028bd..bfb13bb7 100644 --- a/lib/math/big/int.go +++ b/lib/math/big/int.go @@ -105,7 +105,7 @@ func (i *Int) UnmarshalJSON(in []byte) (err error) { // Value implement the sql/driver.Valuer. func (i *Int) Value() (driver.Value, error) { - var s string = "0" + var s = `0` if i != nil { s = i.String() } diff --git a/lib/memfs/memfs.go b/lib/memfs/memfs.go index fef17b52..d8644ae4 100644 --- a/lib/memfs/memfs.go +++ b/lib/memfs/memfs.go @@ -367,7 +367,7 @@ func (mfs *MemFS) ListNames() (paths []string) { // The field that being encoded is the Root node. func (mfs *MemFS) MarshalJSON() ([]byte, error) { var buf bytes.Buffer - mfs.Root.packAsJson(&buf, 0, true, true) + mfs.Root.packAsJSON(&buf, 0, true, true) return buf.Bytes(), nil } diff --git a/lib/memfs/memfs_test.go b/lib/memfs/memfs_test.go index 61b50bb7..411d1a06 100644 --- a/lib/memfs/memfs_test.go +++ b/lib/memfs/memfs_test.go @@ -394,11 +394,11 @@ func TestMemFS_Get_refresh(t *testing.T) { filePath string tag string path string - expJson string + expJSON string expError string fileContent []byte - rawJson []byte - gotJson bytes.Buffer + rawJSON []byte + gotJSON bytes.Buffer ) for filePath, fileContent = range tdata.Input { @@ -431,21 +431,21 @@ func TestMemFS_Get_refresh(t *testing.T) { // Check the tree of MemFS. - rawJson, err = mfs.Root.JSON(9999, true, false) + rawJSON, err = mfs.Root.JSON(9999, true, false) if err != nil { t.Fatal(err) } - gotJson.Reset() - err = json.Indent(&gotJson, rawJson, ``, ` `) + gotJSON.Reset() + err = json.Indent(&gotJSON, rawJSON, ``, ` `) if err != nil { t.Fatal(err) } test.Assert(t, filePath, string(fileContent), string(node.Content)) - expJson = string(tdata.Output[filePath]) - test.Assert(t, filePath, expJson, gotJson.String()) + expJSON = string(tdata.Output[filePath]) + test.Assert(t, filePath, expJSON, gotJSON.String()) } } diff --git a/lib/memfs/node.go b/lib/memfs/node.go index b2f13f8f..45e1f33f 100644 --- a/lib/memfs/node.go +++ b/lib/memfs/node.go @@ -24,7 +24,7 @@ import ( ) const ( - templateIndexHtmlHeader = `<!DOCTYPE html><html> + templateIndexHTMLHeader = `<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width"> <style> @@ -154,6 +154,8 @@ func (node *Node) Close() error { // GenerateIndexHtml generate simple directory listing as HTML for all childs // in this node. // This method is only applicable if node is a directory. +// +//revive:disable-next-line func (node *Node) GenerateIndexHtml() { if !node.IsDir() { return @@ -170,7 +172,7 @@ func (node *Node) GenerateIndexHtml() { child *Node ) - buf.WriteString(templateIndexHtmlHeader) + buf.WriteString(templateIndexHTMLHeader) fmt.Fprintf(&buf, `<h3>Index of %s</h3>`, node.name) @@ -210,7 +212,7 @@ func (node *Node) IsDir() bool { // included in the output. func (node *Node) JSON(depth int, withContent, withModTime bool) (rawjson []byte, err error) { var buf bytes.Buffer - node.packAsJson(&buf, depth, withContent, withModTime) + node.packAsJSON(&buf, depth, withContent, withModTime) return buf.Bytes(), nil } @@ -220,7 +222,7 @@ func (node *Node) JSON(depth int, withContent, withModTime bool) (rawjson []byte // childs of childs. func (node *Node) MarshalJSON() ([]byte, error) { var buf bytes.Buffer - node.packAsJson(&buf, 0, true, true) + node.packAsJSON(&buf, 0, true, true) return buf.Bytes(), nil } @@ -414,7 +416,7 @@ func (node *Node) generateFuncName(in string) { node.GenFuncName = "generate_" + syspath } -func (node *Node) packAsJson(buf *bytes.Buffer, depth int, withContent, withModTime bool) { +func (node *Node) packAsJSON(buf *bytes.Buffer, depth int, withContent, withModTime bool) { isDir := node.IsDir() _ = buf.WriteByte('{') @@ -442,7 +444,7 @@ func (node *Node) packAsJson(buf *bytes.Buffer, depth int, withContent, withModT if x > 0 { _ = buf.WriteByte(',') } - child.packAsJson(buf, depth-1, withContent, withModTime) + child.packAsJSON(buf, depth-1, withContent, withModTime) } _ = buf.WriteByte(']') } else { diff --git a/lib/memfs/pathnode.go b/lib/memfs/pathnode.go index b891fedc..d6b436a7 100644 --- a/lib/memfs/pathnode.go +++ b/lib/memfs/pathnode.go @@ -60,7 +60,7 @@ func (pn *PathNode) MarshalJSON() ([]byte, error) { fmt.Fprintf(&buf, "%q:", path) node = pn.v[path] if node != nil { - node.packAsJson(&buf, 0, true, true) + node.packAsJSON(&buf, 0, true, true) } } _ = buf.WriteByte('}') diff --git a/lib/mlog/mlog.go b/lib/mlog/mlog.go index a54ca602..155a2500 100644 --- a/lib/mlog/mlog.go +++ b/lib/mlog/mlog.go @@ -37,7 +37,7 @@ const ( defTimeFormat = "2006-01-02 15:04:05 MST" ) -var defaultMLog *MultiLogger = createMultiLogger(defTimeFormat, "", +var defaultMLog = createMultiLogger(defTimeFormat, ``, []NamedWriter{ NewNamedWriter("stdout", os.Stdout), }, diff --git a/lib/mlog/multi_logger.go b/lib/mlog/multi_logger.go index bf420a05..33fe3223 100644 --- a/lib/mlog/multi_logger.go +++ b/lib/mlog/multi_logger.go @@ -162,7 +162,7 @@ func (mlog *MultiLogger) Outf(format string, v ...interface{}) { func (mlog *MultiLogger) Panicf(format string, v ...interface{}) { mlog.Errf(format, v...) mlog.Flush() - var msg string = fmt.Sprintf(format, v...) + var msg = fmt.Sprintf(format, v...) panic(msg) } @@ -186,7 +186,7 @@ func (mlog *MultiLogger) PrintStack() { // RegisterErrorWriter register the named writer to one of error writers. // The writer Name() must not be empty or it will not registered. func (mlog *MultiLogger) RegisterErrorWriter(errw NamedWriter) { - var name string = errw.Name() + var name = errw.Name() if len(name) == 0 { return } @@ -196,7 +196,7 @@ func (mlog *MultiLogger) RegisterErrorWriter(errw NamedWriter) { // RegisterOutputWriter register the named writer to one of output writers. // The writer Name() must not be empty or it will not registered. func (mlog *MultiLogger) RegisterOutputWriter(outw NamedWriter) { - var name string = outw.Name() + var name = outw.Name() if len(name) == 0 { return } diff --git a/lib/net/net.go b/lib/net/net.go index 824482e9..66b7db5a 100644 --- a/lib/net/net.go +++ b/lib/net/net.go @@ -130,7 +130,7 @@ func Read(conn net.Conn, bufsize int, timeout time.Duration) (packet []byte, err } var ( - buf []byte = make([]byte, bufsize) + buf = make([]byte, bufsize) n int ) diff --git a/lib/reflect/reflect.go b/lib/reflect/reflect.go index df4a0e6e..ae0238d7 100644 --- a/lib/reflect/reflect.go +++ b/lib/reflect/reflect.go @@ -28,8 +28,8 @@ func DoEqual(x, y interface{}) (err error) { } var ( - v1 reflect.Value = reflect.ValueOf(x) - v2 reflect.Value = reflect.ValueOf(y) + v1 = reflect.ValueOf(x) + v2 = reflect.ValueOf(y) ) err = doEqual(v1, v2) if err != nil { @@ -49,9 +49,9 @@ func IsEqual(x, y interface{}) bool { } var ( - v1 reflect.Value = reflect.ValueOf(x) - v2 reflect.Value = reflect.ValueOf(y) - err = doEqual(v1, v2) + v1 = reflect.ValueOf(x) + v2 = reflect.ValueOf(y) + err = doEqual(v1, v2) ) return err == nil } @@ -59,9 +59,7 @@ func IsEqual(x, y interface{}) bool { // IsNil will return true if v's type is chan, func, interface, map, pointer, // or slice and its value is `nil`; otherwise it will return false. func IsNil(v interface{}) bool { - var ( - val reflect.Value = reflect.ValueOf(v) - ) + var val = reflect.ValueOf(v) switch val.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, @@ -156,9 +154,9 @@ func Marshal(obj interface{}) (out []byte, err error) { // - obj Kind is Invalid, Array, Chan, Func, Map, or UnsafePointer. func Set(obj reflect.Value, val string) (err error) { var ( - logp = "Set" - objType reflect.Type = obj.Type() - objKind reflect.Kind = obj.Kind() + logp = `Set` + objType = obj.Type() + objKind = obj.Kind() objValue reflect.Value ) @@ -225,8 +223,8 @@ func Set(obj reflect.Value, val string) (err error) { // setSlice append the string value of val to the slice. func setSlice(slice reflect.Value, val string) (sliceOut reflect.Value, err error) { var ( - sliceKind reflect.Kind = slice.Kind() - sliceType reflect.Type = slice.Type() + sliceKind = slice.Kind() + sliceType = slice.Type() elValue reflect.Value ptrValue reflect.Value @@ -511,16 +509,14 @@ func Tag(field reflect.StructField, tag string) (val string, opts []string, hasT return "", nil, false } - var ( - x int - ) - val, hasTag = field.Tag.Lookup(tag) if !hasTag { // Tag not defined, so we use field name as key. return field.Name, nil, false } + var x int + opts = strings.Split(val, ",") for x, val = range opts { opts[x] = strings.TrimSpace(val) @@ -559,12 +555,12 @@ func doEqual(v1, v2 reflect.Value) (err error) { } var ( - k1 reflect.Kind = v1.Kind() - k2 reflect.Kind = v2.Kind() - t1 reflect.Type = v1.Type() - t2 reflect.Type = v2.Type() - name1 = t1.Name() - name2 = t2.Name() + k1 = v1.Kind() + k2 = v2.Kind() + t1 = v1.Type() + t2 = v2.Type() + name1 = t1.Name() + name2 = t2.Name() x int ) @@ -733,7 +729,7 @@ func doEqualMap(v1, v2 reflect.Value) (err error) { } var ( - keys []reflect.Value = v1.MapKeys() + keys = v1.MapKeys() tipe reflect.Type name string @@ -756,7 +752,7 @@ func doEqualMap(v1, v2 reflect.Value) (err error) { // The type of both struct is already equal when this function called. func doEqualStruct(v1, v2 reflect.Value) (err error) { var ( - m1 reflect.Value = v1.MethodByName("IsEqual") + m1 = v1.MethodByName(`IsEqual`) callIn []reflect.Value callOut []reflect.Value @@ -774,9 +770,9 @@ func doEqualStruct(v1, v2 reflect.Value) (err error) { } var ( - t1 reflect.Type = v1.Type() - v1Name string = t1.Name() - n int = v1.NumField() + t1 = v1.Type() + v1Name = t1.Name() + n = v1.NumField() f1, f2 reflect.Value f1Name string diff --git a/lib/reflect/reflect_test.go b/lib/reflect/reflect_test.go index 98e65c61..7f839ed6 100644 --- a/lib/reflect/reflect_test.go +++ b/lib/reflect/reflect_test.go @@ -11,10 +11,10 @@ import ( func TestAppendSlice(t *testing.T) { var ( - v123 int = 123 - v456 int = 456 - pv123 *int = &v123 - pv456 *int = &v456 + v123 = 123 + v456 = 456 + pv123 = &v123 + pv456 = &v456 sliceT []int slicePtrT []*int diff --git a/lib/smtp/client.go b/lib/smtp/client.go index d6b88d68..22d04dc1 100644 --- a/lib/smtp/client.go +++ b/lib/smtp/client.go @@ -357,7 +357,7 @@ func (cl *Client) SendCommand(cmd []byte) (res *Response, err error) { // SendEmail is the wrapper that simplify sending email. // This method automatically create [MailTx] for passing it to method // [Client.MailTx]. -func (cl *Client) SendEmail(from string, to []string, subject, bodyText, bodyHtml []byte) (err error) { +func (cl *Client) SendEmail(from string, to []string, subject, bodyText, bodyHTML []byte) (err error) { var ( logp = `SendEmail` toAddresses = strings.Join(to, `, `) @@ -370,7 +370,7 @@ func (cl *Client) SendEmail(from string, to []string, subject, bodyText, bodyHtm []byte(toAddresses), []byte(subject), bodyText, - bodyHtml, + bodyHTML, ) if err != nil { return fmt.Errorf(`%s: %w`, logp, err) diff --git a/lib/smtp/client_options.go b/lib/smtp/client_options.go index 1592226a..4ae28e40 100644 --- a/lib/smtp/client_options.go +++ b/lib/smtp/client_options.go @@ -25,7 +25,7 @@ type ClientOptions struct { // remote address at port 465 (implicit TLS). // If scheme is "smtp+starttls" and no port is given, client will // connect to remote address at port 587. - ServerUrl string + ServerUrl string //revive:disable-line // The user name to authenticate to remote server. // diff --git a/lib/smtp/client_test.go b/lib/smtp/client_test.go index c54869a3..f32e8842 100644 --- a/lib/smtp/client_test.go +++ b/lib/smtp/client_test.go @@ -47,10 +47,10 @@ func TestClient_live(t *testing.T) { to = []string{`Shulhan <m.shulhan@gmail.com>`} subject = tdata.Input[`subject`] bodyText = tdata.Input[`bodyText`] - bodyHtml = tdata.Input[`bodyHtml`] + bodyHTML = tdata.Input[`bodyHtml`] ) - err = cl.SendEmail(from, to, subject, bodyText, bodyHtml) + err = cl.SendEmail(from, to, subject, bodyText, bodyHTML) if err != nil { t.Fatal(err) } @@ -150,9 +150,7 @@ func TestAuth(t *testing.T) { }, }} - var ( - cl *Client = testNewClient(false) - ) + var cl = testNewClient(false) for _, c := range cases { t.Log(c.desc) @@ -224,9 +222,7 @@ func TestExpand(t *testing.T) { }, }} - var ( - cl *Client = testNewClient(true) - ) + var cl = testNewClient(true) for _, c := range cases { t.Log(c.desc) @@ -253,9 +249,7 @@ func TestHelp(t *testing.T) { }, }} - var ( - cl *Client = testNewClient(true) - ) + var cl = testNewClient(true) for _, c := range cases { t.Log(c.desc) @@ -297,9 +291,7 @@ func TestSendCommand(t *testing.T) { }, }} - var ( - cl *Client = testNewClient(false) - ) + var cl = testNewClient(false) for _, c := range cases { t.Log(c.desc) @@ -346,9 +338,7 @@ func TestMailTx(t *testing.T) { }, }} - var ( - cl *Client = testNewClient(true) - ) + var cl = testNewClient(true) for _, c := range cases { t.Log(c.desc) @@ -385,9 +375,7 @@ func TestVerify(t *testing.T) { }, }} - var ( - cl *Client = testNewClient(true) - ) + var cl = testNewClient(true) for _, c := range cases { t.Log(c.desc) @@ -403,8 +391,8 @@ func TestVerify(t *testing.T) { func TestQuit(t *testing.T) { var ( - cl *Client = testNewClient(false) - exp = &Response{ + cl = testNewClient(false) + exp = &Response{ Code: StatusClosing, Message: "Service closing transmission channel", } diff --git a/lib/ssh/config/config.go b/lib/ssh/config/config.go index f8c92ea8..856bd6c8 100644 --- a/lib/ssh/config/config.go +++ b/lib/ssh/config/config.go @@ -13,7 +13,7 @@ import ( ) const ( - envSshAuthSock = "SSH_AUTH_SOCK" + envSSHAuthSock = `SSH_AUTH_SOCK` ) const ( diff --git a/lib/ssh/config/parser.go b/lib/ssh/config/parser.go index 5f9e57bc..8e0d6b03 100644 --- a/lib/ssh/config/parser.go +++ b/lib/ssh/config/parser.go @@ -135,10 +135,11 @@ func isIncludeDirective(line string) bool { func parseInclude(line string) (patterns []string) { var ( - useQuote bool - x int = len(keyInclude) + x = len(keyInclude) + start int end int + useQuote bool ) for ; x < len(line); x++ { diff --git a/lib/ssh/config/section.go b/lib/ssh/config/section.go index 70ed8969..baeeb344 100644 --- a/lib/ssh/config/section.go +++ b/lib/ssh/config/section.go @@ -358,8 +358,8 @@ func (section *Section) IdentityAgent() string { if value == `none` { return `` } - if len(value) == 0 || value == envSshAuthSock { - return os.Getenv(envSshAuthSock) + if len(value) == 0 || value == envSSHAuthSock { + return os.Getenv(envSSHAuthSock) } if value[0] == '$' { // Read the socket from environment variable defined by diff --git a/lib/ssh/sftp/client.go b/lib/ssh/sftp/client.go index ea8c4ae8..aec6751d 100644 --- a/lib/ssh/sftp/client.go +++ b/lib/ssh/sftp/client.go @@ -25,13 +25,13 @@ type Client struct { pipeOut io.Reader pipeErr io.Reader - // The requestId is unique number that will be incremented by client, + // The requestID is unique number that will be incremented by client, // to prevent the same ID generated on concurrent operations. - requestId uint32 + requestID uint32 version uint32 - mtxId sync.Mutex + mtxID sync.Mutex } // NewClient create and initialize new client for SSH file transfer protocol. @@ -69,7 +69,7 @@ func NewClient(sshc *ssh.Client) (cl *Client, err error) { return nil, fmt.Errorf("%s: RequestSubsystem: %w", logp, err) } - cl.requestId = uint32(time.Now().Unix()) + cl.requestID = uint32(time.Now().Unix()) err = cl.init() if err != nil { @@ -83,7 +83,7 @@ func NewClient(sshc *ssh.Client) (cl *Client, err error) { func (cl *Client) Close() (err error) { err = cl.sess.Close() - cl.requestId = 0 + cl.requestID = 0 cl.pipeErr = nil cl.pipeOut = nil cl.pipeIn = nil @@ -647,12 +647,12 @@ func (cl *Client) Write(fh *FileHandle, offset uint64, data []byte) (err error) } func (cl *Client) generatePacket() (pac *packet) { - cl.mtxId.Lock() - cl.requestId++ + cl.mtxID.Lock() + cl.requestID++ pac = &packet{ - requestId: cl.requestId, + requestID: cl.requestID, } - cl.mtxId.Unlock() + cl.mtxID.Unlock() return pac } diff --git a/lib/ssh/sftp/file_attrs.go b/lib/ssh/sftp/file_attrs.go index a5e8c870..12b69590 100644 --- a/lib/ssh/sftp/file_attrs.go +++ b/lib/ssh/sftp/file_attrs.go @@ -27,29 +27,29 @@ const ( // List of valid values for FileAttrs.flags. const ( - attr_SIZE uint32 = 0x00000001 - attr_UIDGID uint32 = 0x00000002 - attr_PERMISSIONS uint32 = 0x00000004 - attr_ACMODTIME uint32 = 0x00000008 - attr_EXTENDED uint32 = 0x80000000 + attrSize uint32 = 0x00000001 + attrUIDGID uint32 = 0x00000002 + attrPermissions uint32 = 0x00000004 + attrAcModtime uint32 = 0x00000008 + attrExtended uint32 = 0x80000000 ) // FileAttrs define the attributes for opening or creating file on the remote. type FileAttrs struct { - exts extensions // attr_EXTENDED + exts extensions // attrExtended name string fsMode fs.FileMode - size uint64 // attr_SIZE + size uint64 // attrSize flags uint32 - uid uint32 // attr_UIDGID - gid uint32 // attr_UIDGID - permissions uint32 // attr_PERMISSIONS - atime uint32 // attr_ACMODTIME - mtime uint32 // attr_ACMODTIME + uid uint32 // attrUIDGID + gid uint32 // attrUIDGID + permissions uint32 // attrPermissions + atime uint32 // attrAcModtime + mtime uint32 // attrAcModtime } // NewFileAttrs create and initialize FileAttrs from FileInfo. @@ -79,12 +79,12 @@ func unpackFileAttrs(payload []byte) (fa *FileAttrs, length int) { payload = payload[4:] length += 4 - if fa.flags&attr_SIZE != 0 { + if fa.flags&attrSize != 0 { fa.size = binary.BigEndian.Uint64(payload) payload = payload[8:] length += 8 } - if fa.flags&attr_UIDGID != 0 { + if fa.flags&attrUIDGID != 0 { fa.uid = binary.BigEndian.Uint32(payload) payload = payload[4:] length += 4 @@ -92,13 +92,13 @@ func unpackFileAttrs(payload []byte) (fa *FileAttrs, length int) { payload = payload[4:] length += 4 } - if fa.flags&attr_PERMISSIONS != 0 { + if fa.flags&attrPermissions != 0 { fa.permissions = binary.BigEndian.Uint32(payload) payload = payload[4:] length += 4 fa.updateFsmode() } - if fa.flags&attr_ACMODTIME != 0 { + if fa.flags&attrAcModtime != 0 { fa.atime = binary.BigEndian.Uint32(payload) payload = payload[4:] length += 4 @@ -106,7 +106,7 @@ func unpackFileAttrs(payload []byte) (fa *FileAttrs, length int) { payload = payload[4:] length += 4 } - if fa.flags&attr_EXTENDED != 0 { + if fa.flags&attrExtended != 0 { n := binary.BigEndian.Uint32(payload) payload = payload[4:] length += 4 @@ -138,21 +138,21 @@ func unpackFileAttrs(payload []byte) (fa *FileAttrs, length int) { func (fa *FileAttrs) pack(w io.Writer) { _ = binary.Write(w, binary.BigEndian, fa.flags) - if fa.flags&attr_SIZE != 0 { + if fa.flags&attrSize != 0 { _ = binary.Write(w, binary.BigEndian, fa.size) } - if fa.flags&attr_UIDGID != 0 { + if fa.flags&attrUIDGID != 0 { _ = binary.Write(w, binary.BigEndian, fa.uid) _ = binary.Write(w, binary.BigEndian, fa.gid) } - if fa.flags&attr_PERMISSIONS != 0 { + if fa.flags&attrPermissions != 0 { _ = binary.Write(w, binary.BigEndian, fa.permissions) } - if fa.flags&attr_ACMODTIME != 0 { + if fa.flags&attrAcModtime != 0 { _ = binary.Write(w, binary.BigEndian, fa.atime) _ = binary.Write(w, binary.BigEndian, fa.mtime) } - if fa.flags&attr_EXTENDED != 0 { + if fa.flags&attrExtended != 0 { n := uint32(len(fa.exts)) _ = binary.Write(w, binary.BigEndian, n) for k, v := range fa.exts { @@ -207,7 +207,7 @@ func (fa *FileAttrs) Permissions() uint32 { // SetAccessTime set the file attribute access time. func (fa *FileAttrs) SetAccessTime(v uint32) { - fa.flags |= attr_ACMODTIME + fa.flags |= attrAcModtime fa.atime = v } @@ -216,38 +216,38 @@ func (fa *FileAttrs) SetExtension(name, data string) { if fa.exts == nil { fa.exts = extensions{} } - fa.flags |= attr_EXTENDED + fa.flags |= attrExtended fa.exts[name] = data } // SetGid set the file attribute group ID. func (fa *FileAttrs) SetGid(gid uint32) { - fa.flags |= attr_UIDGID + fa.flags |= attrUIDGID fa.gid = gid } // SetModifiedTime set the file attribute modified time. func (fa *FileAttrs) SetModifiedTime(v uint32) { - fa.flags |= attr_ACMODTIME + fa.flags |= attrAcModtime fa.mtime = v } // SetPermissions set the remote file permission. func (fa *FileAttrs) SetPermissions(v uint32) { - fa.flags |= attr_PERMISSIONS + fa.flags |= attrPermissions fa.permissions = v fa.updateFsmode() } // SetSize set the remote file size. func (fa *FileAttrs) SetSize(v uint64) { - fa.flags |= attr_SIZE + fa.flags |= attrSize fa.size = v } // SetUid set the file attribute user ID. -func (fa *FileAttrs) SetUid(uid uint32) { - fa.flags |= attr_UIDGID +func (fa *FileAttrs) SetUid(uid uint32) { //revive:disable-line + fa.flags |= attrUIDGID fa.uid = uid } @@ -262,7 +262,7 @@ func (fa *FileAttrs) Sys() interface{} { } // Uid return the user ID of file. -func (fa *FileAttrs) Uid() uint32 { +func (fa *FileAttrs) Uid() uint32 { //revive:disable-line return fa.uid } diff --git a/lib/ssh/sftp/packet.go b/lib/ssh/sftp/packet.go index 4f7b24f3..2460e1dd 100644 --- a/lib/ssh/sftp/packet.go +++ b/lib/ssh/sftp/packet.go @@ -67,7 +67,7 @@ type packet struct { version uint32 // from FxpVersion. code uint32 // from FxpStatus length uint32 - requestId uint32 + requestID uint32 kind byte } @@ -96,7 +96,7 @@ func unpackPacket(payload []byte) (pac *packet, err error) { return pac, nil } - pac.requestId = v + pac.requestID = v switch pac.kind { case packetKindFxpStatus: @@ -161,7 +161,7 @@ func (pac *packet) fxpClose(fh *FileHandle) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpClose) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(fh.v))) _ = binary.Write(&buf, binary.BigEndian, fh.v) @@ -172,7 +172,7 @@ func (pac *packet) fxpFsetstat(fh *FileHandle, fa *FileAttrs) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpFsetstat) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(fh.v))) _ = binary.Write(&buf, binary.BigEndian, fh.v) fa.pack(&buf) @@ -184,7 +184,7 @@ func (pac *packet) fxpFstat(fh *FileHandle) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpFstat) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(fh.v))) _ = binary.Write(&buf, binary.BigEndian, fh.v) @@ -207,7 +207,7 @@ func (pac *packet) fxpLstat(remoteFile string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpLstat) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(remoteFile))) _ = binary.Write(&buf, binary.BigEndian, []byte(remoteFile)) @@ -218,7 +218,7 @@ func (pac *packet) fxpMkdir(path string, fa *FileAttrs) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpMkdir) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(path))) _ = binary.Write(&buf, binary.BigEndian, []byte(path)) fa.pack(&buf) @@ -230,7 +230,7 @@ func (pac *packet) fxpOpen(filename string, pflags uint32, fa *FileAttrs) []byte var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpOpen) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(filename))) _ = binary.Write(&buf, binary.BigEndian, []byte(filename)) _ = binary.Write(&buf, binary.BigEndian, pflags) @@ -243,7 +243,7 @@ func (pac *packet) fxpOpendir(path string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpOpendir) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(path))) _ = binary.Write(&buf, binary.BigEndian, []byte(path)) @@ -254,7 +254,7 @@ func (pac *packet) fxpRead(fh *FileHandle, offset uint64, length uint32) []byte var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpRead) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(fh.v))) _ = binary.Write(&buf, binary.BigEndian, []byte(fh.v)) _ = binary.Write(&buf, binary.BigEndian, offset) @@ -267,7 +267,7 @@ func (pac *packet) fxpReaddir(fh *FileHandle) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpReaddir) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(fh.v))) _ = binary.Write(&buf, binary.BigEndian, []byte(fh.v)) @@ -278,7 +278,7 @@ func (pac *packet) fxpReadlink(linkPath string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpReadlink) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(linkPath))) _ = binary.Write(&buf, binary.BigEndian, []byte(linkPath)) @@ -289,7 +289,7 @@ func (pac *packet) fxpRealpath(path string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpRealpath) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(path))) _ = binary.Write(&buf, binary.BigEndian, []byte(path)) @@ -300,7 +300,7 @@ func (pac *packet) fxpRemove(remoteFile string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpRemove) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(remoteFile))) _ = binary.Write(&buf, binary.BigEndian, []byte(remoteFile)) @@ -311,7 +311,7 @@ func (pac *packet) fxpRename(oldPath, newPath string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpRename) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(oldPath))) _ = binary.Write(&buf, binary.BigEndian, []byte(oldPath)) _ = binary.Write(&buf, binary.BigEndian, uint32(len(newPath))) @@ -324,7 +324,7 @@ func (pac *packet) fxpRmdir(path string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpRmdir) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(path))) _ = binary.Write(&buf, binary.BigEndian, []byte(path)) @@ -335,7 +335,7 @@ func (pac *packet) fxpSetstat(remoteFile string, fa *FileAttrs) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpSetstat) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(remoteFile))) _ = binary.Write(&buf, binary.BigEndian, []byte(remoteFile)) fa.pack(&buf) @@ -347,7 +347,7 @@ func (pac *packet) fxpStat(remoteFile string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpStat) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(remoteFile))) _ = binary.Write(&buf, binary.BigEndian, []byte(remoteFile)) @@ -358,7 +358,7 @@ func (pac *packet) fxpSymlink(linkPath, targetPath string) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpSymlink) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(linkPath))) _ = binary.Write(&buf, binary.BigEndian, []byte(linkPath)) _ = binary.Write(&buf, binary.BigEndian, uint32(len(targetPath))) @@ -371,7 +371,7 @@ func (pac *packet) fxpWrite(fh *FileHandle, offset uint64, data []byte) []byte { var buf bytes.Buffer _ = binary.Write(&buf, binary.BigEndian, packetKindFxpWrite) - _ = binary.Write(&buf, binary.BigEndian, pac.requestId) + _ = binary.Write(&buf, binary.BigEndian, pac.requestID) _ = binary.Write(&buf, binary.BigEndian, uint32(len(fh.v))) _ = binary.Write(&buf, binary.BigEndian, fh.v) _ = binary.Write(&buf, binary.BigEndian, offset) diff --git a/lib/telemetry/questdb_options.go b/lib/telemetry/questdb_options.go index fe73f58a..1d595460 100644 --- a/lib/telemetry/questdb_options.go +++ b/lib/telemetry/questdb_options.go @@ -24,10 +24,10 @@ type QuestdbOptions struct { // Usually set to IlpFormatter. Fmt Formatter - // ServerUrl define the QuestDB server URL. + // ServerURL define the QuestDB server URL. // Currently, it only support the TCP scheme using the following // format "tcp://<host>:<port>". - ServerUrl string + ServerURL string proto string address string @@ -40,7 +40,7 @@ type QuestdbOptions struct { func (opts *QuestdbOptions) init() (err error) { var surl *url.URL - surl, err = url.Parse(opts.ServerUrl) + surl, err = url.Parse(opts.ServerURL) if err != nil { return err } diff --git a/lib/test/data.go b/lib/test/data.go index 075e6221..1a2d317d 100644 --- a/lib/test/data.go +++ b/lib/test/data.go @@ -275,7 +275,7 @@ func (data *Data) parse(content []byte) (err error) { func (data *Data) parseFlag(content []byte) { var ( - idx int = bytes.IndexByte(content, ':') + idx = bytes.IndexByte(content, ':') bkey []byte bval []byte ) diff --git a/lib/time/scheduler.go b/lib/time/scheduler.go index bc0b6a86..b3bef5df 100644 --- a/lib/time/scheduler.go +++ b/lib/time/scheduler.go @@ -18,7 +18,7 @@ import ( // ErrScheduleUnknown define an error when unknown schedule kind parsed from // value. -var ErrScheduleUnknown error = errors.New(`unknown schedule`) +var ErrScheduleUnknown = errors.New(`unknown schedule`) // List of kind of schedule. const ( diff --git a/lib/time/scheduler_test.go b/lib/time/scheduler_test.go index 7a4642cd..ef609143 100644 --- a/lib/time/scheduler_test.go +++ b/lib/time/scheduler_test.go @@ -427,7 +427,7 @@ func TestScheduler_calcNext_minutely(t *testing.T) { }} var ( - c testCase = cases[0] + c = cases[0] got *Scheduler err error diff --git a/lib/totp/totp.go b/lib/totp/totp.go index 54090bf6..953fb843 100644 --- a/lib/totp/totp.go +++ b/lib/totp/totp.go @@ -92,8 +92,8 @@ func New(cryptoHash CryptoHash, codeDigits, timeStep int) Protocol { // Generate one time password using the secret and current timestamp. func (p *Protocol) Generate(secret []byte) (otp string, err error) { var ( - mac hash.Hash = hmac.New(p.fnHash, secret) - now int64 = time.Now().Unix() + mac = hmac.New(p.fnHash, secret) + now = time.Now().Unix() ) return p.generateWithTimestamp(mac, now) @@ -103,8 +103,8 @@ func (p *Protocol) Generate(secret []byte) (otp string, err error) { // until the curent time. func (p *Protocol) GenerateN(secret []byte, n int) (listOTP []string, err error) { var ( - mac hash.Hash = hmac.New(p.fnHash, secret) - ts int64 = time.Now().Unix() + mac = hmac.New(p.fnHash, secret) + ts = time.Now().Unix() otp string t int64 @@ -134,8 +134,8 @@ func (p *Protocol) GenerateN(secret []byte, n int) (listOTP []string, err error) // For security reason, the maximum stepsBack is limited to DefStepsBack. func (p *Protocol) Verify(secret []byte, token string, stepsBack int) bool { var ( - mac hash.Hash = hmac.New(p.fnHash, secret) - now int64 = time.Now().Unix() + mac = hmac.New(p.fnHash, secret) + now = time.Now().Unix() ) if stepsBack <= 0 || stepsBack > DefStepsBack { diff --git a/lib/websocket/client.go b/lib/websocket/client.go index d3da7a24..590a4c83 100644 --- a/lib/websocket/client.go +++ b/lib/websocket/client.go @@ -257,7 +257,7 @@ func (cl *Client) Connect() (err error) { // response from server may include WebSocket frame, not just HTTP // response. if len(rest) > 0 { - var isClosing bool = cl.handleRaw(rest) + var isClosing = cl.handleRaw(rest) if isClosing { cl.Quit() return nil @@ -327,8 +327,8 @@ func (cl *Client) parseURI() (err error) { } var ( - serverAddress string = cl.remoteURL.Hostname() - serverPort string = cl.remoteURL.Port() + serverAddress = cl.remoteURL.Hostname() + serverPort = cl.remoteURL.Port() ) switch cl.remoteURL.Scheme { @@ -380,10 +380,10 @@ func (cl *Client) open() (err error) { // handshake send the WebSocket opening handshake. func (cl *Client) handshake() (rest []byte, err error) { var ( - logp = `handshake` - path string = cl.remoteURL.EscapedPath() - key []byte = generateHandshakeKey() - keyAccept string = generateHandshakeAccept(key) + logp = `handshake` + path = cl.remoteURL.EscapedPath() + key = generateHandshakeKey() + keyAccept = generateHandshakeAccept(key) bb bytes.Buffer req []byte @@ -491,9 +491,7 @@ func clientOnClose(cl *Client, frame *Frame) (err error) { } } - var ( - packet []byte = NewFrameClose(true, frame.closeCode, frame.payload) - ) + var packet = NewFrameClose(true, frame.closeCode, frame.payload) cl.Lock() err = cl.send(packet) @@ -574,7 +572,7 @@ func (cl *Client) handleFrame(frame *Frame) (isClosing bool) { switch frame.opcode { case OpcodeCont, OpcodeText, OpcodeBin: - var isInvalid bool = cl.handleFragment(frame) + var isInvalid = cl.handleFragment(frame) if isInvalid { isClosing = true } @@ -610,9 +608,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 - ) + var httpRes *http.Response httpRes, rest, err = libhttp.ParseResponseHeader(resp) if err != nil { @@ -623,7 +619,8 @@ func (cl *Client) handleHandshake(keyAccept string, resp []byte) (rest []byte, e return nil, errors.New(httpRes.Status) } - var gotAccept string = httpRes.Header.Get(_hdrKeyWSAccept) + var gotAccept = httpRes.Header.Get(_hdrKeyWSAccept) + if keyAccept != gotAccept { return nil, errors.New(`invalid server accept key`) } @@ -634,8 +631,8 @@ func (cl *Client) handleHandshake(keyAccept string, resp []byte) (rest []byte, e // handleRaw packet from server. func (cl *Client) handleRaw(packet []byte) (isClosing bool) { var ( - logp = `handleRaw` - frames *Frames = Unpack(packet) + logp = `handleRaw` + frames = Unpack(packet) f *Frame ) @@ -725,8 +722,8 @@ func (cl *Client) SendPong(payload []byte) (err error) { // If handler is nil, no response will be read from server. func (cl *Client) SendText(payload []byte) (err error) { var ( - logp = `SendText` - packet []byte = NewFrameText(true, payload) + logp = `SendText` + packet = NewFrameText(true, payload) ) cl.Lock() err = cl.send(packet) @@ -833,7 +830,7 @@ func (cl *Client) recv() (packet []byte, err error) { } var ( - buf []byte = make([]byte, 512) + buf = make([]byte, 512) neterr net.Error n int ok bool @@ -889,8 +886,8 @@ func (cl *Client) send(packet []byte) (err error) { // pinger send the PING control frame every 10 seconds. func (cl *Client) pinger() { var ( - logp = `pinger` - t *time.Ticker = time.NewTicker(cl.PingInterval) + logp = `pinger` + t = time.NewTicker(cl.PingInterval) err error ) diff --git a/lib/websocket/examples/account.go b/lib/websocket/examples/account.go index fafafd76..17b50668 100644 --- a/lib/websocket/examples/account.go +++ b/lib/websocket/examples/account.go @@ -12,7 +12,7 @@ type Account struct { } // Users contain list of user's account in the system. -var Users map[int64]*Account = map[int64]*Account{ +var Users = map[int64]*Account{ 1: { ID: 1, Name: "Groot", diff --git a/lib/websocket/examples/cmd/client/main.go b/lib/websocket/examples/cmd/client/main.go index 1b42ea29..a2cda935 100644 --- a/lib/websocket/examples/cmd/client/main.go +++ b/lib/websocket/examples/cmd/client/main.go @@ -62,7 +62,7 @@ func newChatClient(user *examples.Account) (cc *chatClient) { os.Exit(0) } - var err error = cc.conn.Connect() + var err = cc.conn.Connect() if err != nil { log.Fatal("Connect: " + err.Error()) } diff --git a/lib/websocket/examples/cmd/server/main.go b/lib/websocket/examples/cmd/server/main.go index 18a0777c..b542cb35 100644 --- a/lib/websocket/examples/cmd/server/main.go +++ b/lib/websocket/examples/cmd/server/main.go @@ -52,7 +52,8 @@ func main() { // value. func handleAuth(req *websocket.Handshake) (ctx context.Context, err error) { var ( - key string = req.Header.Get("Key") + key = req.Header.Get(`Key`) + id int64 user *examples.Account ) @@ -73,8 +74,9 @@ func handleClientAdd(ctx context.Context, conn int) { log.Printf("server: adding client %d ...", conn) var ( - uid int64 = ctx.Value(websocket.CtxKeyUID).(int64) - user *examples.Account = examples.Users[uid] + uid = ctx.Value(websocket.CtxKeyUID).(int64) + user = examples.Users[uid] + body string packet []byte err error @@ -105,8 +107,9 @@ func handleClientRemove(ctx context.Context, conn int) { log.Printf("server: client %d has been disconnected ...", conn) var ( - uid int64 = ctx.Value(websocket.CtxKeyUID).(int64) - user *examples.Account = examples.Users[uid] + uid = ctx.Value(websocket.CtxKeyUID).(int64) + user = examples.Users[uid] + body string packet []byte err error @@ -134,9 +137,10 @@ func handleClientRemove(ctx context.Context, conn int) { // handlePostMessage handle message that is send to server by client. func handlePostMessage(ctx context.Context, req *websocket.Request) (res websocket.Response) { var ( - uid int64 = ctx.Value(websocket.CtxKeyUID).(int64) - user *examples.Account = examples.Users[uid] - body string = user.Name + ": " + req.Body + uid = ctx.Value(websocket.CtxKeyUID).(int64) + user = examples.Users[uid] + body = user.Name + `: ` + req.Body + packet []byte err error conn int diff --git a/lib/websocket/frame.go b/lib/websocket/frame.go index 2f0e3714..b3003aaa 100644 --- a/lib/websocket/frame.go +++ b/lib/websocket/frame.go @@ -116,7 +116,8 @@ func NewFrameClose(isMasked bool, code CloseCode, payload []byte) []byte { // If there is a body, the first two bytes of the body MUST be a // 2-byte unsigned integer (in network byte order) representing a // status code. - var packet []byte = make([]byte, 2+len(payload)) + var packet = make([]byte, 2+len(payload)) + binary.BigEndian.PutUint16(packet[:2], uint16(code)) copy(packet[2:], payload) @@ -423,14 +424,14 @@ func (f *Frame) unpack(packet []byte) []byte { return nil } - var vuint64 uint64 = f.len - uint64(len(f.payload)) + var vuint64 = f.len - uint64(len(f.payload)) if uint64(len(packet)) < vuint64 { vuint64 = uint64(len(packet)) } if f.masked == frameIsMasked { var ( - start int = len(f.payload) % 4 + start = len(f.payload) % 4 x uint64 ) for ; x < vuint64; x++ { diff --git a/lib/websocket/funcs.go b/lib/websocket/funcs.go index 6137cddf..065cbe73 100644 --- a/lib/websocket/funcs.go +++ b/lib/websocket/funcs.go @@ -143,7 +143,7 @@ func Send(fd int, packet []byte, timeout time.Duration) (err error) { // Section 4 of [RFC4648]) this 20-byte hash. func generateHandshakeAccept(key []byte) string { key = append(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"...) - var sum [20]byte = sha1.Sum(key) + var sum = sha1.Sum(key) return base64.StdEncoding.EncodeToString(sum[:]) } diff --git a/lib/websocket/handshake.go b/lib/websocket/handshake.go index 8cea6cd2..122baa46 100644 --- a/lib/websocket/handshake.go +++ b/lib/websocket/handshake.go @@ -141,9 +141,7 @@ func (h *Handshake) getBytesChunk(sep byte, tolower bool) (chunk []byte) { // parseHTTPLine check if HTTP method is "GET", save the URI, and make sure // that HTTP version is 1.1. func (h *Handshake) parseHTTPLine() (err error) { - var ( - chunk []byte = h.getBytesChunk(' ', false) - ) + var chunk = h.getBytesChunk(' ', false) if !bytes.Equal(chunk, []byte("GET")) { return ErrInvalidHTTPMethod @@ -174,9 +172,7 @@ func (h *Handshake) parseHTTPLine() (err error) { // parseHeader of HTTP request. func (h *Handshake) parseHeader() (k, v []byte, err error) { - var ( - chunk []byte = h.getBytesChunk(':', true) - ) + var chunk = h.getBytesChunk(':', true) if len(chunk) == 0 { return nil, nil, nil @@ -425,7 +421,7 @@ func (h *Handshake) parse() (err error) { } } - var requiredFlags int = _hdrFlagHost | _hdrFlagConn | _hdrFlagUpgrade | _hdrFlagWSKey | _hdrFlagWSVersion + var requiredFlags = _hdrFlagHost | _hdrFlagConn | _hdrFlagUpgrade | _hdrFlagWSKey | _hdrFlagWSVersion if h.headerFlags&requiredFlags != requiredFlags { return ErrMissingRequiredHeader diff --git a/lib/websocket/internal/autobahn/autobahn.go b/lib/websocket/internal/autobahn/autobahn.go index 365b5e37..01c89481 100644 --- a/lib/websocket/internal/autobahn/autobahn.go +++ b/lib/websocket/internal/autobahn/autobahn.go @@ -54,9 +54,9 @@ type autobahnCaseReport map[string]autobahnTestReport type autobahnReport map[string]autobahnCaseReport -// PrintReports read the JSON reports from fileReportsJson and print the +// PrintReports read the JSON reports from fileReportsJSON and print the // total test cases and the failed one. -func PrintReports(fileReportsJson string) { +func PrintReports(fileReportsJSON string) { var ( logp = `PrintReports` @@ -65,7 +65,7 @@ func PrintReports(fileReportsJson string) { err error ) - raw, err = os.ReadFile(fileReportsJson) + raw, err = os.ReadFile(fileReportsJSON) if err != nil { log.Fatalf(`%s: %s`, logp, err) } diff --git a/lib/websocket/request.go b/lib/websocket/request.go index ef5902d8..d56d6406 100644 --- a/lib/websocket/request.go +++ b/lib/websocket/request.go @@ -81,7 +81,7 @@ func (req *Request) unpack(routes *rootRoute) (handler RouteHandler, err error) return nil, nil } - var pathQuery []string = strings.SplitN(req.Target, pathQuerySep, 2) + var pathQuery = strings.SplitN(req.Target, pathQuerySep, 2) req.Path = pathQuery[0] diff --git a/lib/websocket/request_test.go b/lib/websocket/request_test.go index 4bfe33cd..ed12bec6 100644 --- a/lib/websocket/request_test.go +++ b/lib/websocket/request_test.go @@ -14,7 +14,7 @@ import ( ) func TestRequestReset(t *testing.T) { - var req *Request = _reqPool.Get().(*Request) + var req = _reqPool.Get().(*Request) req.reset() diff --git a/lib/websocket/response.go b/lib/websocket/response.go index 6a1ffe30..6ea65b24 100644 --- a/lib/websocket/response.go +++ b/lib/websocket/response.go @@ -55,8 +55,8 @@ type Response struct { // and wrapped in TEXT frame. func NewBroadcast(message, body string) (packet []byte, err error) { var ( - logp = `NewBroadcast` - res *Response = _resPool.Get().(*Response) + logp = `NewBroadcast` + res = _resPool.Get().(*Response) ) res.reset() diff --git a/lib/websocket/response_test.go b/lib/websocket/response_test.go index 03d171d5..d5cf02cf 100644 --- a/lib/websocket/response_test.go +++ b/lib/websocket/response_test.go @@ -11,7 +11,7 @@ import ( ) func TestResponseReset(t *testing.T) { - var res *Response = _resPool.Get().(*Response) + var res = _resPool.Get().(*Response) res.reset() diff --git a/lib/websocket/rootroute.go b/lib/websocket/rootroute.go index 8ef49303..0d2f6027 100644 --- a/lib/websocket/rootroute.go +++ b/lib/websocket/rootroute.go @@ -108,7 +108,7 @@ func (root *rootRoute) add(method, target string, handler RouteHandler) (err err method = strings.ToUpper(method) var ( - parent *route = root.getParent(method) + parent = root.getParent(method) bb *bytes.Buffer x int @@ -181,7 +181,7 @@ func (root *rootRoute) get(method, target string) (params targetParam, handler R method = strings.ToUpper(method) var ( - parent *route = root.getParent(method) + parent = root.getParent(method) child *route bb *bytes.Buffer diff --git a/lib/websocket/route.go b/lib/websocket/route.go index 01327481..51d16c45 100644 --- a/lib/websocket/route.go +++ b/lib/websocket/route.go @@ -69,7 +69,7 @@ func (r *route) getChildAsParam() (c *route) { // formatted print to print pointer to route as address. func (r *route) String() (out string) { var ( - bb *bytes.Buffer = _bbPool.Get().(*bytes.Buffer) + bb = _bbPool.Get().(*bytes.Buffer) c *route x int diff --git a/lib/websocket/server.go b/lib/websocket/server.go index 4fcd98fd..75855c9e 100644 --- a/lib/websocket/server.go +++ b/lib/websocket/server.go @@ -163,7 +163,7 @@ func (serv *Server) createSockServer() (err error) { // RegisterTextHandler register specific function to be called by server when // request opcode is text, and method and target matched with Request. func (serv *Server) RegisterTextHandler(method, target string, handler RouteHandler) (err error) { - var logp string = `RegisterTextHandler` + var logp = `RegisterTextHandler` if len(method) == 0 { return fmt.Errorf("%s: empty method", logp) @@ -445,7 +445,7 @@ func (serv *Server) handleFrame(conn int, frame *Frame) (isClosing bool) { switch frame.opcode { case OpcodeCont, OpcodeText, OpcodeBin: - var isInvalid bool = serv.handleFragment(conn, frame) + var isInvalid = serv.handleFragment(conn, frame) if isInvalid { isClosing = true } @@ -559,7 +559,7 @@ func (serv *Server) handleStatus(conn int) { } var ( - res string = fmt.Sprintf(_resStatusOK, contentType, len(data), data) + res = fmt.Sprintf(_resStatusOK, contentType, len(data), data) err error ) @@ -627,7 +627,7 @@ func (serv *Server) handleClose(conn int, req *Frame) { } var ( - packet []byte = NewFrameClose(false, req.closeCode, req.payload) + packet = NewFrameClose(false, req.closeCode, req.payload) err error ) @@ -642,8 +642,8 @@ func (serv *Server) handleClose(conn int, req *Frame) { // handleBadRequest by sending Close frame with status. func (serv *Server) handleBadRequest(conn int) { var ( - logp = `handleBadRequest` - frameClose []byte = NewFrameClose(false, StatusBadRequest, nil) + logp = `handleBadRequest` + frameClose = NewFrameClose(false, StatusBadRequest, nil) err error ) @@ -665,8 +665,8 @@ out: // handleInvalidData by sending Close frame with status 1007. func (serv *Server) handleInvalidData(conn int) { var ( - logp = `handleInvalidData` - frameClose []byte = NewFrameClose(false, StatusInvalidData, nil) + logp = `handleInvalidData` + frameClose = NewFrameClose(false, StatusInvalidData, nil) err error ) @@ -698,8 +698,8 @@ func (serv *Server) handlePing(conn int, req *Frame) { req.masked = 0 var ( - logp = `handlePing` - res []byte = req.pack() + logp = `handlePing` + res = req.pack() err error ) @@ -870,7 +870,7 @@ func (serv *Server) delayReader(conn int) { // every N seconds. func (serv *Server) pollPinger() { var ( - pingTicker *time.Ticker = time.NewTicker(16 * time.Second) + pingTicker = time.NewTicker(16 * time.Second) all []int conn int diff --git a/lib/websocket/server_test.go b/lib/websocket/server_test.go index 941cd508..64a9d71d 100644 --- a/lib/websocket/server_test.go +++ b/lib/websocket/server_test.go @@ -24,7 +24,7 @@ func createClient(t *testing.T, endpoint string) (cl *Client) { Endpoint: endpoint, } - var err error = cl.parseURI() + var err = cl.parseURI() if err != nil { t.Fatal(err) return diff --git a/lib/websocket/websocket_test.go b/lib/websocket/websocket_test.go index 6e1e6c39..fed5fef6 100644 --- a/lib/websocket/websocket_test.go +++ b/lib/websocket/websocket_test.go @@ -8,7 +8,6 @@ import ( "context" "fmt" "log" - "net/url" "os" "strconv" "testing" @@ -53,7 +52,7 @@ func generateDummyPayload(size uint64) (payload []byte, masked []byte) { // testHandleText from websocket by echo-ing back the payload. func testHandleText(conn int, payload []byte) { var ( - packet []byte = NewFrameText(false, payload) + packet = NewFrameText(false, payload) err error ) @@ -66,7 +65,7 @@ func testHandleText(conn int, payload []byte) { // testHandleBin from websocket by echo-ing back the payload. func testHandleBin(conn int, payload []byte) { var ( - packet []byte = NewFrameBin(false, payload) + packet = NewFrameBin(false, payload) err error ) @@ -79,7 +78,7 @@ func testHandleBin(conn int, payload []byte) { // testHandleAuth with token in query parameter func testHandleAuth(req *Handshake) (ctx context.Context, err error) { var ( - q url.Values = req.URL.Query() + q = req.URL.Query() extJWT string ) |
