diff options
| author | Shulhan <ms@kilabit.info> | 2024-03-02 18:28:58 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2024-03-05 14:53:03 +0700 |
| commit | b921ebfb3e81b367ff24305eb18c5dd073b38635 (patch) | |
| tree | 89c88e32ad92af2ade65dec6552ddd06ddc0cd90 | |
| parent | 901c9803e6f93e0d5ee282f4061309022c46f490 (diff) | |
| download | pakakeh.go-b921ebfb3e81b367ff24305eb18c5dd073b38635.tar.xz | |
all: comply with linter recommendations #1
Instead of annotating the lines that caught by linters, fix it to comply
with the recommendations.
This causes several breaking changes, especially related to naming,
* api/slack: [Message.IconUrl] become [Message.IconURL]
* lib/dns: DefaultSoaMinumumTtl become DefaultSoaMinimumTTL
* lib/email: [Message.SetBodyHtml] become [Message.SetBodyHTML]
* lib/http: [Client.GenerateHttpRequest] become
[Client.GenerateHTTPRequest]
* lib/http: [ClientOptions.ServerUrl] become [ClientOptions.ServerURL]
* lib/http: [EndpointRequest.HttpWriter] become
[EndpointRequest.HTTPWriter]
* lib/http: [EndpointRequest.HttpRequest] become
[EndpointRequest.HTTPRequest]
* lib/http: [ServerOptions.EnableIndexHtml] become
[ServerOptions.EnableIndexHTML]
* lib/http: [SSEConn.HttpRequest] become [SSEConn.HTTPRequest]
* lib/smtp: [ClientOptions.ServerUrl] become [ClientOptions.ServerURL]
* lib/ssh/sftp: [FileAttrs.SetUid] become [FileAttrs.SetUID]
* lib/ssh/sftp: [FileAttrs.Uid] become [FileAttrs.UID]
50 files changed, 175 insertions, 226 deletions
diff --git a/api/slack/message.go b/api/slack/message.go index 2a62c200..1483f20d 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"` //revive:disable-line + IconURL string `json:"icon_url,omitempty"` Text string `json:"text"` } diff --git a/api/slack/webhook_client.go b/api/slack/webhook_client.go index 753f38bc..651f8d35 100644 --- a/api/slack/webhook_client.go +++ b/api/slack/webhook_client.go @@ -32,7 +32,7 @@ func NewWebhookClient(webhookURL, user, channel string) (wcl *WebhookClient, err } clientOpts := &libhttp.ClientOptions{ - ServerUrl: fmt.Sprintf("%s://%s", wurl.Scheme, wurl.Host), + ServerURL: fmt.Sprintf("%s://%s", wurl.Scheme, wurl.Host), } wcl = &WebhookClient{ Client: libhttp.NewClient(clientOpts), diff --git a/api/telegram/bot/bot.go b/api/telegram/bot/bot.go index f0e2c009..2f237489 100644 --- a/api/telegram/bot/bot.go +++ b/api/telegram/bot/bot.go @@ -110,7 +110,7 @@ func New(opts Options) (bot *Bot, err error) { } clientOpts := &http.ClientOptions{ - ServerUrl: defURL + opts.Token + "/", + ServerURL: defURL + opts.Token + `/`, } bot = &Bot{ opts: opts, diff --git a/api/telegram/bot/passport_data.go b/api/telegram/bot/passport_data.go index e7d9d271..3c3d077b 100644 --- a/api/telegram/bot/passport_data.go +++ b/api/telegram/bot/passport_data.go @@ -9,8 +9,4 @@ package bot type PassportData struct { // Encrypted credentials required to decrypt the data. Credentials EncryptedCredentials - - // Array with information about documents and other Telegram Passport - // elements that was shared with the bot. - data []EncryptedPassportElement //nolint: structcheck,unused } diff --git a/cmd/httpdfs/main.go b/cmd/httpdfs/main.go index 0790656b..ed62c07f 100644 --- a/cmd/httpdfs/main.go +++ b/cmd/httpdfs/main.go @@ -11,8 +11,9 @@ import ( "log" "os" "os/signal" + "syscall" - "git.sr.ht/~shulhan/pakakeh.go" + pakakeh "git.sr.ht/~shulhan/pakakeh.go" libhttp "git.sr.ht/~shulhan/pakakeh.go/lib/http" "git.sr.ht/~shulhan/pakakeh.go/lib/memfs" ) @@ -47,7 +48,7 @@ func main() { os.Exit(0) } if flagVersion { - fmt.Println(share.Version) + fmt.Println(pakakeh.Version) os.Exit(0) } @@ -84,7 +85,7 @@ func main() { serverOpts = libhttp.ServerOptions{ Memfs: mfs, Address: flagAddress, - EnableIndexHtml: true, + EnableIndexHTML: true, } httpd *libhttp.Server ) @@ -95,7 +96,7 @@ func main() { } var signalq = make(chan os.Signal, 1) - signal.Notify(signalq, os.Interrupt, os.Kill) + signal.Notify(signalq, os.Interrupt, syscall.SIGTERM) go func() { log.Printf(`%s: serving %q at http://%s`, cmdName, dirBase, flagAddress) diff --git a/cmd/sendemail/main.go b/cmd/sendemail/main.go index 2e69b782..97460e2b 100644 --- a/cmd/sendemail/main.go +++ b/cmd/sendemail/main.go @@ -106,7 +106,7 @@ func main() { if err != nil { log.Println(err) } - _ = msg.SetBodyHtml(content) + _ = msg.SetBodyHTML(content) } mailb, err = msg.Pack() @@ -120,7 +120,7 @@ func main() { mailtx = smtp.NewMailTx(from, []string{to}, mailb) clientOpts = smtp.ClientOptions{ - ServerUrl: serverURL, + ServerURL: serverURL, AuthUser: os.Getenv(envSMTPUsername), AuthPass: os.Getenv(envSMTPPassword), AuthMechanism: smtp.SaslMechanismPlain, diff --git a/cmd/smtpcli/client.go b/cmd/smtpcli/client.go index 10020719..70c7b392 100644 --- a/cmd/smtpcli/client.go +++ b/cmd/smtpcli/client.go @@ -30,7 +30,7 @@ type client struct { func newClient(remoteURL string) (cli *client, err error) { var ( clientOpts = smtp.ClientOptions{ - ServerUrl: remoteURL, + ServerURL: remoteURL, } ) diff --git a/lib/crypto/crypto.go b/lib/crypto/crypto.go index 12718a89..0cf3f484 100644 --- a/lib/crypto/crypto.go +++ b/lib/crypto/crypto.go @@ -249,7 +249,9 @@ func readPassTerm(termrw io.ReadWriter, file string) (pass string, err error) { if err != nil { return ``, fmt.Errorf(`MakeRaw: %w`, err) } - defer term.Restore(stdin, oldState) + defer func() { + _ = term.Restore(stdin, oldState) + }() termrw = os.Stdin } diff --git a/lib/crypto/crypto_test.go b/lib/crypto/crypto_test.go index 96751f6d..b99ff4a4 100644 --- a/lib/crypto/crypto_test.go +++ b/lib/crypto/crypto_test.go @@ -57,12 +57,6 @@ func TestEncryptOaep(t *testing.T) { t.Logf(`max message size = public key size (%d) - 2*hash.Size (%d) - 2 = %d`, rsapub.Size(), 2*hash.Size(), maxSize) - cipher, err = rsa.EncryptOAEP(hash, rand.Reader, rsapub, expPlain, nil) - if err != nil { - var expError = string(tdata.Output[`error_too_long`]) - test.Assert(t, `rsa.EncryptOAEP`, expError, err.Error()) - } - cipher, err = EncryptOaep(hash, rand.Reader, rsapub, expPlain, nil) if err != nil { t.Fatal(err) diff --git a/lib/dns/rdata_soa.go b/lib/dns/rdata_soa.go index 6c195f6a..f7d97176 100644 --- a/lib/dns/rdata_soa.go +++ b/lib/dns/rdata_soa.go @@ -14,8 +14,7 @@ const ( 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. + DefaultSoaMinimumTTL uint32 = 1 * 60 * 60 // 1 Hour. ) // RDataSOA contains the authority of zone. @@ -86,6 +85,6 @@ func (soa *RDataSOA) init() { soa.Retry = DefaultSoaRetry } if soa.Minimum == 0 { - soa.Minimum = DefaultSoaMinimumTtl + soa.Minimum = DefaultSoaMinimumTTL } } diff --git a/lib/dns/zone.go b/lib/dns/zone.go index 8c6f99cb..281e9968 100644 --- a/lib/dns/zone.go +++ b/lib/dns/zone.go @@ -119,7 +119,7 @@ func ParseZone(content []byte, origin string, ttl uint32) (zone *Zone, err error ) if ttl <= 0 { - ttl = DefaultSoaMinimumTtl + ttl = DefaultSoaMinimumTTL } zone = NewZone(``, origin) diff --git a/lib/email/message.go b/lib/email/message.go index 9623b395..9c888f89 100644 --- a/lib/email/message.go +++ b/lib/email/message.go @@ -304,8 +304,8 @@ func (msg *Message) DKIMVerify() (*dkim.Status, error) { return msg.dkimStatus, nil } -// SetBodyHtml set or replace the message's body HTML content. -func (msg *Message) SetBodyHtml(content []byte) (err error) { //revive:disable-line +// SetBodyHTML set or replace the message's body HTML content. +func (msg *Message) SetBodyHTML(content []byte) (err error) { err = msg.setBody([]byte(contentTypeTextHTML), content) if err != nil { return fmt.Errorf("SetBodyHtml: %w", err) diff --git a/lib/email/message_test.go b/lib/email/message_test.go index 647bbe98..a26f81c6 100644 --- a/lib/email/message_test.go +++ b/lib/email/message_test.go @@ -336,7 +336,7 @@ func TestMessage_packSingle(t *testing.T) { } } if len(c.bodyHTML) > 0 { - err = msg.SetBodyHtml([]byte(c.bodyHTML)) + err = msg.SetBodyHTML([]byte(c.bodyHTML)) if err != nil { t.Fatal(err) } diff --git a/lib/http/callback_error_handler.go b/lib/http/callback_error_handler.go index ec0c4a8a..7a1c075d 100644 --- a/lib/http/callback_error_handler.go +++ b/lib/http/callback_error_handler.go @@ -44,14 +44,14 @@ func DefaultErrorHandler(epr *EndpointRequest) { errInternal.Code = http.StatusInternalServerError } } else { - mlog.Errf("%s: %s %s: %s", logp, epr.HttpRequest.Method, - epr.HttpRequest.URL.Path, epr.Error) + mlog.Errf(`%s: %s %s: %s`, logp, epr.HTTPRequest.Method, + epr.HTTPRequest.URL.Path, epr.Error) errInternal = liberrors.Internal(epr.Error) } - epr.HttpWriter.Header().Set(HeaderContentType, ContentTypeJSON) - epr.HttpWriter.WriteHeader(errInternal.Code) + epr.HTTPWriter.Header().Set(HeaderContentType, ContentTypeJSON) + epr.HTTPWriter.WriteHeader(errInternal.Code) jsonb, err = json.Marshal(errInternal) if err != nil { @@ -59,7 +59,7 @@ func DefaultErrorHandler(epr *EndpointRequest) { return } - _, err = epr.HttpWriter.Write(jsonb) + _, err = epr.HTTPWriter.Write(jsonb) if err != nil { mlog.Errf("%s: Write: %s", logp, err) } diff --git a/lib/http/client.go b/lib/http/client.go index 24d83a9a..9b59fa6d 100644 --- a/lib/http/client.go +++ b/lib/http/client.go @@ -25,11 +25,11 @@ import ( "strings" "time" - "git.sr.ht/~shulhan/pakakeh.go" + pakakeh "git.sr.ht/~shulhan/pakakeh.go" ) var ( - defUserAgent = `libhttp/` + share.Version + defUserAgent = `libhttp/` + pakakeh.Version ) // Client is a wrapper for standard [http.Client] with simplified @@ -174,7 +174,7 @@ out: return res, err } -// GenerateHttpRequest generate [http.Request] from method, rpath, +// GenerateHTTPRequest generate [http.Request] from method, rpath, // rtype, hdr, and params. // // For HTTP method GET, CONNECT, DELETE, HEAD, OPTIONS, or TRACE; the params @@ -193,9 +193,7 @@ out: // body. // - If rtype is [RequestTypeJSON] and params is not nil, the params // will be encoded as JSON in body. -// -//revive:disable-next-line -func (client *Client) GenerateHttpRequest( +func (client *Client) GenerateHTTPRequest( method RequestMethod, rpath string, rtype RequestType, @@ -203,7 +201,7 @@ func (client *Client) GenerateHttpRequest( params interface{}, ) (req *http.Request, err error) { var ( - logp = "GenerateHttpRequest" + logp = `GenerateHTTPRequest` paramsAsURLValues url.Values isParamsURLValues bool paramsAsJSON []byte @@ -264,7 +262,7 @@ func (client *Client) GenerateHttpRequest( } rpath = path.Join(`/`, rpath) - fullURL := client.opts.ServerUrl + rpath + var fullURL = client.opts.ServerURL + rpath req, err = http.NewRequest(method.String(), fullURL, body) if err != nil { @@ -428,7 +426,7 @@ func (client *Client) doRequest( res *http.Response, resBody []byte, err error, ) { rpath = path.Join(`/`, rpath) - fullURL := client.opts.ServerUrl + rpath + var fullURL = client.opts.ServerURL + rpath httpReq, err := http.NewRequest(httpMethod, fullURL, body) if err != nil { diff --git a/lib/http/client_options.go b/lib/http/client_options.go index 8e573d70..b3cd195e 100644 --- a/lib/http/client_options.go +++ b/lib/http/client_options.go @@ -17,11 +17,11 @@ type ClientOptions struct { // This field is optional. Headers http.Header - // ServerUrl define the server address without path, for example + // ServerURL define the server address without path, for example // "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 //revive:disable-line + ServerURL string // Timeout affect the http Transport Timeout and TLSHandshakeTimeout. // This field is optional, if not set it will set to 10 seconds. @@ -40,5 +40,5 @@ func (opts *ClientOptions) init() { if opts.Timeout <= 0 { opts.Timeout = defClientTimeout } - opts.ServerUrl = strings.TrimSuffix(opts.ServerUrl, `/`) + opts.ServerURL = strings.TrimSuffix(opts.ServerURL, `/`) } diff --git a/lib/http/client_request.go b/lib/http/client_request.go index 635c88da..a1a2d7ec 100644 --- a/lib/http/client_request.go +++ b/lib/http/client_request.go @@ -76,7 +76,7 @@ func (creq *ClientRequest) toHTTPRequest(client *Client) (httpReq *http.Request, ) if client != nil { - path.WriteString(client.opts.ServerUrl) + path.WriteString(client.opts.ServerURL) } path.WriteString(creq.Path) paramsAsURLValues, isParamsURLValues = creq.Params.(url.Values) diff --git a/lib/http/client_test.go b/lib/http/client_test.go index 6aa82f44..b92b3b11 100644 --- a/lib/http/client_test.go +++ b/lib/http/client_test.go @@ -16,7 +16,7 @@ func TestClient_Download(t *testing.T) { var ( logp = `Download` clientOpts = ClientOptions{ - ServerUrl: fmt.Sprintf("http://%s", testServer.Options.Address), + ServerURL: `http://` + testServer.Options.Address, } client = NewClient(&clientOpts) diff --git a/lib/http/endpoint.go b/lib/http/endpoint.go index 570529e4..1d8d4699 100644 --- a/lib/http/endpoint.go +++ b/lib/http/endpoint.go @@ -77,8 +77,8 @@ func (ep *Endpoint) call( logp = "Endpoint.call" epr = &EndpointRequest{ Endpoint: ep, - HttpWriter: res, - HttpRequest: req, + HTTPWriter: res, + HTTPRequest: req, } responseBody []byte e error diff --git a/lib/http/endpoint_example_test.go b/lib/http/endpoint_example_test.go index 231421ce..6cf9b515 100644 --- a/lib/http/endpoint_example_test.go +++ b/lib/http/endpoint_example_test.go @@ -26,19 +26,19 @@ func ExampleEndpoint_errorHandler() { RequestType: RequestTypeQuery, ResponseType: ResponseTypePlain, Call: func(epr *EndpointRequest) ([]byte, error) { - return nil, fmt.Errorf(epr.HttpRequest.Form.Get("error")) + return nil, fmt.Errorf(epr.HTTPRequest.Form.Get(`error`)) }, ErrorHandler: func(epr *EndpointRequest) { - epr.HttpWriter.Header().Set(HeaderContentType, ContentTypePlain) + epr.HTTPWriter.Header().Set(HeaderContentType, ContentTypePlain) codeMsg := strings.Split(epr.Error.Error(), ":") if len(codeMsg) != 2 { - epr.HttpWriter.WriteHeader(http.StatusInternalServerError) - _, _ = epr.HttpWriter.Write([]byte(epr.Error.Error())) + epr.HTTPWriter.WriteHeader(http.StatusInternalServerError) + _, _ = epr.HTTPWriter.Write([]byte(epr.Error.Error())) } else { code, _ := strconv.Atoi(codeMsg[0]) - epr.HttpWriter.WriteHeader(code) - _, _ = epr.HttpWriter.Write([]byte(codeMsg[1])) + epr.HTTPWriter.WriteHeader(code) + _, _ = epr.HTTPWriter.Write([]byte(codeMsg[1])) } }, } @@ -53,7 +53,7 @@ func ExampleEndpoint_errorHandler() { time.Sleep(1 * time.Second) clientOpts := &ClientOptions{ - ServerUrl: "http://" + serverOpts.Address, + ServerURL: `http://` + serverOpts.Address, } client := NewClient(clientOpts) diff --git a/lib/http/endpoint_request.go b/lib/http/endpoint_request.go index 10c52423..668b57c5 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 //revive:disable-line + HTTPWriter http.ResponseWriter Error error Endpoint *Endpoint - HttpRequest *http.Request //revive:disable-line + HTTPRequest *http.Request RequestBody []byte } diff --git a/lib/http/endpoint_response_example_test.go b/lib/http/endpoint_response_example_test.go index 6dad54d4..1fab11a4 100644 --- a/lib/http/endpoint_response_example_test.go +++ b/lib/http/endpoint_response_example_test.go @@ -36,7 +36,7 @@ func ExampleEndpointResponse() { ResponseType: ResponseTypeJSON, Call: func(epr *EndpointRequest) ([]byte, error) { res := &EndpointResponse{} - id := epr.HttpRequest.Form.Get("id") + id := epr.HTTPRequest.Form.Get(`id`) if len(id) == 0 { res.E.Code = http.StatusBadRequest res.E.Message = "empty parameter id" @@ -68,7 +68,7 @@ func ExampleEndpointResponse() { time.Sleep(1 * time.Second) clientOpts := &ClientOptions{ - ServerUrl: "http://127.0.0.1:7016", + ServerURL: `http://127.0.0.1:7016`, } cl := NewClient(clientOpts) params := url.Values{} diff --git a/lib/http/example_server_test.go b/lib/http/example_server_test.go index 2cf897c0..c9575172 100644 --- a/lib/http/example_server_test.go +++ b/lib/http/example_server_test.go @@ -53,7 +53,7 @@ func ExampleServer_customHTTPStatusCode() { Call: func(epr *EndpointRequest) ( resbody []byte, err error, ) { - epr.HttpWriter.WriteHeader(exp.Status) + epr.HTTPWriter.WriteHeader(exp.Status) return json.Marshal(exp) }, } @@ -67,7 +67,7 @@ func ExampleServer_customHTTPStatusCode() { time.Sleep(1 * time.Second) clientOpts := &ClientOptions{ - ServerUrl: "http://127.0.0.1:8123", + ServerURL: `http://127.0.0.1:8123`, } client := NewClient(clientOpts) diff --git a/lib/http/http.go b/lib/http/http.go index 535aefb9..838e5106 100644 --- a/lib/http/http.go +++ b/lib/http/http.go @@ -304,7 +304,7 @@ const ( HeaderSetCookie = `Set-Cookie` HeaderUserAgent = `User-Agent` HeaderXForwardedFor = `X-Forwarded-For` // https://en.wikipedia.org/wiki/X-Forwarded-For - HeaderXRealIp = `X-Real-Ip` //revive:disable-line + HeaderXRealIP = `X-Real-Ip` ) var ( @@ -322,7 +322,7 @@ var ( // "X-Real-IP" or "X-Forwarded-For", which ever non-empty first. // If no headers present, use the default address. func IPAddressOfRequest(headers http.Header, defAddr string) (addr string) { - addr = headers.Get(HeaderXRealIp) + addr = headers.Get(HeaderXRealIP) if len(addr) == 0 { addr, _ = ParseXForwardedFor(headers.Get(HeaderXForwardedFor)) if len(addr) == 0 { diff --git a/lib/http/http_test.go b/lib/http/http_test.go index 699ee20d..47c03894 100644 --- a/lib/http/http_test.go +++ b/lib/http/http_test.go @@ -33,9 +33,9 @@ var ( } cbPlain = func(epr *EndpointRequest) (resBody []byte, e error) { - s := fmt.Sprintf("%s\n", epr.HttpRequest.Form) - s += fmt.Sprintf("%s\n", epr.HttpRequest.PostForm) - s += fmt.Sprintf("%v\n", epr.HttpRequest.MultipartForm) + var s = fmt.Sprintf("%s\n", epr.HTTPRequest.Form) + s += fmt.Sprintf("%s\n", epr.HTTPRequest.PostForm) + s += fmt.Sprintf("%v\n", epr.HTTPRequest.MultipartForm) s += string(epr.RequestBody) return []byte(s), nil } @@ -45,7 +45,7 @@ var ( "form": "%s", "multipartForm": "%v", "body": %q -}`, epr.HttpRequest.Form, epr.HttpRequest.MultipartForm, epr.RequestBody) +}`, epr.HTTPRequest.Form, epr.HTTPRequest.MultipartForm, epr.RequestBody) return []byte(s), nil } ) @@ -153,7 +153,7 @@ func registerEndpoints() { Path: "/redirect/download", ResponseType: ResponseTypePlain, Call: func(epr *EndpointRequest) ([]byte, error) { - http.Redirect(epr.HttpWriter, epr.HttpRequest, "/download", http.StatusFound) + http.Redirect(epr.HTTPWriter, epr.HTTPRequest, `/download`, http.StatusFound) return nil, nil }, }) diff --git a/lib/http/server.go b/lib/http/server.go index 57f9756a..4d9a627f 100644 --- a/lib/http/server.go +++ b/lib/http/server.go @@ -337,8 +337,8 @@ func (srv *Server) Stop(wait time.Duration) (err error) { // with true will be returned. // // If the path is directory and does not contains index.html and -// EnableIndexHtml is true, server will generate list of content for -// index.html. +// [ServerOptions.EnableIndexHTML] is true, server will generate list of +// content for index.html. func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) { var ( nodeIndexHTML *memfs.Node @@ -375,11 +375,11 @@ func (srv *Server) getFSNode(reqPath string) (node *memfs.Node, isDir bool) { return nodeIndexHTML, true } - if !srv.Options.EnableIndexHtml { + if !srv.Options.EnableIndexHTML { return nil, false } - node.GenerateIndexHtml() + node.GenerateIndexHTML() } return node, false diff --git a/lib/http/server_test.go b/lib/http/server_test.go index e1d4d3f7..4d573540 100644 --- a/lib/http/server_test.go +++ b/lib/http/server_test.go @@ -910,7 +910,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} @@ -986,7 +986,7 @@ func TestServer_handleRange(t *testing.T) { func TestServer_handleRange_HEAD(t *testing.T) { var ( clOpts = &ClientOptions{ - ServerUrl: testServerURL, + ServerURL: testServerURL, } cl = NewClient(clOpts) @@ -1055,7 +1055,12 @@ func TestServerHandleRangeBig(t *testing.T) { ) srv = runServerFS(t, serverAddress, tempDir) - defer srv.Stop(100 * time.Millisecond) + defer func() { + var errStop = srv.Stop(100 * time.Millisecond) + if errStop != nil { + log.Fatal(errStop) + } + }() var ( tdata *test.Data @@ -1069,7 +1074,7 @@ func TestServerHandleRangeBig(t *testing.T) { var ( clOpts = &ClientOptions{ - ServerUrl: `http://` + serverAddress, + ServerURL: `http://` + serverAddress, } cl *Client ) diff --git a/lib/http/serveroptions.go b/lib/http/serveroptions.go index 8b3e0d79..38da8531 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 //revive:disable-line + EnableIndexHTML bool } func (opts *ServerOptions) init() { diff --git a/lib/http/sse_conn.go b/lib/http/sse_conn.go index c5da3e3c..bb3e4f94 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 //revive:disable-line + HTTPRequest *http.Request bufrw *bufio.ReadWriter conn net.Conn @@ -102,7 +102,7 @@ func (ep *SSEConn) workerKeepAlive(interval time.Duration) { err error ) - for _ = range ticker.C { + for range ticker.C { err = ep.WriteRaw(emptyMsg) if err != nil { // Write failed, probably connection has been @@ -134,9 +134,18 @@ func (ep *SSEConn) writeData(buf *bytes.Buffer, data string, id *string) { // handshake write the last HTTP response to indicate the connection is // accepted. func (ep *SSEConn) handshake() { - ep.bufrw.WriteString("HTTP/1.1 200 OK\r\n") - ep.bufrw.WriteString("content-type: text/event-stream\r\n") - ep.bufrw.WriteString("cache-control: no-cache\r\n") - ep.bufrw.WriteString("\r\n") - ep.bufrw.Flush() + var ( + bb bytes.Buffer + err error + ) + + bb.WriteString("HTTP/1.1 200 OK\r\n") + bb.WriteString("content-type: text/event-stream\r\n") + bb.WriteString("cache-control: no-cache\r\n") + bb.WriteString("\r\n") + + _, err = ep.bufrw.Write(bb.Bytes()) + if err == nil { + ep.bufrw.Flush() + } } diff --git a/lib/http/sse_endpoint.go b/lib/http/sse_endpoint.go index e1979985..c1bef50c 100644 --- a/lib/http/sse_endpoint.go +++ b/lib/http/sse_endpoint.go @@ -113,7 +113,7 @@ func (ep *SSEEndpoint) hijack(res http.ResponseWriter, req *http.Request) (sseco } sseconn = &SSEConn{ - HttpRequest: req, + HTTPRequest: req, } sseconn.conn, sseconn.bufrw, err = hijack.Hijack() diff --git a/lib/http/sseclient/sseclient.go b/lib/http/sseclient/sseclient.go index afc9ed05..04cd1bbf 100644 --- a/lib/http/sseclient/sseclient.go +++ b/lib/http/sseclient/sseclient.go @@ -30,7 +30,7 @@ import ( "strings" "time" - "git.sr.ht/~shulhan/pakakeh.go" + pakakeh "git.sr.ht/~shulhan/pakakeh.go" libhttp "git.sr.ht/~shulhan/pakakeh.go/lib/http" libnet "git.sr.ht/~shulhan/pakakeh.go/lib/net" ) @@ -180,7 +180,7 @@ func (cl *Client) init(header http.Header) (err error) { cl.header = http.Header{} } cl.header.Set(libhttp.HeaderHost, cl.serverURL.Host) - cl.header.Set(libhttp.HeaderUserAgent, `libhttp/`+share.Version) + cl.header.Set(libhttp.HeaderUserAgent, `libhttp/`+pakakeh.Version) cl.header.Set(libhttp.HeaderAccept, libhttp.ContentTypeEventStream) if cl.Timeout <= 0 { @@ -245,6 +245,7 @@ func (cl *Client) handshake() (packet []byte, err error) { } func (cl *Client) handshakeRequest() (err error) { + var logp = `handshakeRequest` var buf bytes.Buffer fmt.Fprintf(&buf, `GET %s`, cl.serverURL.Path) @@ -281,7 +282,10 @@ func (cl *Client) handshakeRequest() (err error) { var deadline = time.Now().Add(cl.Timeout) - cl.conn.SetWriteDeadline(deadline) + err = cl.conn.SetWriteDeadline(deadline) + if err != nil { + return fmt.Errorf(`%s: %w`, logp, err) + } var ( buflen = buf.Len() diff --git a/lib/http/sseclient/sseclient_test.go b/lib/http/sseclient/sseclient_test.go index 7467bbf5..0986efbf 100644 --- a/lib/http/sseclient/sseclient_test.go +++ b/lib/http/sseclient/sseclient_test.go @@ -6,6 +6,7 @@ package sseclient import ( "fmt" + "log" "math/rand" "sync/atomic" "testing" @@ -109,7 +110,9 @@ func TestClient(t *testing.T) { if err != nil { t.Fatal(`testRunSSEServer:`, err) } - t.Cleanup(func() { srv.Stop(1 * time.Second) }) + t.Cleanup(func() { + _ = srv.Stop(1 * time.Second) + }) var cl = Client{ Endpoint: fmt.Sprintf(`http://%s/sse`, srv.Options.Address), @@ -239,7 +242,9 @@ func TestClient_raw(t *testing.T) { if err != nil { t.Fatal(`testRunSSEServer:`, err) } - t.Cleanup(func() { srv.Stop(1 * time.Second) }) + t.Cleanup(func() { + _ = srv.Stop(1 * time.Second) + }) var cl = Client{ Endpoint: fmt.Sprintf(`http://%s/sse`, srv.Options.Address), @@ -350,7 +355,9 @@ func TestClientRetry(t *testing.T) { if err != nil { t.Fatal(`testRunSSEServer:`, err) } - t.Cleanup(func() { srv.Stop(1 * time.Second) }) + t.Cleanup(func() { + _ = srv.Stop(1 * time.Second) + }) var cl = Client{ Endpoint: fmt.Sprintf(`http://%s/sse`, srv.Options.Address), @@ -421,7 +428,12 @@ func testRunSSEServer(t *testing.T, cb libhttp.SSECallback) (srv *libhttp.Server return nil, err } - go srv.Start() + go func() { + var errStart = srv.Start() + if errStart != nil { + log.Fatal(errStart) + } + }() err = libnet.WaitAlive(`tcp`, address, 1*time.Second) if err != nil { diff --git a/lib/hunspell/hunspell.go b/lib/hunspell/hunspell.go index f4ca9d4d..eb813bb8 100644 --- a/lib/hunspell/hunspell.go +++ b/lib/hunspell/hunspell.go @@ -94,8 +94,6 @@ const ( ) // List of morphological and other IDs. -// -// nolint: deadcode,varcheck const ( morphKeyPH = "ph" morphKeyST = "st" diff --git a/lib/ini/ini.go b/lib/ini/ini.go index 325cb38c..b6dc22b5 100644 --- a/lib/ini/ini.go +++ b/lib/ini/ini.go @@ -50,7 +50,7 @@ func Open(filename string) (in *Ini, err error) { // Create the file if not exist. - f, err = os.Create(filename) + _, err = os.Create(filename) if err != nil { return nil, fmt.Errorf(`%s: %w`, logp, err) } diff --git a/lib/ini/reader.go b/lib/ini/reader.go index aeaf76d3..794ad6cf 100644 --- a/lib/ini/reader.go +++ b/lib/ini/reader.go @@ -9,7 +9,6 @@ import ( "errors" "fmt" "io" - "os" "strings" "unicode" @@ -82,27 +81,6 @@ func (reader *reader) reset(src []byte) { reader.bufFormat.Reset() } -// parseFile will open, read, and parse INI file `filename` and return an -// instance of Ini. -// -// On failure, it return nil and error. -func (reader *reader) parseFile(filename string) (in *Ini, err error) { - var ( - src []byte - ) - - src, err = os.ReadFile(filename) - if err != nil { - return - } - - reader.filename = filename - - in, err = reader.Parse(src) - - return -} - // Parse will parse INI config from slice of bytes `src` into `in`. func (reader *reader) Parse(src []byte) (in *Ini, err error) { in = &Ini{} diff --git a/lib/memfs/dirwatcher.go b/lib/memfs/dirwatcher.go index e1ab7dc1..045adc73 100644 --- a/lib/memfs/dirwatcher.go +++ b/lib/memfs/dirwatcher.go @@ -184,12 +184,17 @@ func (dw *DirWatcher) mapSubdirs(node *Node) { // onCreated handle new child created on parent node. func (dw *DirWatcher) onCreated(parent, child *Node) (err error) { + var logp = `onCreated` + if child.IsDir() { dw.dirsLocker.Lock() dw.dirs[child.Path] = child dw.dirsLocker.Unlock() } else { - dw.startWatchingFile(parent, child) + err = dw.startWatchingFile(parent, child) + if err != nil { + return fmt.Errorf(`%s: %w`, logp, err) + } } var ns = NodeState{ diff --git a/lib/memfs/node.go b/lib/memfs/node.go index 0fd41d61..34ed18a5 100644 --- a/lib/memfs/node.go +++ b/lib/memfs/node.go @@ -151,12 +151,10 @@ func (node *Node) Close() error { return nil } -// GenerateIndexHtml generate simple directory listing as HTML for all childs -// in this node. +// 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() { +func (node *Node) GenerateIndexHTML() { if !node.IsDir() { return } diff --git a/lib/net/net.go b/lib/net/net.go index 66b7db5a..09f99837 100644 --- a/lib/net/net.go +++ b/lib/net/net.go @@ -237,18 +237,16 @@ func WaitAlive(network, address string, timeout time.Duration) (err error) { ) for total < timeout { - select { - case <-ticker.C: - conn, err = dialer.Dial(network, address) - if err != nil { - total += dialTimeout - continue - } - // Connection successfully established. - ticker.Stop() - _ = conn.Close() - return nil + <-ticker.C + conn, err = dialer.Dial(network, address) + if err != nil { + total += dialTimeout + continue } + // Connection successfully established. + ticker.Stop() + _ = conn.Close() + return nil } ticker.Stop() return fmt.Errorf(`%s: timeout connecting to %s after %s`, logp, address, timeout) diff --git a/lib/smtp/client.go b/lib/smtp/client.go index 7668d9e1..8e393bc2 100644 --- a/lib/smtp/client.go +++ b/lib/smtp/client.go @@ -59,7 +59,7 @@ func NewClient(opts ClientOptions) (cl *Client, err error) { port uint16 ) - rurl, err = url.Parse(opts.ServerUrl) + rurl, err = url.Parse(opts.ServerURL) if err != nil { return nil, fmt.Errorf("%s: %w", logp, err) } diff --git a/lib/smtp/client_options.go b/lib/smtp/client_options.go index 4ae28e40..8adc9b6e 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 //revive:disable-line + ServerURL string // The user name to authenticate to remote server. // diff --git a/lib/smtp/client_test.go b/lib/smtp/client_test.go index 18ecb348..764a2c04 100644 --- a/lib/smtp/client_test.go +++ b/lib/smtp/client_test.go @@ -18,7 +18,7 @@ func TestClient_live(t *testing.T) { var ( clientOpts = ClientOptions{ - ServerUrl: os.Getenv(`SMTP_SERVER`), + ServerURL: os.Getenv(`SMTP_SERVER`), AuthUser: os.Getenv(`SMTP_USER`), AuthPass: os.Getenv(`SMTP_PASS`), AuthMechanism: SaslMechanismPlain, @@ -168,7 +168,7 @@ func TestAuth(t *testing.T) { func TestAuth2(t *testing.T) { var ( opts = ClientOptions{ - ServerUrl: testSMTPSAddress, + ServerURL: testSMTPSAddress, Insecure: true, } diff --git a/lib/smtp/smtp_test.go b/lib/smtp/smtp_test.go index cb288884..b36da4c7 100644 --- a/lib/smtp/smtp_test.go +++ b/lib/smtp/smtp_test.go @@ -101,7 +101,7 @@ func testRunServer() { func testNewClient(withAuth bool) (cl *Client) { var ( opts = ClientOptions{ - ServerUrl: testSMTPSAddress, + ServerURL: testSMTPSAddress, Insecure: true, } diff --git a/lib/sql/meta_example_test.go b/lib/sql/meta_example_test.go index bec88339..35674cf8 100644 --- a/lib/sql/meta_example_test.go +++ b/lib/sql/meta_example_test.go @@ -262,11 +262,6 @@ func ExampleMeta_WhereHolders() { } func ExampleMeta_deleteOnPostgresql() { - type Table struct { - Name string - ID int - } - var ( meta = sql.NewMeta(sql.DriverNamePostgres, sql.DMLKindUpdate) qid = 1 diff --git a/lib/ssh/config/config.go b/lib/ssh/config/config.go index 6f252398..98a8fb34 100644 --- a/lib/ssh/config/config.go +++ b/lib/ssh/config/config.go @@ -172,7 +172,10 @@ func (cfg *Config) Get(host string) (section *Section) { section.setDefaults() if host != `` && section.Field[KeyHostname] == `` { - section.Set(KeyHostname, host) + var err = section.Set(KeyHostname, host) + if err != nil { + return nil + } } return section diff --git a/lib/ssh/config/config_test.go b/lib/ssh/config/config_test.go index 23650a44..6ba52c53 100644 --- a/lib/ssh/config/config_test.go +++ b/lib/ssh/config/config_test.go @@ -110,7 +110,10 @@ func TestConfigGet(t *testing.T) { for _, c = range cases { section = cfg.Get(c.name) buf.Reset() - section.WriteTo(&buf) + _, err = section.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } test.Assert(t, c.name, c.exp, buf.String()) } } @@ -149,7 +152,10 @@ func TestConfigMerge(t *testing.T) { buf bytes.Buffer ) - gotSection.WriteTo(&buf) + _, err = gotSection.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } test.Assert(t, host, string(tdata.Output[host]), buf.String()) } diff --git a/lib/ssh/config/match_criteria.go b/lib/ssh/config/match_criteria.go index 38ecb7b3..f07b4fcf 100644 --- a/lib/ssh/config/match_criteria.go +++ b/lib/ssh/config/match_criteria.go @@ -6,6 +6,7 @@ package config import ( "bytes" + "fmt" "io" "strings" ) @@ -53,6 +54,7 @@ func newMatchCriteria(name, arg string) (criteria *matchCriteria, err error) { // MarshalText encode the criteria back to ssh_config format. func (mcriteria *matchCriteria) MarshalText() (text []byte, err error) { + var logp = `MarshalText` var buf bytes.Buffer if mcriteria.isNegate { @@ -70,7 +72,10 @@ func (mcriteria *matchCriteria) MarshalText() (text []byte, err error) { } else { buf.WriteByte(',') } - pat.WriteTo(&buf) + _, err = pat.WriteTo(&buf) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } } return buf.Bytes(), nil diff --git a/lib/ssh/config/section.go b/lib/ssh/config/section.go index 6fe4877e..37e7d90a 100644 --- a/lib/ssh/config/section.go +++ b/lib/ssh/config/section.go @@ -21,6 +21,8 @@ import ( // List of valid keys in Host or Match section. const ( + keyInclude = `include` + // List of key in Host or Match with single, string value. KeyAddKeysToAgent = `addkeystoagent` KeyAddressFamily = `addressfamily` @@ -60,73 +62,6 @@ const ( KeyUser = `user` ) -// TODO: list of keys that are not implemented yet due to hard or -// unknown how to test it. -// nolint: deadcode,varcheck -const ( - keyCiphers = "ciphers" - keyControlMaster = "controlmaster" - keyControlPath = "controlpath" - keyControlPersist = "controlpersist" - keyDynamicForward = "dynamicforward" - keyEnableSSHKeysign = "enablesshkeysign" - keyEscapeChar = "escapechar" - keyExitOnForwardFailure = "keyexitonforwardfailure" - keyFingerprintHash = "fingerprinthash" - keyForwardAgent = "forwardagent" - keyForwardX11 = "forwardx11" - keyForwardX11Timeout = "forwardx11timeout" - keyForwardX11Trusted = "forwardx11trusted" - keyGatewayPorts = "gatewayports" - keyGlobalKnownHostsFile = "globalknownhostsfile" - keyGSSAPIAuthentication = "gssapiauthentication" - keyGSSAPIDelegateCredentials = "gssapidelegatecredentials" - keyHashKnownHosts = "hashknownhosts" - keyHostBasedAuthentication = "hostbasedauthentication" - keyHostBaseKeyTypes = "hostbasedkeytypes" - keyHostKeyAlgorithms = "hostkeyalgorithms" - keyHostKeyAlias = "hostkeyalias" - keyIdentitiesOnly = "identitiesonly" - keyIgnoreUnknown = "ignoreunknown" - keyInclude = "include" - keyIPQoS = "ipqos" - keyKbdInteractiveAuthentication = "kbdinteractiveauthentication" - keyKbdInteractiveDevices = "kbdinteractivedevices" - keyKexAlgorithms = "kexalgorithms" - keyLocalCommand = "localcommand" - keyLocalForward = "localforward" - keyLogLevel = "loglevel" - keyMACs = "macs" - keyNoHostAuthenticationForLocalhost = "nohostauthenticationforlocalhost" - keyNumberOfPasswordPrompts = "numberofpasswordprompts" - keyPasswordAuthentication = "passwordauthentication" - keyPermitLocalCommand = "permitlocalcommand" - keyPKCS11Provider = "pkcs11provider" - keyPreferredAuthentications = "preferredauthentications" - keyProxyCommand = "proxycommand" - keyProxyJump = "proxyjump" - keyProxyUseFdpass = "proxyusefdpass" - keyPubkeyAcceptedKeyTypes = "pubkeyacceptedkeytypes" - keyPubkeyAuthentication = "pubkeyauthentication" - keyRekeyLimit = "rekeylimit" - keyRemoteCommand = "remotecommand" - keyRemoteForward = "remoteforward" - keyRequestTTY = "requesttty" - keyRevokeHostKeys = "revokehostkeys" - keyServerAliveCountMax = "serveralivecountmax" - keyServerAliveInterval = "serveraliveinterval" - keyStreamLocalBindMask = "streamlocalbindmask" - keyStreamLocalBindUnlink = "streamlocalbindunlink" - keyStrictHostKeyChecking = "stricthostkeychecking" - keySyslogFacility = "syslogfacility" - keyTCPKeepAlive = "tcpkeepalive" - keyTunnel = "tunnel" - keyTunnelDevince = "tunneldevice" - keyUpdatehostKeys = "updatehostkeys" - keyUseKeychain = "usekeychain" - keyVerifyHostKeyDNS = "verifyhostkeydns" -) - // Known values for key. const ( ValueAcceptNew = `accept-new` @@ -620,6 +555,7 @@ func (section *Section) UserKnownHostsFile() []string { // MarshalText encode the Section back to ssh_config format. // The key is indented by two spaces. func (section *Section) MarshalText() (text []byte, err error) { + var logp = `MarshalText` var buf bytes.Buffer if section.useCriteria { @@ -628,7 +564,10 @@ func (section *Section) MarshalText() (text []byte, err error) { var criteria *matchCriteria for _, criteria = range section.criteria { buf.WriteByte(' ') - criteria.WriteTo(&buf) + _, err = criteria.WriteTo(&buf) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } } } else { buf.WriteString(`Host`) @@ -640,7 +579,10 @@ func (section *Section) MarshalText() (text []byte, err error) { var pat *pattern for _, pat = range section.patterns { buf.WriteByte(' ') - pat.WriteTo(&buf) + _, err = pat.WriteTo(&buf) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } } } } @@ -701,11 +643,11 @@ func (section *Section) WriteTo(w io.Writer) (n int64, err error) { // pathFold remove the path prefix from input file "in", start from the // "config" directory and then the user's home directory. func (section *Section) pathFold(in string) (out string) { - if filepath.HasPrefix(in, section.dir) { + if strings.HasPrefix(in, section.dir) { out, _ = filepath.Rel(section.dir, in) return out } - if filepath.HasPrefix(in, section.homeDir) { + if strings.HasPrefix(in, section.homeDir) { out, _ = filepath.Rel(section.homeDir, in) return `~/` + out } diff --git a/lib/ssh/sftp/client.go b/lib/ssh/sftp/client.go index 79c89b48..d5db3a3a 100644 --- a/lib/ssh/sftp/client.go +++ b/lib/ssh/sftp/client.go @@ -337,6 +337,7 @@ func (cl *Client) MkdirAll(dir string, fa *FileAttrs) (err error) { continue } lastErr = handleStatusCode(res.code, res.message) + break } // Reset last error if its success. lastErr = nil diff --git a/lib/ssh/sftp/file_attrs.go b/lib/ssh/sftp/file_attrs.go index 65fb79ca..87ffc763 100644 --- a/lib/ssh/sftp/file_attrs.go +++ b/lib/ssh/sftp/file_attrs.go @@ -245,8 +245,8 @@ func (fa *FileAttrs) SetSize(v uint64) { fa.size = v } -// SetUid set the file attribute user ID. -func (fa *FileAttrs) SetUid(uid uint32) { //revive:disable-line +// SetUID set the file attribute user ID. +func (fa *FileAttrs) SetUID(uid uint32) { fa.flags |= attrUIDGID fa.uid = uid } @@ -262,8 +262,8 @@ func (fa *FileAttrs) Sys() interface{} { return fa } -// Uid return the user ID of file. -func (fa *FileAttrs) Uid() uint32 { //revive:disable-line +// UID return the user ID of file. +func (fa *FileAttrs) UID() uint32 { return fa.uid } diff --git a/lib/xmlrpc/client.go b/lib/xmlrpc/client.go index 40a9c318..1ea5c6b0 100644 --- a/lib/xmlrpc/client.go +++ b/lib/xmlrpc/client.go @@ -52,12 +52,12 @@ func NewClient(url *url.URL, timeout time.Duration) (client *Client, err error) if port == 0 { port = 443 } - clientOpts.ServerUrl = fmt.Sprintf("https://%s:%d", host, port) + clientOpts.ServerURL = fmt.Sprintf(`https://%s:%d`, host, port) } else { if port == 0 { port = 80 } - clientOpts.ServerUrl = fmt.Sprintf("http://%s:%d", host, port) + clientOpts.ServerURL = fmt.Sprintf(`http://%s:%d`, host, port) } client.conn = libhttp.NewClient(clientOpts) |
