From ec654b29b428aa72615d6283bfc2857b300ab190 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 14:20:39 +0800 Subject: [PATCH 01/31] use gofmput to format code --- .golangci.yml | 3 +-- admin.go | 2 +- caddy.go | 6 +++--- caddyconfig/caddyfile/importgraph.go | 3 +++ caddyconfig/caddyfile/parse.go | 1 - caddyconfig/httpcaddyfile/addresses.go | 6 ++++-- caddyconfig/httpcaddyfile/directives.go | 3 ++- caddyconfig/httpcaddyfile/httptype.go | 13 +++++++------ caddyconfig/httpcaddyfile/pkiapp.go | 1 - caddyconfig/httpcaddyfile/tlsapp.go | 1 - caddytest/caddytest.go | 16 ---------------- cmd/commandfuncs.go | 2 +- cmd/commands.go | 2 +- cmd/storagefuncs.go | 2 +- internal/sockets.go | 2 +- listeners.go | 1 - modules/caddyhttp/caddyhttp.go | 6 ++++-- modules/caddyhttp/celmatcher.go | 4 ++++ modules/caddyhttp/fileserver/browse.go | 2 +- modules/caddyhttp/matchers.go | 4 +--- modules/caddyhttp/reverseproxy/addresses.go | 3 +++ modules/caddyhttp/reverseproxy/caddyfile.go | 1 - modules/caddyhttp/reverseproxy/command.go | 3 ++- modules/caddyhttp/reverseproxy/fastcgi/client.go | 3 --- modules/caddyhttp/reverseproxy/reverseproxy.go | 3 ++- modules/caddyhttp/reverseproxy/streaming.go | 6 ++++-- modules/caddyhttp/templates/tplcontext.go | 3 --- modules/caddypki/acmeserver/acmeserver.go | 8 +++++--- modules/caddypki/ca.go | 4 ++++ modules/caddytls/connpolicy.go | 2 +- modules/logging/filewriter.go | 2 +- modules/logging/filters.go | 3 +-- replacer.go | 3 ++- 33 files changed, 60 insertions(+), 64 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 3d319f1584c..1dc305e0bf3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,8 +8,7 @@ linters: enable: - bodyclose - errcheck - - gofmt - - goimports + - gofumpt - gosec - gosimple - govet diff --git a/admin.go b/admin.go index 1966556a5b5..335b8e89545 100644 --- a/admin.go +++ b/admin.go @@ -1346,7 +1346,7 @@ var ( // will get deleted before the process gracefully exits. func PIDFile(filename string) error { pid := []byte(strconv.Itoa(os.Getpid()) + "\n") - err := os.WriteFile(filename, pid, 0600) + err := os.WriteFile(filename, pid, 0o600) if err != nil { return err } diff --git a/caddy.go b/caddy.go index 76d51c833c3..fac965e96cc 100644 --- a/caddy.go +++ b/caddy.go @@ -356,13 +356,13 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error { newCfg.Admin.Config.Persist == nil || *newCfg.Admin.Config.Persist) { dir := filepath.Dir(ConfigAutosavePath) - err := os.MkdirAll(dir, 0700) + err := os.MkdirAll(dir, 0o700) if err != nil { Log().Error("unable to create folder for config autosave", zap.String("dir", dir), zap.Error(err)) } else { - err := os.WriteFile(ConfigAutosavePath, cfgJSON, 0600) + err := os.WriteFile(ConfigAutosavePath, cfgJSON, 0o600) if err == nil { Log().Info("autosaved config (load with --resume flag)", zap.String("file", ConfigAutosavePath)) } else { @@ -831,7 +831,7 @@ func InstanceID() (uuid.UUID, error) { if err != nil { return uuid, err } - err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0600) + err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0o600) return uuid, err } else if err != nil { return [16]byte{}, err diff --git a/caddyconfig/caddyfile/importgraph.go b/caddyconfig/caddyfile/importgraph.go index 659c368002c..d27f4710bd9 100644 --- a/caddyconfig/caddyfile/importgraph.go +++ b/caddyconfig/caddyfile/importgraph.go @@ -34,6 +34,7 @@ func (i *importGraph) addNode(name string) { } i.nodes[name] = true } + func (i *importGraph) addNodes(names []string) { for _, name := range names { i.addNode(name) @@ -43,6 +44,7 @@ func (i *importGraph) addNodes(names []string) { func (i *importGraph) removeNode(name string) { delete(i.nodes, name) } + func (i *importGraph) removeNodes(names []string) { for _, name := range names { i.removeNode(name) @@ -73,6 +75,7 @@ func (i *importGraph) addEdge(from, to string) error { i.edges[from] = append(i.edges[from], to) return nil } + func (i *importGraph) addEdges(from string, tos []string) error { for _, to := range tos { err := i.addEdge(from, to) diff --git a/caddyconfig/caddyfile/parse.go b/caddyconfig/caddyfile/parse.go index 0a1a9e7b16f..620f0917d86 100644 --- a/caddyconfig/caddyfile/parse.go +++ b/caddyconfig/caddyfile/parse.go @@ -565,7 +565,6 @@ func (p *parser) doSingleImport(importFile string) ([]Token, error) { // are loaded into the current server block for later use // by directive setup functions. func (p *parser) directive() error { - // a segment is a list of tokens associated with this directive var segment Segment diff --git a/caddyconfig/httpcaddyfile/addresses.go b/caddyconfig/httpcaddyfile/addresses.go index 93bad27d61c..4f8db3a9b44 100644 --- a/caddyconfig/httpcaddyfile/addresses.go +++ b/caddyconfig/httpcaddyfile/addresses.go @@ -77,7 +77,8 @@ import ( // multiple addresses to the same lists of server blocks (a many:many mapping). // (Doing this is essentially a map-reduce technique.) func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBlock, - options map[string]any) (map[string][]serverBlock, error) { + options map[string]any, +) (map[string][]serverBlock, error) { sbmap := make(map[string][]serverBlock) for i, sblock := range originalServerBlocks { @@ -187,7 +188,8 @@ func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]se // listenerAddrsForServerBlockKey essentially converts the Caddyfile // site addresses to Caddy listener addresses for each server block. func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string, - options map[string]any) ([]string, error) { + options map[string]any, +) ([]string, error) { addr, err := ParseAddress(key) if err != nil { return nil, fmt.Errorf("parsing key: %v", err) diff --git a/caddyconfig/httpcaddyfile/directives.go b/caddyconfig/httpcaddyfile/directives.go index 9c86a22a1e5..13229ed5cd4 100644 --- a/caddyconfig/httpcaddyfile/directives.go +++ b/caddyconfig/httpcaddyfile/directives.go @@ -217,7 +217,8 @@ func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) { // NewRoute returns config values relevant to creating a new HTTP route. func (h Helper) NewRoute(matcherSet caddy.ModuleMap, - handler caddyhttp.MiddlewareHandler) []ConfigValue { + handler caddyhttp.MiddlewareHandler, +) []ConfigValue { mod, err := caddy.GetModule(caddy.GetModuleID(handler)) if err != nil { *h.warnings = append(*h.warnings, caddyconfig.Warning{ diff --git a/caddyconfig/httpcaddyfile/httptype.go b/caddyconfig/httpcaddyfile/httptype.go index ce2ebde3e23..fe7e7ced554 100644 --- a/caddyconfig/httpcaddyfile/httptype.go +++ b/caddyconfig/httpcaddyfile/httptype.go @@ -49,8 +49,7 @@ type App struct { } // ServerType can set up a config from an HTTP Caddyfile. -type ServerType struct { -} +type ServerType struct{} // Setup makes a config from the tokens. func (st ServerType) Setup( @@ -1059,8 +1058,8 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList, subroute *caddyhttp.Subroute, matcherSetsEnc []caddy.ModuleMap, p sbAddrAssociation, - warnings *[]caddyconfig.Warning) caddyhttp.RouteList { - + warnings *[]caddyconfig.Warning, +) caddyhttp.RouteList { // nothing to do if... there's nothing to do if len(matcherSetsEnc) == 0 && len(subroute.Routes) == 0 && subroute.Errors == nil { return routeList @@ -1608,8 +1607,10 @@ type sbAddrAssociation struct { serverBlocks []serverBlock } -const matcherPrefix = "@" -const namedRouteKey = "named_route" +const ( + matcherPrefix = "@" + namedRouteKey = "named_route" +) // Interface guard var _ caddyfile.ServerType = (*ServerType)(nil) diff --git a/caddyconfig/httpcaddyfile/pkiapp.go b/caddyconfig/httpcaddyfile/pkiapp.go index 3414636ee1b..b5c682187d9 100644 --- a/caddyconfig/httpcaddyfile/pkiapp.go +++ b/caddyconfig/httpcaddyfile/pkiapp.go @@ -174,7 +174,6 @@ func (st ServerType) buildPKIApp( options map[string]any, warnings []caddyconfig.Warning, ) (*caddypki.PKI, []caddyconfig.Warning, error) { - skipInstallTrust := false if _, ok := options["skip_install_trust"]; ok { skipInstallTrust = true diff --git a/caddyconfig/httpcaddyfile/tlsapp.go b/caddyconfig/httpcaddyfile/tlsapp.go index c63569e4184..21427524d8d 100644 --- a/caddyconfig/httpcaddyfile/tlsapp.go +++ b/caddyconfig/httpcaddyfile/tlsapp.go @@ -36,7 +36,6 @@ func (st ServerType) buildTLSApp( options map[string]any, warnings []caddyconfig.Warning, ) (*caddytls.TLS, []caddyconfig.Warning, error) { - tlsApp := &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)} var certLoaders []caddytls.CertificateLoader diff --git a/caddytest/caddytest.go b/caddytest/caddytest.go index 0958e6c9a4a..49665480485 100644 --- a/caddytest/caddytest.go +++ b/caddytest/caddytest.go @@ -63,7 +63,6 @@ type Tester struct { // NewTester will create a new testing client with an attached cookie jar func NewTester(t *testing.T) *Tester { - jar, err := cookiejar.New(nil) if err != nil { t.Fatalf("failed to create cookiejar: %s", err) @@ -94,7 +93,6 @@ func timeElapsed(start time.Time, name string) { // InitServer this will configure the server with a configurion of a specific // type. The configType must be either "json" or the adapter type. func (tc *Tester) InitServer(rawConfig string, configType string) { - if err := tc.initServer(rawConfig, configType); err != nil { tc.t.Logf("failed to load config: %s", err) tc.t.Fail() @@ -108,7 +106,6 @@ func (tc *Tester) InitServer(rawConfig string, configType string) { // InitServer this will configure the server with a configurion of a specific // type. The configType must be either "json" or the adapter type. func (tc *Tester) initServer(rawConfig string, configType string) error { - if testing.Short() { tc.t.SkipNow() return nil @@ -232,7 +229,6 @@ const initConfig = `{ // validateTestPrerequisites ensures the certificates are available in the // designated path and Caddy sub-process is running. func validateTestPrerequisites(t *testing.T) error { - // check certificates are found for _, certName := range Default.Certifcates { if _, err := os.Stat(getIntegrationDir() + certName); os.IsNotExist(err) { @@ -284,7 +280,6 @@ func isCaddyAdminRunning() error { } func getIntegrationDir() string { - _, filename, _, ok := runtime.Caller(1) if !ok { panic("unable to determine the current file path") @@ -304,7 +299,6 @@ func prependCaddyFilePath(rawConfig string) string { // CreateTestingTransport creates a testing transport that forces call dialing connections to happen locally func CreateTestingTransport() *http.Transport { - dialer := net.Dialer{ Timeout: 5 * time.Second, KeepAlive: 5 * time.Second, @@ -332,7 +326,6 @@ func CreateTestingTransport() *http.Transport { // AssertLoadError will load a config and expect an error func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) { - tc := NewTester(t) err := tc.initServer(rawConfig, configType) @@ -343,7 +336,6 @@ func AssertLoadError(t *testing.T, rawConfig string, configType string, expected // AssertRedirect makes a request and asserts the redirection happens func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, expectedStatusCode int) *http.Response { - redirectPolicyFunc := func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } @@ -381,7 +373,6 @@ func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, e // CompareAdapt adapts a config and then compares it against an expected result func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string, expectedResponse string) bool { - cfgAdapter := caddyconfig.GetAdapter(adapterName) if cfgAdapter == nil { t.Logf("unrecognized config adapter '%s'", adapterName) @@ -469,7 +460,6 @@ func applyHeaders(t *testing.T, req *http.Request, requestHeaders []string) { // AssertResponseCode will execute the request and verify the status code, returns a response for additional assertions func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) *http.Response { - resp, err := tc.Client.Do(req) if err != nil { tc.t.Fatalf("failed to call server %s", err) @@ -484,7 +474,6 @@ func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) // AssertResponse request a URI and assert the status code and the body contains a string func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expectedBody string) (*http.Response, string) { - resp := tc.AssertResponseCode(req, expectedStatusCode) defer resp.Body.Close() @@ -506,7 +495,6 @@ func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expe // AssertGetResponse GET a URI and expect a statusCode and body text func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) { - req, err := http.NewRequest("GET", requestURI, nil) if err != nil { tc.t.Fatalf("unable to create request %s", err) @@ -517,7 +505,6 @@ func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, e // AssertDeleteResponse request a URI and expect a statusCode and body text func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) { - req, err := http.NewRequest("DELETE", requestURI, nil) if err != nil { tc.t.Fatalf("unable to create request %s", err) @@ -528,7 +515,6 @@ func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int // AssertPostResponseBody POST to a URI and assert the response code and body func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) { - req, err := http.NewRequest("POST", requestURI, requestBody) if err != nil { tc.t.Errorf("failed to create request %s", err) @@ -542,7 +528,6 @@ func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []str // AssertPutResponseBody PUT to a URI and assert the response code and body func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) { - req, err := http.NewRequest("PUT", requestURI, requestBody) if err != nil { tc.t.Errorf("failed to create request %s", err) @@ -556,7 +541,6 @@ func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []stri // AssertPatchResponseBody PATCH to a URI and assert the response code and body func (tc *Tester) AssertPatchResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) { - req, err := http.NewRequest("PATCH", requestURI, requestBody) if err != nil { tc.t.Errorf("failed to create request %s", err) diff --git a/cmd/commandfuncs.go b/cmd/commandfuncs.go index dde870be6c3..837526ed013 100644 --- a/cmd/commandfuncs.go +++ b/cmd/commandfuncs.go @@ -565,7 +565,7 @@ func cmdFmt(fl Flags) (int, error) { output := caddyfile.Format(input) if fl.Bool("overwrite") { - if err := os.WriteFile(formatCmdConfigFile, output, 0600); err != nil { + if err := os.WriteFile(formatCmdConfigFile, output, 0o600); err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err) } return caddy.ExitCodeSuccess, nil diff --git a/cmd/commands.go b/cmd/commands.go index d1b76f4460d..3bf47df4e00 100644 --- a/cmd/commands.go +++ b/cmd/commands.go @@ -444,7 +444,7 @@ argument of --directory. If the directory does not exist, it will be created. if dir == "" { return caddy.ExitCodeFailedQuit, fmt.Errorf("designated output directory and specified section are required") } - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return caddy.ExitCodeFailedQuit, err } if err := doc.GenManTree(rootCmd, &doc.GenManHeader{ diff --git a/cmd/storagefuncs.go b/cmd/storagefuncs.go index 75790ab7b8a..a9f1bcac82f 100644 --- a/cmd/storagefuncs.go +++ b/cmd/storagefuncs.go @@ -200,7 +200,7 @@ func cmdExportStorage(fl Flags) (int, error) { hdr := &tar.Header{ Name: k, - Mode: 0600, + Mode: 0o600, Size: int64(len(v)), } diff --git a/internal/sockets.go b/internal/sockets.go index 761f92051c6..56ae9f4e6fa 100644 --- a/internal/sockets.go +++ b/internal/sockets.go @@ -52,5 +52,5 @@ func SplitUnixSocketPermissionsBits(addr string) (path string, fileMode fs.FileM // default to 0200 (symbolic: `u=w,g=,o=`) // if no permission bits are specified - return addr, 0200, nil + return addr, 0o200, nil } diff --git a/listeners.go b/listeners.go index 9e761be6054..4cd00b21e79 100644 --- a/listeners.go +++ b/listeners.go @@ -174,7 +174,6 @@ func (na NetworkAddress) listen(ctx context.Context, portOffset uint, config net if err := os.Chmod(address, unixFileMode); err != nil { return nil, fmt.Errorf("unable to set permissions (%s) on %s: %v", unixFileMode, address, err) } - } return socket, err } diff --git a/modules/caddyhttp/caddyhttp.go b/modules/caddyhttp/caddyhttp.go index c497dc7a1d2..f15aec5ed4b 100644 --- a/modules/caddyhttp/caddyhttp.go +++ b/modules/caddyhttp/caddyhttp.go @@ -307,5 +307,7 @@ const ( const separator = string(filepath.Separator) // Interface guard -var _ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil) -var _ caddyfile.Unmarshaler = (*tlsPlaceholderWrapper)(nil) +var ( + _ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil) + _ caddyfile.Unmarshaler = (*tlsPlaceholderWrapper)(nil) +) diff --git a/modules/caddyhttp/celmatcher.go b/modules/caddyhttp/celmatcher.go index cc87146ec59..1ba61a0528d 100644 --- a/modules/caddyhttp/celmatcher.go +++ b/modules/caddyhttp/celmatcher.go @@ -234,9 +234,11 @@ func (cr celHTTPRequest) Parent() interpreter.Activation { func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) { return cr.Request, nil } + func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val { panic("not implemented") } + func (cr celHTTPRequest) Equal(other ref.Val) ref.Val { if o, ok := other.Value().(celHTTPRequest); ok { return types.Bool(o.Request == cr.Request) @@ -255,12 +257,14 @@ type celPkixName struct{ *pkix.Name } func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) { return pn.Name, nil } + func (pn celPkixName) ConvertToType(typeVal ref.Type) ref.Val { if typeVal.TypeName() == "string" { return types.String(pn.Name.String()) } panic("not implemented") } + func (pn celPkixName) Equal(other ref.Val) ref.Val { if o, ok := other.Value().(string); ok { return types.Bool(pn.Name.String() == o) diff --git a/modules/caddyhttp/fileserver/browse.go b/modules/caddyhttp/fileserver/browse.go index 29f29fc8ebb..45b5cb86816 100644 --- a/modules/caddyhttp/fileserver/browse.go +++ b/modules/caddyhttp/fileserver/browse.go @@ -113,7 +113,7 @@ func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter, fs = http.Dir(repl.ReplaceAll(fsrv.Root, ".")) } - var tplCtx = &templateContext{ + tplCtx := &templateContext{ TemplateContext: templates.TemplateContext{ Root: fs, Req: r, diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go index fb84875d95a..f40802fc326 100644 --- a/modules/caddyhttp/matchers.go +++ b/modules/caddyhttp/matchers.go @@ -1392,9 +1392,7 @@ func ParseCaddyfileNestedMatcherSet(d *caddyfile.Dispenser) (caddy.ModuleMap, er return matcherSet, nil } -var ( - wordRE = regexp.MustCompile(`\w+`) -) +var wordRE = regexp.MustCompile(`\w+`) const regexpPlaceholderPrefix = "http.regexp" diff --git a/modules/caddyhttp/reverseproxy/addresses.go b/modules/caddyhttp/reverseproxy/addresses.go index 09394973924..82c1c799461 100644 --- a/modules/caddyhttp/reverseproxy/addresses.go +++ b/modules/caddyhttp/reverseproxy/addresses.go @@ -45,12 +45,15 @@ func (p parsedAddr) dialAddr() string { } return net.JoinHostPort(p.host, p.port) } + func (p parsedAddr) rangedPort() bool { return strings.Contains(p.port, "-") } + func (p parsedAddr) replaceablePort() bool { return strings.Contains(p.port, "{") && strings.Contains(p.port, "}") } + func (p parsedAddr) isUnix() bool { return caddy.IsUnixNetwork(p.network) } diff --git a/modules/caddyhttp/reverseproxy/caddyfile.go b/modules/caddyhttp/reverseproxy/caddyfile.go index f5eb7a5d01d..774f889ea07 100644 --- a/modules/caddyhttp/reverseproxy/caddyfile.go +++ b/modules/caddyhttp/reverseproxy/caddyfile.go @@ -549,7 +549,6 @@ func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { h.RequestBuffers = int64(size) } else if subdir == "response_buffers" { h.ResponseBuffers = int64(size) - } // TODO: These three properties are deprecated; remove them sometime after v2.6.4 diff --git a/modules/caddyhttp/reverseproxy/command.go b/modules/caddyhttp/reverseproxy/command.go index 8438b727830..9359f3d0b35 100644 --- a/modules/caddyhttp/reverseproxy/command.go +++ b/modules/caddyhttp/reverseproxy/command.go @@ -284,7 +284,8 @@ func cmdReverseProxy(fs caddycmd.Flags) (int, error) { var false bool cfg := &caddy.Config{ - Admin: &caddy.AdminConfig{Disabled: true, + Admin: &caddy.AdminConfig{ + Disabled: true, Config: &caddy.ConfigSettings{ Persist: &false, }, diff --git a/modules/caddyhttp/reverseproxy/fastcgi/client.go b/modules/caddyhttp/reverseproxy/fastcgi/client.go index ae36dd8b09c..04513dd85f3 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/client.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/client.go @@ -251,7 +251,6 @@ func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Respons // Get issues a GET request to the fcgi responder. func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error) { - p["REQUEST_METHOD"] = "GET" p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10) @@ -260,7 +259,6 @@ func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.R // Head issues a HEAD request to the fcgi responder. func (c *client) Head(p map[string]string) (resp *http.Response, err error) { - p["REQUEST_METHOD"] = "HEAD" p["CONTENT_LENGTH"] = "0" @@ -269,7 +267,6 @@ func (c *client) Head(p map[string]string) (resp *http.Response, err error) { // Options issues an OPTIONS request to the fcgi responder. func (c *client) Options(p map[string]string) (resp *http.Response, err error) { - p["REQUEST_METHOD"] = "OPTIONS" p["CONTENT_LENGTH"] = "0" diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index 842d75de8e1..b65dce7202a 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -450,7 +450,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht // It returns true when the loop is done and should break; false otherwise. The error value returned should // be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break). func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w http.ResponseWriter, proxyErr error, start time.Time, retries int, - repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler) (bool, error) { + repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler, +) (bool, error) { // get the updated list of upstreams upstreams := h.Upstreams if h.DynamicUpstreams != nil { diff --git a/modules/caddyhttp/reverseproxy/streaming.go b/modules/caddyhttp/reverseproxy/streaming.go index 71b93860846..c5369d8c3c5 100644 --- a/modules/caddyhttp/reverseproxy/streaming.go +++ b/modules/caddyhttp/reverseproxy/streaming.go @@ -522,5 +522,7 @@ var streamingBufPool = sync.Pool{ }, } -const defaultBufferSize = 32 * 1024 -const wordSize = int(unsafe.Sizeof(uintptr(0))) +const ( + defaultBufferSize = 32 * 1024 + wordSize = int(unsafe.Sizeof(uintptr(0))) +) diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go index 5dc4ae55326..89158f49251 100644 --- a/modules/caddyhttp/templates/tplcontext.go +++ b/modules/caddyhttp/templates/tplcontext.go @@ -103,13 +103,11 @@ func (c TemplateContext) OriginalReq() http.Request { // trusted files. If it is not trusted, be sure to use escaping functions // in your template. func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) { - bodyBuf := bufPool.Get().(*bytes.Buffer) bodyBuf.Reset() defer bufPool.Put(bodyBuf) err := c.readFileToBuffer(filename, bodyBuf) - if err != nil { return "", err } @@ -215,7 +213,6 @@ func (c TemplateContext) funcHTTPInclude(uri string) (string, error) { // {{ template }} from the standard template library. If the imported file has // no {{ define }} blocks, the name of the import will be the path func (c *TemplateContext) funcImport(filename string) (string, error) { - bodyBuf := bufPool.Get().(*bytes.Buffer) bodyBuf.Reset() defer bufPool.Put(bodyBuf) diff --git a/modules/caddypki/acmeserver/acmeserver.go b/modules/caddypki/acmeserver/acmeserver.go index 0f739ec319c..454720bf36a 100644 --- a/modules/caddypki/acmeserver/acmeserver.go +++ b/modules/caddypki/acmeserver/acmeserver.go @@ -239,7 +239,7 @@ func (ash Handler) openDatabase() (*db.AuthDB, error) { dbFolder := filepath.Join(caddy.AppDataDir(), "acme_server", key) dbPath := filepath.Join(dbFolder, "db") - err := os.MkdirAll(dbFolder, 0755) + err := os.MkdirAll(dbFolder, 0o755) if err != nil { return nil, fmt.Errorf("making folder for CA database: %v", err) } @@ -310,8 +310,10 @@ func (c resolverClient) LookupTxt(name string) ([]string, error) { const defaultPathPrefix = "/acme/" -var keyCleaner = regexp.MustCompile(`[^\w.-_]`) -var databasePool = caddy.NewUsagePool() +var ( + keyCleaner = regexp.MustCompile(`[^\w.-_]`) + databasePool = caddy.NewUsagePool() +) type databaseCloser struct { DB *db.AuthDB diff --git a/modules/caddypki/ca.go b/modules/caddypki/ca.go index 1ba08900a94..d52fc5f360f 100644 --- a/modules/caddypki/ca.go +++ b/modules/caddypki/ca.go @@ -376,15 +376,19 @@ func (ca CA) genIntermediate(rootCert *x509.Certificate, rootKey crypto.Signer) func (ca CA) storageKeyCAPrefix() string { return path.Join("pki", "authorities", certmagic.StorageKeys.Safe(ca.ID)) } + func (ca CA) storageKeyRootCert() string { return path.Join(ca.storageKeyCAPrefix(), "root.crt") } + func (ca CA) storageKeyRootKey() string { return path.Join(ca.storageKeyCAPrefix(), "root.key") } + func (ca CA) storageKeyIntermediateCert() string { return path.Join(ca.storageKeyCAPrefix(), "intermediate.crt") } + func (ca CA) storageKeyIntermediateKey() string { return path.Join(ca.storageKeyCAPrefix(), "intermediate.key") } diff --git a/modules/caddytls/connpolicy.go b/modules/caddytls/connpolicy.go index a4dc4119d96..74c83241107 100644 --- a/modules/caddytls/connpolicy.go +++ b/modules/caddytls/connpolicy.go @@ -316,7 +316,7 @@ func (p *ConnectionPolicy) buildStandardTLSConfig(ctx caddy.Context) error { return err } logFile, _, err := secretsLogPool.LoadOrNew(filename, func() (caddy.Destructor, error) { - w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) + w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) return destructableWriter{w}, err }) if err != nil { diff --git a/modules/logging/filewriter.go b/modules/logging/filewriter.go index f902a6db374..afc4afccd97 100644 --- a/modules/logging/filewriter.go +++ b/modules/logging/filewriter.go @@ -126,7 +126,7 @@ func (fw FileWriter) OpenWriter() (io.WriteCloser, error) { } // otherwise just open a regular file - return os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) + return os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: diff --git a/modules/logging/filters.go b/modules/logging/filters.go index 8cc84c73a50..af9be745b0f 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -81,8 +81,7 @@ func hash(s string) string { // of the SHA-256 hash of the content. Operates // on string fields, or on arrays of strings // where each string is hashed. -type HashFilter struct { -} +type HashFilter struct{} // CaddyModule returns the Caddy module information. func (HashFilter) CaddyModule() caddy.ModuleInfo { diff --git a/replacer.go b/replacer.go index 16d50ac2a7c..817bcfe3480 100644 --- a/replacer.go +++ b/replacer.go @@ -131,7 +131,8 @@ func (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error) func (r *Replacer) replace(input, empty string, treatUnknownAsEmpty, errOnEmpty, errOnUnknown bool, - f ReplacementFunc) (string, error) { + f ReplacementFunc, +) (string, error) { if !strings.Contains(input, string(phOpen)) { return input, nil } From 00c54449b4e7be40ac165f06c9c4b76ab2db006c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 14:25:17 +0800 Subject: [PATCH 02/31] use gci to format imports --- .golangci.yml | 1 + caddytest/caddytest.go | 1 - cmd/caddy/main.go | 1 - modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go | 3 +-- modules/metrics/metrics.go | 4 +--- 5 files changed, 3 insertions(+), 7 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 1dc305e0bf3..cdfe3ff3287 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,6 +8,7 @@ linters: enable: - bodyclose - errcheck + - gci - gofumpt - gosec - gosimple diff --git a/caddytest/caddytest.go b/caddytest/caddytest.go index 49665480485..742c48629d1 100644 --- a/caddytest/caddytest.go +++ b/caddytest/caddytest.go @@ -24,7 +24,6 @@ import ( "github.com/aryann/difflib" "github.com/caddyserver/caddy/v2/caddyconfig" caddycmd "github.com/caddyserver/caddy/v2/cmd" - // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" ) diff --git a/cmd/caddy/main.go b/cmd/caddy/main.go index 48fa149aa08..425b8954f95 100644 --- a/cmd/caddy/main.go +++ b/cmd/caddy/main.go @@ -30,7 +30,6 @@ package main import ( caddycmd "github.com/caddyserver/caddy/v2/cmd" - // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" ) diff --git a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go index f150edc9c05..4560cc144fd 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go @@ -24,13 +24,12 @@ import ( "strings" "time" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" "github.com/caddyserver/caddy/v2/modules/caddytls" "go.uber.org/zap" "go.uber.org/zap/zapcore" - - "github.com/caddyserver/caddy/v2" ) var noopLogger = zap.NewNop() diff --git a/modules/metrics/metrics.go b/modules/metrics/metrics.go index d4ad977987f..e832737af0f 100644 --- a/modules/metrics/metrics.go +++ b/modules/metrics/metrics.go @@ -21,11 +21,9 @@ import ( "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - - "go.uber.org/zap" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "go.uber.org/zap" ) func init() { From b6a44e8a8ed41c1c3cd7dcdc795f5a694937b5ed Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 14:27:13 +0800 Subject: [PATCH 03/31] lint tests, too --- .golangci.yml | 2 +- caddyconfig/caddyfile/dispenser_test.go | 2 +- caddyconfig/caddyfile/parse_test.go | 18 +-- caddyconfig/httpcaddyfile/directives_test.go | 9 +- caddytest/integration/caddyfile_test.go | 5 - caddytest/integration/reverseproxy_test.go | 1 - caddytest/integration/sni_test.go | 2 - caddytest/integration/stream_test.go | 1 - modules/caddyhttp/encode/encode_test.go | 2 - modules/caddyhttp/fileserver/matcher_test.go | 136 +++++++++--------- modules/caddyhttp/matchers_test.go | 2 +- modules/caddyhttp/reverseproxy/ascii_test.go | 4 +- .../reverseproxy/fastcgi/client_test.go | 12 +- .../reverseproxy/selectionpolicies_test.go | 3 +- modules/caddyhttp/rewrite/rewrite_test.go | 2 +- .../caddyhttp/templates/tplcontext_test.go | 7 +- .../caddyhttp/tracing/tracerprovider_test.go | 1 - 17 files changed, 95 insertions(+), 114 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index cdfe3ff3287..fd51c084ddd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -66,7 +66,7 @@ run: # concurrency: 4 # explicitly omit this value to fully utilize available resources. deadline: 5m issues-exit-code: 1 - tests: false + tests: true # output configuration options output: diff --git a/caddyconfig/caddyfile/dispenser_test.go b/caddyconfig/caddyfile/dispenser_test.go index b64a97354d4..0f6ee5043f4 100644 --- a/caddyconfig/caddyfile/dispenser_test.go +++ b/caddyconfig/caddyfile/dispenser_test.go @@ -305,7 +305,7 @@ func TestDispenser_ArgErr_Err(t *testing.T) { t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err) } - var ErrBarIsFull = errors.New("bar is full") + ErrBarIsFull := errors.New("bar is full") bookingError := d.Errf("unable to reserve: %w", ErrBarIsFull) if !errors.Is(bookingError, ErrBarIsFull) { t.Errorf("Errf(): should be able to unwrap the error chain") diff --git a/caddyconfig/caddyfile/parse_test.go b/caddyconfig/caddyfile/parse_test.go index b1104edf943..be8726a024e 100644 --- a/caddyconfig/caddyfile/parse_test.go +++ b/caddyconfig/caddyfile/parse_test.go @@ -22,7 +22,7 @@ import ( ) func TestParseVariadic(t *testing.T) { - var args = make([]string, 10) + args := make([]string, 10) for i, tc := range []struct { input string result bool @@ -107,7 +107,6 @@ func TestAllTokens(t *testing.T) { input := []byte("a b c\nd e") expected := []string{"a", "b", "c", "d", "e"} tokens, err := allTokens("TestAllTokens", input) - if err != nil { t.Fatalf("Expected no error, got %v", err) } @@ -145,10 +144,11 @@ func TestParseOneAndImport(t *testing.T) { "localhost", }, []int{1}}, - {`localhost:1234 + { + `localhost:1234 dir1 foo bar`, false, []string{ - "localhost:1234", - }, []int{3}, + "localhost:1234", + }, []int{3}, }, {`localhost { @@ -403,13 +403,13 @@ func TestRecursiveImport(t *testing.T) { err = os.WriteFile(recursiveFile1, []byte( `localhost dir1 - import recursive_import_test2`), 0644) + import recursive_import_test2`), 0o644) if err != nil { t.Fatal(err) } defer os.Remove(recursiveFile1) - err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0644) + err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0o644) if err != nil { t.Fatal(err) } @@ -437,7 +437,7 @@ func TestRecursiveImport(t *testing.T) { err = os.WriteFile(recursiveFile1, []byte( `localhost dir1 - import `+recursiveFile2), 0644) + import `+recursiveFile2), 0o644) if err != nil { t.Fatal(err) } @@ -491,7 +491,7 @@ func TestDirectiveImport(t *testing.T) { } err = os.WriteFile(directiveFile, []byte(`prop1 1 - prop2 2`), 0644) + prop2 2`), 0o644) if err != nil { t.Fatal(err) } diff --git a/caddyconfig/httpcaddyfile/directives_test.go b/caddyconfig/httpcaddyfile/directives_test.go index e46a6d2af7b..db028229950 100644 --- a/caddyconfig/httpcaddyfile/directives_test.go +++ b/caddyconfig/httpcaddyfile/directives_test.go @@ -31,20 +31,23 @@ func TestHostsFromKeys(t *testing.T) { []Address{ {Original: ":2015", Port: "2015"}, }, - []string{}, []string{}, + []string{}, + []string{}, }, { []Address{ {Original: ":443", Port: "443"}, }, - []string{}, []string{}, + []string{}, + []string{}, }, { []Address{ {Original: "foo", Host: "foo"}, {Original: ":2015", Port: "2015"}, }, - []string{}, []string{"foo"}, + []string{}, + []string{"foo"}, }, { []Address{ diff --git a/caddytest/integration/caddyfile_test.go b/caddytest/integration/caddyfile_test.go index 3f3ba0ae2a7..2eae704e2e1 100644 --- a/caddytest/integration/caddyfile_test.go +++ b/caddytest/integration/caddyfile_test.go @@ -9,7 +9,6 @@ import ( ) func TestRespond(t *testing.T) { - // arrange tester := caddytest.NewTester(t) tester.InitServer(` @@ -32,7 +31,6 @@ func TestRespond(t *testing.T) { } func TestRedirect(t *testing.T) { - // arrange tester := caddytest.NewTester(t) tester.InitServer(` @@ -61,7 +59,6 @@ func TestRedirect(t *testing.T) { } func TestDuplicateHosts(t *testing.T) { - // act and assert caddytest.AssertLoadError(t, ` @@ -76,7 +73,6 @@ func TestDuplicateHosts(t *testing.T) { } func TestReadCookie(t *testing.T) { - localhost, _ := url.Parse("http://localhost") cookie := http.Cookie{ Name: "clientname", @@ -110,7 +106,6 @@ func TestReadCookie(t *testing.T) { } func TestReplIndex(t *testing.T) { - tester := caddytest.NewTester(t) tester.InitServer(` { diff --git a/caddytest/integration/reverseproxy_test.go b/caddytest/integration/reverseproxy_test.go index 4f4261b87d0..0beb71afcac 100644 --- a/caddytest/integration/reverseproxy_test.go +++ b/caddytest/integration/reverseproxy_test.go @@ -57,7 +57,6 @@ func TestSRVReverseProxy(t *testing.T) { } func TestDialWithPlaceholderUnix(t *testing.T) { - if runtime.GOOS == "windows" { t.SkipNow() } diff --git a/caddytest/integration/sni_test.go b/caddytest/integration/sni_test.go index 24dddc59afe..188f9354135 100644 --- a/caddytest/integration/sni_test.go +++ b/caddytest/integration/sni_test.go @@ -7,7 +7,6 @@ import ( ) func TestDefaultSNI(t *testing.T) { - // arrange tester := caddytest.NewTester(t) tester.InitServer(`{ @@ -107,7 +106,6 @@ func TestDefaultSNI(t *testing.T) { } func TestDefaultSNIWithNamedHostAndExplicitIP(t *testing.T) { - // arrange tester := caddytest.NewTester(t) tester.InitServer(` diff --git a/caddytest/integration/stream_test.go b/caddytest/integration/stream_test.go index 6bc612d3695..ef3ea498d33 100644 --- a/caddytest/integration/stream_test.go +++ b/caddytest/integration/stream_test.go @@ -360,7 +360,6 @@ func TestH2ToH1ChunkedResponse(t *testing.T) { func testH2ToH1ChunkedResponseServeH1(t *testing.T) *http.Server { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Host != "127.0.0.1:9443" { t.Errorf("r.Host doesn't match, %v!", r.Host) w.WriteHeader(http.StatusNotFound) diff --git a/modules/caddyhttp/encode/encode_test.go b/modules/caddyhttp/encode/encode_test.go index 3374ee3b5c0..d76945498dd 100644 --- a/modules/caddyhttp/encode/encode_test.go +++ b/modules/caddyhttp/encode/encode_test.go @@ -105,7 +105,6 @@ func TestPreferOrder(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { - if test.accept == "" { r.Header.Del("Accept-Encoding") } else { @@ -258,7 +257,6 @@ func TestValidate(t *testing.T) { t.Errorf("Validate() error = %v, wantErr = %v", err, test.wantErr) } }) - } } diff --git a/modules/caddyhttp/fileserver/matcher_test.go b/modules/caddyhttp/fileserver/matcher_test.go index bab34cc63e9..3daaa8fc5e6 100644 --- a/modules/caddyhttp/fileserver/matcher_test.go +++ b/modules/caddyhttp/fileserver/matcher_test.go @@ -276,83 +276,81 @@ func TestFirstSplit(t *testing.T) { } } -var ( - expressionTests = []struct { - name string - expression *caddyhttp.MatchExpression - urlTarget string - httpMethod string - httpHeader *http.Header - wantErr bool - wantResult bool - clientCertificate []byte - }{ - { - name: "file error no args (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file()`, - }, - urlTarget: "https://example.com/foo.txt", - wantResult: true, +var expressionTests = []struct { + name string + expression *caddyhttp.MatchExpression + urlTarget string + httpMethod string + httpHeader *http.Header + wantErr bool + wantResult bool + clientCertificate []byte +}{ + { + name: "file error no args (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file()`, }, - { - name: "file error bad try files (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file({"try_file": ["bad_arg"]})`, - }, - urlTarget: "https://example.com/foo", - wantErr: true, + urlTarget: "https://example.com/foo.txt", + wantResult: true, + }, + { + name: "file error bad try files (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file({"try_file": ["bad_arg"]})`, }, - { - name: "file match short pattern index.php (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file("index.php")`, - }, - urlTarget: "https://example.com/foo", - wantResult: true, + urlTarget: "https://example.com/foo", + wantErr: true, + }, + { + name: "file match short pattern index.php (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file("index.php")`, }, - { - name: "file match short pattern foo.txt (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file({http.request.uri.path})`, - }, - urlTarget: "https://example.com/foo.txt", - wantResult: true, + urlTarget: "https://example.com/foo", + wantResult: true, + }, + { + name: "file match short pattern foo.txt (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file({http.request.uri.path})`, }, - { - name: "file match index.php (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}, "/index.php"]})`, - }, - urlTarget: "https://example.com/foo", - wantResult: true, + urlTarget: "https://example.com/foo.txt", + wantResult: true, + }, + { + name: "file match index.php (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}, "/index.php"]})`, }, - { - name: "file match long pattern foo.txt (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, - }, - urlTarget: "https://example.com/foo.txt", - wantResult: true, + urlTarget: "https://example.com/foo", + wantResult: true, + }, + { + name: "file match long pattern foo.txt (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, }, - { - name: "file match long pattern foo.txt with concatenation (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file({"root": ".", "try_files": ["./testdata" + {http.request.uri.path}]})`, - }, - urlTarget: "https://example.com/foo.txt", - wantResult: true, + urlTarget: "https://example.com/foo.txt", + wantResult: true, + }, + { + name: "file match long pattern foo.txt with concatenation (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file({"root": ".", "try_files": ["./testdata" + {http.request.uri.path}]})`, }, - { - name: "file not match long pattern (MatchFile)", - expression: &caddyhttp.MatchExpression{ - Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, - }, - urlTarget: "https://example.com/nopenope.txt", - wantResult: false, + urlTarget: "https://example.com/foo.txt", + wantResult: true, + }, + { + name: "file not match long pattern (MatchFile)", + expression: &caddyhttp.MatchExpression{ + Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, }, - } -) + urlTarget: "https://example.com/nopenope.txt", + wantResult: false, + }, +} func TestMatchExpressionMatch(t *testing.T) { for _, tst := range expressionTests { diff --git a/modules/caddyhttp/matchers_test.go b/modules/caddyhttp/matchers_test.go index 041975d80b5..100813096b6 100644 --- a/modules/caddyhttp/matchers_test.go +++ b/modules/caddyhttp/matchers_test.go @@ -862,7 +862,6 @@ func TestHeaderREMatcher(t *testing.T) { } func BenchmarkHeaderREMatcher(b *testing.B) { - i := 0 match := MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}} input := http.Header{"Field": []string{"foobar"}} @@ -1086,6 +1085,7 @@ func TestNotMatcher(t *testing.T) { } } } + func BenchmarkLargeHostMatcher(b *testing.B) { // this benchmark simulates a large host matcher (thousands of entries) where each // value is an exact hostname (not a placeholder or wildcard) - compare the results diff --git a/modules/caddyhttp/reverseproxy/ascii_test.go b/modules/caddyhttp/reverseproxy/ascii_test.go index d1f0c1da903..de67963bd7c 100644 --- a/modules/caddyhttp/reverseproxy/ascii_test.go +++ b/modules/caddyhttp/reverseproxy/ascii_test.go @@ -26,7 +26,7 @@ package reverseproxy import "testing" func TestEqualFold(t *testing.T) { - var tests = []struct { + tests := []struct { name string a, b string want bool @@ -64,7 +64,7 @@ func TestEqualFold(t *testing.T) { } func TestIsPrint(t *testing.T) { - var tests = []struct { + tests := []struct { name string in string want bool diff --git a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go index 29bb5785b18..a2227a65332 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go @@ -48,7 +48,7 @@ import ( // and output "FAILED" in response const ( scriptFile = "/tank/www/fcgic_test.php" - //ipPort = "remote-php-serv:59000" + // ipPort = "remote-php-serv:59000" ipPort = "127.0.0.1:59000" ) @@ -57,7 +57,6 @@ var globalt *testing.T type FastCGIServer struct{} func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { - if err := req.ParseMultipartForm(100000000); err != nil { log.Printf("[ERROR] failed to parse: %v", err) } @@ -84,7 +83,7 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { if req.MultipartForm != nil { fileNum = len(req.MultipartForm.File) for kn, fns := range req.MultipartForm.File { - //fmt.Fprintln(resp, "server:filekey ", kn ) + // fmt.Fprintln(resp, "server:filekey ", kn ) length += len(kn) for _, f := range fns { fd, err := f.Open() @@ -101,13 +100,13 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { length += int(l0) defer fd.Close() md5 := fmt.Sprintf("%x", h.Sum(nil)) - //fmt.Fprintln(resp, "server:filemd5 ", md5 ) + // fmt.Fprintln(resp, "server:filemd5 ", md5 ) if kn != md5 { fmt.Fprintln(resp, "server:err ", md5, kn) stat = "FAILED" } - //fmt.Fprintln(resp, "server:filename ", f.Filename ) + // fmt.Fprintln(resp, "server:filename ", f.Filename ) } } } @@ -181,7 +180,6 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ } func generateRandFile(size int) (p string, m string) { - p = filepath.Join(os.TempDir(), "fcgict"+strconv.Itoa(rand.Int())) // open output file @@ -236,7 +234,7 @@ func DisabledTest(t *testing.T) { fcgiParams := make(map[string]string) fcgiParams["REQUEST_METHOD"] = "GET" fcgiParams["SERVER_PROTOCOL"] = "HTTP/1.1" - //fcgi_params["GATEWAY_INTERFACE"] = "CGI/1.1" + // fcgi_params["GATEWAY_INTERFACE"] = "CGI/1.1" fcgiParams["SCRIPT_FILENAME"] = scriptFile // simple GET diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies_test.go b/modules/caddyhttp/reverseproxy/selectionpolicies_test.go index dc613a53896..62e6548b931 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies_test.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies_test.go @@ -120,7 +120,7 @@ func TestWeightedRoundRobinPolicy(t *testing.T) { h = wrrPolicy.Select(pool, req, nil) if h != pool[0] { - t.Error("Expected to select first host on availablity.") + t.Error("Expected to select first host on availability.") } // mark host as full pool[1].countRequest(1) @@ -629,7 +629,6 @@ func TestRandomChoicePolicy(t *testing.T) { if h == pool[0] { t.Error("RandomChoicePolicy should not choose pool[0]") } - } func TestCookieHashPolicy(t *testing.T) { diff --git a/modules/caddyhttp/rewrite/rewrite_test.go b/modules/caddyhttp/rewrite/rewrite_test.go index bb937ec5bad..aaa142bc23e 100644 --- a/modules/caddyhttp/rewrite/rewrite_test.go +++ b/modules/caddyhttp/rewrite/rewrite_test.go @@ -333,7 +333,7 @@ func TestRewrite(t *testing.T) { input: newRequest(t, "GET", "/foo/findme%2Fbar"), expect: newRequest(t, "GET", "/foo/replaced%2Fbar"), }, - + { rule: Rewrite{PathRegexp: []*regexReplacer{{Find: "/{2,}", Replace: "/"}}}, input: newRequest(t, "GET", "/foo//bar///baz?a=b//c"), diff --git a/modules/caddyhttp/templates/tplcontext_test.go b/modules/caddyhttp/templates/tplcontext_test.go index fdf2c1065b6..6b8d2a7b18d 100644 --- a/modules/caddyhttp/templates/tplcontext_test.go +++ b/modules/caddyhttp/templates/tplcontext_test.go @@ -30,8 +30,7 @@ import ( "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) -type handle struct { -} +type handle struct{} func (h *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Accept-Encoding") == "identity" { @@ -176,7 +175,6 @@ func TestImport(t *testing.T) { } else if !templateWasDefined && actual != "" { // template should be defined, return value should be an empty string t.Errorf("Test %d: Expected template %s to be define but got %s", i, test.expect, tplContext.tpl.DefinedTemplates()) - } if absFilePath != "" { @@ -255,7 +253,6 @@ func TestNestedInclude(t *testing.T) { } else if buf.String() != test.expect { // t.Errorf("Test %d: Expected '%s' but got '%s'", i, test.expect, buf.String()) - } if absFilePath != "" { @@ -342,7 +339,6 @@ func TestInclude(t *testing.T) { t.Errorf("Test %d: Expected error but had none", i) } else if actual != test.expect { t.Errorf("Test %d: Expected %s but got %s", i, test.expect, actual) - } if absFilePath != "" { @@ -602,7 +598,6 @@ title = "Welcome" t.Errorf("Test %d: Expected body %s, found %s. Input was SplitFrontMatter(%s)", i, test.body, result.Body, test.input) } } - } func TestHumanize(t *testing.T) { diff --git a/modules/caddyhttp/tracing/tracerprovider_test.go b/modules/caddyhttp/tracing/tracerprovider_test.go index cb2e5936f9a..5a5df0a23f2 100644 --- a/modules/caddyhttp/tracing/tracerprovider_test.go +++ b/modules/caddyhttp/tracing/tracerprovider_test.go @@ -28,7 +28,6 @@ func Test_tracersProvider_cleanupTracerProvider(t *testing.T) { tp.getTracerProvider() err := tp.cleanupTracerProvider(zap.NewNop()) - if err != nil { t.Errorf("There should be no error: %v", err) } From 74cc70f7ee661d08bac4009a4fdb3044a09dbabc Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 14:41:18 +0800 Subject: [PATCH 04/31] naked return checks --- .github/dependabot.yml | 10 +++++++--- .golangci.yml | 12 +++++------ caddy.go | 6 +++--- caddyconfig/caddyfile/formatter_test.go | 2 +- cmd/packagesfuncs.go | 4 ++-- modules/caddyhttp/fileserver/matcher.go | 4 ++-- .../caddyhttp/reverseproxy/fastcgi/client.go | 20 +++++++++---------- .../reverseproxy/fastcgi/client_test.go | 6 +++--- modules/logging/netwriter.go | 8 ++++---- usagepool.go | 2 +- 10 files changed, 39 insertions(+), 35 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 64284b90748..13eb3e01e96 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,7 +1,11 @@ --- version: 2 updates: - - package-ecosystem: "github-actions" - directory: "/" + - package-ecosystem: 'github-actions' + directory: '/' schedule: - interval: "monthly" + interval: 'weekly' + - package-ecosystem: 'gomod' + directory: '/' + schedule: + interval: 'weekly' diff --git a/.golangci.yml b/.golangci.yml index fd51c084ddd..2b64a440788 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,6 +14,7 @@ linters: - gosimple - govet - ineffassign + - nakedret - misspell - prealloc - staticcheck @@ -38,7 +39,6 @@ linters: # - godot # - godox # - goerr113 - # - gofumpt # - goheader # - golint # - gomnd @@ -77,23 +77,23 @@ output: issues: exclude-rules: # we aren't calling unknown URL - - text: "G107" # G107: Url provided to HTTP request as taint input + - text: 'G107' # G107: Url provided to HTTP request as taint input linters: - gosec # as a web server that's expected to handle any template, this is totally in the hands of the user. - - text: "G203" # G203: Use of unescaped data in HTML templates + - text: 'G203' # G203: Use of unescaped data in HTML templates linters: - gosec # we're shelling out to known commands, not relying on user-defined input. - - text: "G204" # G204: Audit use of command execution + - text: 'G204' # G204: Audit use of command execution linters: - gosec # the choice of weakrand is deliberate, hence the named import "weakrand" - path: modules/caddyhttp/reverseproxy/selectionpolicies.go - text: "G404" # G404: Insecure random number source (rand) + text: 'G404' # G404: Insecure random number source (rand) linters: - gosec - path: modules/caddyhttp/reverseproxy/streaming.go - text: "G404" # G404: Insecure random number source (rand) + text: 'G404' # G404: Insecure random number source (rand) linters: - gosec diff --git a/caddy.go b/caddy.go index fac965e96cc..de8413eafa7 100644 --- a/caddy.go +++ b/caddy.go @@ -883,11 +883,11 @@ func Version() (simple, full string) { if CustomVersion != "" { full = CustomVersion simple = CustomVersion - return + return full, simple } full = "unknown" simple = "unknown" - return + return full, simple } // find the Caddy module in the dependency list for _, dep := range bi.Deps { @@ -967,7 +967,7 @@ func Version() (simple, full string) { } } - return + return simple, full } // ActiveContext returns the currently-active context. diff --git a/caddyconfig/caddyfile/formatter_test.go b/caddyconfig/caddyfile/formatter_test.go index 8e5b3686069..d7bbb7ca543 100644 --- a/caddyconfig/caddyfile/formatter_test.go +++ b/caddyconfig/caddyfile/formatter_test.go @@ -375,7 +375,7 @@ block { if string(actual) != tc.expect { t.Errorf("\n[TEST %d: %s]\n====== EXPECTED ======\n%s\n====== ACTUAL ======\n%s^^^^^^^^^^^^^^^^^^^^^", - i, tc.description, string(tc.expect), string(actual)) + i, tc.description, tc.expect, string(actual)) } } } diff --git a/cmd/packagesfuncs.go b/cmd/packagesfuncs.go index 3aed0e8c840..8bf4a83ec73 100644 --- a/cmd/packagesfuncs.go +++ b/cmd/packagesfuncs.go @@ -178,7 +178,7 @@ func getModules() (standard, nonstandard, unknown []moduleInfo, err error) { bi, ok := debug.ReadBuildInfo() if !ok { err = fmt.Errorf("no build info") - return + return standard, nonstandard, unknown, err } for _, modID := range caddy.Modules() { @@ -221,7 +221,7 @@ func getModules() (standard, nonstandard, unknown []moduleInfo, err error) { nonstandard = append(nonstandard, caddyModGoMod) } } - return + return standard, nonstandard, unknown, nil } func listModules(path string) error { diff --git a/modules/caddyhttp/fileserver/matcher.go b/modules/caddyhttp/fileserver/matcher.go index f42445fbf3d..1daa5dd09c2 100644 --- a/modules/caddyhttp/fileserver/matcher.go +++ b/modules/caddyhttp/fileserver/matcher.go @@ -405,7 +405,7 @@ func (m MatchFile) selectFile(r *http.Request) (matched bool) { for _, pattern := range m.TryFiles { if err := parseErrorCode(pattern); err != nil { caddyhttp.SetVar(r.Context(), caddyhttp.MatcherErrorVarKey, err) - return + return false } candidates := makeCandidates(pattern) for _, c := range candidates { @@ -479,7 +479,7 @@ func (m MatchFile) selectFile(r *http.Request) (matched bool) { return true } - return + return false } // parseErrorCode checks if the input is a status diff --git a/modules/caddyhttp/reverseproxy/fastcgi/client.go b/modules/caddyhttp/reverseproxy/fastcgi/client.go index 04513dd85f3..d9530397e37 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/client.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/client.go @@ -142,13 +142,13 @@ func (c *client) Do(p map[string]string, req io.Reader) (r io.Reader, err error) err = writer.writeBeginRequest(uint16(Responder), 0) if err != nil { - return + return nil, err } writer.recType = Params err = writer.writePairs(p) if err != nil { - return + return nil, err } writer.recType = Stdin @@ -164,7 +164,7 @@ func (c *client) Do(p map[string]string, req io.Reader) (r io.Reader, err error) } r = &streamReader{c: c} - return + return r, nil } // clientCloser is a io.ReadCloser. It wraps a io.Reader with a Closer @@ -198,7 +198,7 @@ func (f clientCloser) Close() error { func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) { r, err := c.Do(p, req) if err != nil { - return + return nil, err } rb := bufio.NewReader(r) @@ -208,7 +208,7 @@ func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Respons // Parse the response headers. mimeHeader, err := tp.ReadMIMEHeader() if err != nil && err != io.EOF { - return + return nil, err } resp.Header = http.Header(mimeHeader) @@ -216,7 +216,7 @@ func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Respons statusNumber, statusInfo, statusIsCut := strings.Cut(resp.Header.Get("Status"), " ") resp.StatusCode, err = strconv.Atoi(statusNumber) if err != nil { - return + return nil, err } if statusIsCut { resp.Status = statusInfo @@ -246,7 +246,7 @@ func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Respons } resp.Body = closer - return + return resp, nil } // Get issues a GET request to the fcgi responder. @@ -315,7 +315,7 @@ func (c *client) PostFile(p map[string]string, data url.Values, file map[string] for _, v0 := range val { err = writer.WriteField(key, v0) if err != nil { - return + return nil, err } } } @@ -333,13 +333,13 @@ func (c *client) PostFile(p map[string]string, data url.Values, file map[string] } _, err = io.Copy(part, fd) if err != nil { - return + return nil, err } } err = writer.Close() if err != nil { - return + return nil, err } return c.Post(p, "POST", bodyType, buf, int64(buf.Len())) diff --git a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go index a2227a65332..5568a49c468 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go @@ -120,7 +120,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ conn, err := net.Dial("tcp", ipPort) if err != nil { log.Println("err:", err) - return + return nil } fcgi := client{rwc: conn, reqID: 1} @@ -162,7 +162,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ if err != nil { log.Println("err:", err) - return + return nil } defer resp.Body.Close() @@ -176,7 +176,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ globalt.Error("Server return failed message") } - return + return content } func generateRandFile(size int) (p string, m string) { diff --git a/modules/logging/netwriter.go b/modules/logging/netwriter.go index 1939cb711dc..65f9c1ab1c7 100644 --- a/modules/logging/netwriter.go +++ b/modules/logging/netwriter.go @@ -170,7 +170,7 @@ func (reconn *redialerConn) Write(b []byte) (n int, err error) { reconn.connMu.RUnlock() if conn != nil { if n, err = conn.Write(b); err == nil { - return + return n, nil } } @@ -182,7 +182,7 @@ func (reconn *redialerConn) Write(b []byte) (n int, err error) { // one of them might have already re-dialed by now; try writing again if reconn.Conn != nil { if n, err = reconn.Conn.Write(b); err == nil { - return + return n, nil } } @@ -196,7 +196,7 @@ func (reconn *redialerConn) Write(b []byte) (n int, err error) { if err2 != nil { // logger socket still offline; instead of discarding the log, dump it to stderr os.Stderr.Write(b) - return + return 0, err2 } if n, err = conn2.Write(b); err == nil { if reconn.Conn != nil { @@ -209,7 +209,7 @@ func (reconn *redialerConn) Write(b []byte) (n int, err error) { os.Stderr.Write(b) } - return + return n, err } func (reconn *redialerConn) dial() (net.Conn, error) { diff --git a/usagepool.go b/usagepool.go index 7007849fb95..ea37b07f61e 100644 --- a/usagepool.go +++ b/usagepool.go @@ -106,7 +106,7 @@ func (up *UsagePool) LoadOrNew(key any, construct Constructor) (value any, loade } upv.Unlock() } - return + return value, loaded, err } // LoadOrStore loads the value associated with key from the pool if it From 6d529e354dafd52fab11beb80aeb1fbd971a3470 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 16:55:23 +0800 Subject: [PATCH 05/31] continue linting tests --- caddyconfig/caddyfile/parse_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/caddyconfig/caddyfile/parse_test.go b/caddyconfig/caddyfile/parse_test.go index be8726a024e..c4b8c1b9067 100644 --- a/caddyconfig/caddyfile/parse_test.go +++ b/caddyconfig/caddyfile/parse_test.go @@ -403,13 +403,13 @@ func TestRecursiveImport(t *testing.T) { err = os.WriteFile(recursiveFile1, []byte( `localhost dir1 - import recursive_import_test2`), 0o644) + import recursive_import_test2`), 0o600) if err != nil { t.Fatal(err) } defer os.Remove(recursiveFile1) - err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0o644) + err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0o600) if err != nil { t.Fatal(err) } From 84504d39cfa421366ef1e061cfb0e90f158ce21f Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 16:58:43 +0800 Subject: [PATCH 06/31] reconfigure gci --- .golangci.yml | 23 +++++++++++++++---- caddy.go | 3 ++- caddyconfig/caddyfile/importargs.go | 3 ++- caddyconfig/caddyfile/parse.go | 3 ++- caddyconfig/httpcaddyfile/addresses.go | 3 ++- caddyconfig/httpcaddyfile/builtins.go | 7 +++--- caddyconfig/httpcaddyfile/httptype.go | 5 ++-- caddyconfig/httpcaddyfile/options.go | 5 ++-- caddyconfig/httpcaddyfile/serveroptions.go | 3 ++- caddyconfig/httpcaddyfile/tlsapp.go | 5 ++-- caddytest/caddytest.go | 4 +++- cmd/caddy/main.go | 1 + cmd/commandfuncs.go | 3 ++- cmd/commands.go | 3 ++- cmd/main.go | 5 ++-- cmd/packagesfuncs.go | 3 ++- cmd/storagefuncs.go | 3 ++- listeners.go | 3 ++- metrics.go | 3 ++- modules/caddyevents/app.go | 3 ++- modules/caddyhttp/app.go | 7 +++--- modules/caddyhttp/autohttps.go | 5 ++-- modules/caddyhttp/caddyauth/basicauth.go | 3 ++- modules/caddyhttp/caddyauth/caddyauth.go | 3 ++- modules/caddyhttp/caddyauth/command.go | 6 +++-- modules/caddyhttp/caddyauth/hashes.go | 3 ++- modules/caddyhttp/celmatcher.go | 5 ++-- modules/caddyhttp/encode/gzip/gzip.go | 3 ++- modules/caddyhttp/encode/zstd/zstd.go | 3 ++- modules/caddyhttp/fileserver/browse.go | 3 ++- .../caddyhttp/fileserver/browsetplcontext.go | 5 ++-- modules/caddyhttp/fileserver/command.go | 10 ++++---- modules/caddyhttp/fileserver/matcher.go | 7 +++--- modules/caddyhttp/fileserver/staticfiles.go | 3 ++- modules/caddyhttp/ip_matchers.go | 5 ++-- modules/caddyhttp/logging.go | 3 ++- modules/caddyhttp/matchers.go | 5 ++-- modules/caddyhttp/metrics.go | 3 ++- .../proxyprotocol/listenerwrapper.go | 3 ++- modules/caddyhttp/push/handler.go | 3 ++- modules/caddyhttp/replacer.go | 3 ++- modules/caddyhttp/requestbody/caddyfile.go | 3 ++- modules/caddyhttp/reverseproxy/caddyfile.go | 3 ++- modules/caddyhttp/reverseproxy/command.go | 8 ++++--- .../caddyhttp/reverseproxy/fastcgi/fastcgi.go | 5 ++-- .../caddyhttp/reverseproxy/healthchecks.go | 3 ++- .../caddyhttp/reverseproxy/httptransport.go | 7 +++--- .../caddyhttp/reverseproxy/reverseproxy.go | 5 ++-- modules/caddyhttp/reverseproxy/upstreams.go | 3 ++- modules/caddyhttp/rewrite/rewrite.go | 3 ++- modules/caddyhttp/server.go | 7 +++--- modules/caddyhttp/staticresp.go | 8 ++++--- modules/caddyhttp/templates/tplcontext.go | 5 ++-- modules/caddyhttp/tracing/module.go | 3 ++- modules/caddyhttp/tracing/tracer.go | 5 ++-- modules/caddypki/acmeserver/acmeserver.go | 7 +++--- modules/caddypki/adminapi.go | 3 ++- modules/caddypki/ca.go | 3 ++- modules/caddypki/command.go | 6 +++-- modules/caddypki/pki.go | 3 ++- modules/caddytls/acmeissuer.go | 7 +++--- modules/caddytls/automation.go | 3 ++- modules/caddytls/certmanagers.go | 5 ++-- modules/caddytls/connpolicy.go | 3 ++- .../distributedstek/distributedstek.go | 3 ++- modules/caddytls/internalissuer.go | 7 +++--- modules/caddytls/matchers.go | 3 ++- modules/caddytls/storageloader.go | 3 ++- modules/caddytls/tls.go | 5 ++-- modules/caddytls/zerosslissuer.go | 5 ++-- modules/filestorage/filestorage.go | 3 ++- modules/logging/encoders.go | 5 ++-- modules/logging/filewriter.go | 5 ++-- modules/logging/filterencoder.go | 7 +++--- modules/logging/filters.go | 3 ++- modules/metrics/metrics.go | 7 +++--- 76 files changed, 220 insertions(+), 126 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index cdfe3ff3287..daa825ce468 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,6 +2,19 @@ linters-settings: errcheck: ignore: fmt:.*,go.uber.org/zap/zapcore:^Add.* ignoretests: true + gci: + sections: + - prefix(github.com/caddyserver/caddy/v2/cmd) # ensure that this is always at the top and always has a line break. + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/caddyserver/caddy) # Custom section: groups all imports with the specified Prefix. + # Skip generated files. + # Default: true + skip-generated: true + # Enable custom order of sections. + # If `true`, make the section order the same as the order of `sections`. + # Default: false + custom-order: true linters: disable-all: true @@ -77,23 +90,23 @@ output: issues: exclude-rules: # we aren't calling unknown URL - - text: "G107" # G107: Url provided to HTTP request as taint input + - text: 'G107' # G107: Url provided to HTTP request as taint input linters: - gosec # as a web server that's expected to handle any template, this is totally in the hands of the user. - - text: "G203" # G203: Use of unescaped data in HTML templates + - text: 'G203' # G203: Use of unescaped data in HTML templates linters: - gosec # we're shelling out to known commands, not relying on user-defined input. - - text: "G204" # G204: Audit use of command execution + - text: 'G204' # G204: Audit use of command execution linters: - gosec # the choice of weakrand is deliberate, hence the named import "weakrand" - path: modules/caddyhttp/reverseproxy/selectionpolicies.go - text: "G404" # G404: Insecure random number source (rand) + text: 'G404' # G404: Insecure random number source (rand) linters: - gosec - path: modules/caddyhttp/reverseproxy/streaming.go - text: "G404" # G404: Insecure random number source (rand) + text: 'G404' # G404: Insecure random number source (rand) linters: - gosec diff --git a/caddy.go b/caddy.go index fac965e96cc..8e7dce50764 100644 --- a/caddy.go +++ b/caddy.go @@ -34,10 +34,11 @@ import ( "sync/atomic" "time" - "github.com/caddyserver/caddy/v2/notify" "github.com/caddyserver/certmagic" "github.com/google/uuid" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2/notify" ) // Config is the top (or beginning) of the Caddy configuration structure. diff --git a/caddyconfig/caddyfile/importargs.go b/caddyconfig/caddyfile/importargs.go index 54d648e828a..2e21a3652f7 100644 --- a/caddyconfig/caddyfile/importargs.go +++ b/caddyconfig/caddyfile/importargs.go @@ -19,8 +19,9 @@ import ( "strconv" "strings" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) // parseVariadic determines if the token is a variadic placeholder, diff --git a/caddyconfig/caddyfile/parse.go b/caddyconfig/caddyfile/parse.go index 620f0917d86..65d6ee92765 100644 --- a/caddyconfig/caddyfile/parse.go +++ b/caddyconfig/caddyfile/parse.go @@ -22,8 +22,9 @@ import ( "path/filepath" "strings" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) // Parse parses the input just enough to group tokens, in diff --git a/caddyconfig/httpcaddyfile/addresses.go b/caddyconfig/httpcaddyfile/addresses.go index 4f8db3a9b44..b6a8ac07254 100644 --- a/caddyconfig/httpcaddyfile/addresses.go +++ b/caddyconfig/httpcaddyfile/addresses.go @@ -24,10 +24,11 @@ import ( "strings" "unicode" + "github.com/caddyserver/certmagic" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "github.com/caddyserver/certmagic" ) // mapAddressToServerBlocks returns a map of listener address to list of server diff --git a/caddyconfig/httpcaddyfile/builtins.go b/caddyconfig/httpcaddyfile/builtins.go index 5b0c5fb9af6..abd484451a9 100644 --- a/caddyconfig/httpcaddyfile/builtins.go +++ b/caddyconfig/httpcaddyfile/builtins.go @@ -26,14 +26,15 @@ import ( "strings" "time" + "github.com/caddyserver/certmagic" + "github.com/mholt/acmez/acme" + "go.uber.org/zap/zapcore" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddytls" - "github.com/caddyserver/certmagic" - "github.com/mholt/acmez/acme" - "go.uber.org/zap/zapcore" ) func init() { diff --git a/caddyconfig/httpcaddyfile/httptype.go b/caddyconfig/httpcaddyfile/httptype.go index fe7e7ced554..6fa5a9f7c4d 100644 --- a/caddyconfig/httpcaddyfile/httptype.go +++ b/caddyconfig/httpcaddyfile/httptype.go @@ -23,14 +23,15 @@ import ( "strconv" "strings" + "go.uber.org/zap" + "golang.org/x/exp/slices" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddypki" "github.com/caddyserver/caddy/v2/modules/caddytls" - "go.uber.org/zap" - "golang.org/x/exp/slices" ) func init() { diff --git a/caddyconfig/httpcaddyfile/options.go b/caddyconfig/httpcaddyfile/options.go index f9d0b96b498..ba1896b6b84 100644 --- a/caddyconfig/httpcaddyfile/options.go +++ b/caddyconfig/httpcaddyfile/options.go @@ -17,12 +17,13 @@ package httpcaddyfile import ( "strconv" + "github.com/caddyserver/certmagic" + "github.com/mholt/acmez/acme" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddytls" - "github.com/caddyserver/certmagic" - "github.com/mholt/acmez/acme" ) func init() { diff --git a/caddyconfig/httpcaddyfile/serveroptions.go b/caddyconfig/httpcaddyfile/serveroptions.go index 7a71b907476..6d7c6787f37 100644 --- a/caddyconfig/httpcaddyfile/serveroptions.go +++ b/caddyconfig/httpcaddyfile/serveroptions.go @@ -18,11 +18,12 @@ import ( "encoding/json" "fmt" + "github.com/dustin/go-humanize" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "github.com/dustin/go-humanize" ) // serverOptions collects server config overrides parsed from Caddyfile global options diff --git a/caddyconfig/httpcaddyfile/tlsapp.go b/caddyconfig/httpcaddyfile/tlsapp.go index 21427524d8d..927f225df3a 100644 --- a/caddyconfig/httpcaddyfile/tlsapp.go +++ b/caddyconfig/httpcaddyfile/tlsapp.go @@ -23,12 +23,13 @@ import ( "strconv" "strings" + "github.com/caddyserver/certmagic" + "github.com/mholt/acmez/acme" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddytls" - "github.com/caddyserver/certmagic" - "github.com/mholt/acmez/acme" ) func (st ServerType) buildTLSApp( diff --git a/caddytest/caddytest.go b/caddytest/caddytest.go index 742c48629d1..a563a12cde5 100644 --- a/caddytest/caddytest.go +++ b/caddytest/caddytest.go @@ -1,6 +1,8 @@ package caddytest import ( + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "bytes" "context" "crypto/tls" @@ -22,8 +24,8 @@ import ( "time" "github.com/aryann/difflib" + "github.com/caddyserver/caddy/v2/caddyconfig" - caddycmd "github.com/caddyserver/caddy/v2/cmd" // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" ) diff --git a/cmd/caddy/main.go b/cmd/caddy/main.go index 425b8954f95..48fa149aa08 100644 --- a/cmd/caddy/main.go +++ b/cmd/caddy/main.go @@ -30,6 +30,7 @@ package main import ( caddycmd "github.com/caddyserver/caddy/v2/cmd" + // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" ) diff --git a/cmd/commandfuncs.go b/cmd/commandfuncs.go index 837526ed013..11b42a1ff52 100644 --- a/cmd/commandfuncs.go +++ b/cmd/commandfuncs.go @@ -32,11 +32,12 @@ import ( "strings" "github.com/aryann/difflib" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/internal" - "go.uber.org/zap" ) func cmdStart(fl Flags) (int, error) { diff --git a/cmd/commands.go b/cmd/commands.go index 3bf47df4e00..0885577ea3f 100644 --- a/cmd/commands.go +++ b/cmd/commands.go @@ -21,9 +21,10 @@ import ( "regexp" "strings" - "github.com/caddyserver/caddy/v2" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" + + "github.com/caddyserver/caddy/v2" ) // Command represents a subcommand. Name, Func, diff --git a/cmd/main.go b/cmd/main.go index bfbd0bbceb1..c7fb465cbba 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -30,11 +30,12 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/certmagic" "github.com/spf13/pflag" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig" ) func init() { diff --git a/cmd/packagesfuncs.go b/cmd/packagesfuncs.go index 3aed0e8c840..5d77e4d5451 100644 --- a/cmd/packagesfuncs.go +++ b/cmd/packagesfuncs.go @@ -27,8 +27,9 @@ import ( "runtime/debug" "strings" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func cmdUpgrade(fl Flags) (int, error) { diff --git a/cmd/storagefuncs.go b/cmd/storagefuncs.go index a9f1bcac82f..6a6daec7637 100644 --- a/cmd/storagefuncs.go +++ b/cmd/storagefuncs.go @@ -23,8 +23,9 @@ import ( "io" "os" - "github.com/caddyserver/caddy/v2" "github.com/caddyserver/certmagic" + + "github.com/caddyserver/caddy/v2" ) type storVal struct { diff --git a/listeners.go b/listeners.go index 4cd00b21e79..768d977115c 100644 --- a/listeners.go +++ b/listeners.go @@ -31,10 +31,11 @@ import ( "syscall" "time" - "github.com/caddyserver/caddy/v2/internal" "github.com/quic-go/quic-go" "github.com/quic-go/quic-go/http3" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2/internal" ) // NetworkAddress represents one or more network addresses. diff --git a/metrics.go b/metrics.go index eb6c74ff086..0f8ea03cbd6 100644 --- a/metrics.go +++ b/metrics.go @@ -3,10 +3,11 @@ package caddy import ( "net/http" - "github.com/caddyserver/caddy/v2/internal/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/caddyserver/caddy/v2/internal/metrics" ) // define and register the metrics used in this package. diff --git a/modules/caddyevents/app.go b/modules/caddyevents/app.go index 6b10460d38f..1684cfd2a6c 100644 --- a/modules/caddyevents/app.go +++ b/modules/caddyevents/app.go @@ -22,9 +22,10 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" "github.com/google/uuid" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddyhttp/app.go b/modules/caddyhttp/app.go index 944611d3b79..457a5f4d33f 100644 --- a/modules/caddyhttp/app.go +++ b/modules/caddyhttp/app.go @@ -26,12 +26,13 @@ import ( "sync" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyevents" - "github.com/caddyserver/caddy/v2/modules/caddytls" "go.uber.org/zap" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyevents" + "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { diff --git a/modules/caddyhttp/autohttps.go b/modules/caddyhttp/autohttps.go index 39ec135d993..aec43c7c7af 100644 --- a/modules/caddyhttp/autohttps.go +++ b/modules/caddyhttp/autohttps.go @@ -20,10 +20,11 @@ import ( "strconv" "strings" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddytls" "github.com/caddyserver/certmagic" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddytls" ) // AutoHTTPSConfig is used to disable automatic HTTPS diff --git a/modules/caddyhttp/caddyauth/basicauth.go b/modules/caddyhttp/caddyauth/basicauth.go index 6cd38a5773b..f30a8691aeb 100644 --- a/modules/caddyhttp/caddyauth/basicauth.go +++ b/modules/caddyhttp/caddyauth/basicauth.go @@ -24,8 +24,9 @@ import ( "strings" "sync" - "github.com/caddyserver/caddy/v2" "golang.org/x/sync/singleflight" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddyhttp/caddyauth/caddyauth.go b/modules/caddyhttp/caddyauth/caddyauth.go index b2bdbc22f47..c60de880b8b 100644 --- a/modules/caddyhttp/caddyauth/caddyauth.go +++ b/modules/caddyhttp/caddyauth/caddyauth.go @@ -18,9 +18,10 @@ import ( "fmt" "net/http" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/caddyauth/command.go b/modules/caddyhttp/caddyauth/command.go index 915bcd31e07..416849f6472 100644 --- a/modules/caddyhttp/caddyauth/command.go +++ b/modules/caddyhttp/caddyauth/command.go @@ -15,6 +15,8 @@ package caddyauth import ( + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "bufio" "bytes" "encoding/base64" @@ -22,10 +24,10 @@ import ( "os" "os/signal" - "github.com/caddyserver/caddy/v2" - caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/spf13/cobra" "golang.org/x/term" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddyhttp/caddyauth/hashes.go b/modules/caddyhttp/caddyauth/hashes.go index 6a651f0d9e5..324cf1e1ec3 100644 --- a/modules/caddyhttp/caddyauth/hashes.go +++ b/modules/caddyhttp/caddyauth/hashes.go @@ -18,9 +18,10 @@ import ( "crypto/subtle" "encoding/base64" - "github.com/caddyserver/caddy/v2" "golang.org/x/crypto/bcrypt" "golang.org/x/crypto/scrypt" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddyhttp/celmatcher.go b/modules/caddyhttp/celmatcher.go index 1ba61a0528d..e997336ff8a 100644 --- a/modules/caddyhttp/celmatcher.go +++ b/modules/caddyhttp/celmatcher.go @@ -25,8 +25,6 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/google/cel-go/cel" "github.com/google/cel-go/common" "github.com/google/cel-go/common/operators" @@ -39,6 +37,9 @@ import ( "github.com/google/cel-go/parser" "go.uber.org/zap" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/caddyhttp/encode/gzip/gzip.go b/modules/caddyhttp/encode/gzip/gzip.go index 021258317d8..0af38b92776 100644 --- a/modules/caddyhttp/encode/gzip/gzip.go +++ b/modules/caddyhttp/encode/gzip/gzip.go @@ -18,10 +18,11 @@ import ( "fmt" "strconv" + "github.com/klauspost/compress/gzip" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" - "github.com/klauspost/compress/gzip" ) func init() { diff --git a/modules/caddyhttp/encode/zstd/zstd.go b/modules/caddyhttp/encode/zstd/zstd.go index 3da9b13815a..b5a0299d1ae 100644 --- a/modules/caddyhttp/encode/zstd/zstd.go +++ b/modules/caddyhttp/encode/zstd/zstd.go @@ -15,10 +15,11 @@ package caddyzstd import ( + "github.com/klauspost/compress/zstd" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" - "github.com/klauspost/compress/zstd" ) func init() { diff --git a/modules/caddyhttp/fileserver/browse.go b/modules/caddyhttp/fileserver/browse.go index 45b5cb86816..917d14fded5 100644 --- a/modules/caddyhttp/fileserver/browse.go +++ b/modules/caddyhttp/fileserver/browse.go @@ -29,10 +29,11 @@ import ( "sync" "text/template" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" - "go.uber.org/zap" ) //go:embed browse.html diff --git a/modules/caddyhttp/fileserver/browsetplcontext.go b/modules/caddyhttp/fileserver/browsetplcontext.go index e06d0726742..682273c0a20 100644 --- a/modules/caddyhttp/fileserver/browsetplcontext.go +++ b/modules/caddyhttp/fileserver/browsetplcontext.go @@ -25,10 +25,11 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/dustin/go-humanize" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func (fsrv *FileServer) directoryListing(ctx context.Context, entries []fs.DirEntry, canGoUp bool, root, urlPath string, repl *caddy.Replacer) *browseTemplateContext { diff --git a/modules/caddyhttp/fileserver/command.go b/modules/caddyhttp/fileserver/command.go index bccaf2f8e9d..459dd6a0a64 100644 --- a/modules/caddyhttp/fileserver/command.go +++ b/modules/caddyhttp/fileserver/command.go @@ -15,6 +15,8 @@ package fileserver import ( + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "encoding/json" "io" "log" @@ -22,14 +24,14 @@ import ( "strconv" "time" + "github.com/caddyserver/certmagic" + "github.com/spf13/cobra" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" - caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2/modules/caddyhttp" caddytpl "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" - "github.com/caddyserver/certmagic" - "github.com/spf13/cobra" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/fileserver/matcher.go b/modules/caddyhttp/fileserver/matcher.go index f42445fbf3d..c8f5b226e90 100644 --- a/modules/caddyhttp/fileserver/matcher.go +++ b/modules/caddyhttp/fileserver/matcher.go @@ -26,9 +26,6 @@ import ( "strconv" "strings" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" - "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/google/cel-go/cel" "github.com/google/cel-go/common" "github.com/google/cel-go/common/operators" @@ -36,6 +33,10 @@ import ( "github.com/google/cel-go/parser" "go.uber.org/zap" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { diff --git a/modules/caddyhttp/fileserver/staticfiles.go b/modules/caddyhttp/fileserver/staticfiles.go index 3261093d9e0..3eae02c0de6 100644 --- a/modules/caddyhttp/fileserver/staticfiles.go +++ b/modules/caddyhttp/fileserver/staticfiles.go @@ -30,10 +30,11 @@ import ( "strconv" "strings" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/ip_matchers.go b/modules/caddyhttp/ip_matchers.go index 8423c7dc575..57a229578ce 100644 --- a/modules/caddyhttp/ip_matchers.go +++ b/modules/caddyhttp/ip_matchers.go @@ -23,11 +23,12 @@ import ( "reflect" "strings" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types/ref" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) // MatchRemoteIP matches requests by the remote IP address, diff --git a/modules/caddyhttp/logging.go b/modules/caddyhttp/logging.go index 6bfeb51b668..8ecc49a63db 100644 --- a/modules/caddyhttp/logging.go +++ b/modules/caddyhttp/logging.go @@ -20,9 +20,10 @@ import ( "net/http" "strings" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" "go.uber.org/zap/zapcore" + + "github.com/caddyserver/caddy/v2" ) // ServerLogConfig describes a server's logging configuration. If diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go index f40802fc326..b3859797083 100644 --- a/modules/caddyhttp/matchers.go +++ b/modules/caddyhttp/matchers.go @@ -30,11 +30,12 @@ import ( "strconv" "strings" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) type ( diff --git a/modules/caddyhttp/metrics.go b/modules/caddyhttp/metrics.go index 64fbed750e4..9c0f961e58d 100644 --- a/modules/caddyhttp/metrics.go +++ b/modules/caddyhttp/metrics.go @@ -6,9 +6,10 @@ import ( "sync" "time" - "github.com/caddyserver/caddy/v2/internal/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/caddyserver/caddy/v2/internal/metrics" ) // Metrics configures metrics observations. diff --git a/modules/caddyhttp/proxyprotocol/listenerwrapper.go b/modules/caddyhttp/proxyprotocol/listenerwrapper.go index fd90499b503..f404c06fe51 100644 --- a/modules/caddyhttp/proxyprotocol/listenerwrapper.go +++ b/modules/caddyhttp/proxyprotocol/listenerwrapper.go @@ -19,8 +19,9 @@ import ( "net" "time" - "github.com/caddyserver/caddy/v2" "github.com/mastercactapus/proxyprotocol" + + "github.com/caddyserver/caddy/v2" ) // ListenerWrapper provides PROXY protocol support to Caddy by implementing diff --git a/modules/caddyhttp/push/handler.go b/modules/caddyhttp/push/handler.go index 3a71a6d6d05..031a8991fb5 100644 --- a/modules/caddyhttp/push/handler.go +++ b/modules/caddyhttp/push/handler.go @@ -19,10 +19,11 @@ import ( "net/http" "strings" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/replacer.go b/modules/caddyhttp/replacer.go index c58b56ed307..f6b042ce5d6 100644 --- a/modules/caddyhttp/replacer.go +++ b/modules/caddyhttp/replacer.go @@ -39,9 +39,10 @@ import ( "strings" "time" + "github.com/google/uuid" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddytls" - "github.com/google/uuid" ) // NewTestReplacer creates a replacer for an http.Request diff --git a/modules/caddyhttp/requestbody/caddyfile.go b/modules/caddyhttp/requestbody/caddyfile.go index 0a2459fbfa3..8a92909fb19 100644 --- a/modules/caddyhttp/requestbody/caddyfile.go +++ b/modules/caddyhttp/requestbody/caddyfile.go @@ -15,9 +15,10 @@ package requestbody import ( + "github.com/dustin/go-humanize" + "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "github.com/dustin/go-humanize" ) func init() { diff --git a/modules/caddyhttp/reverseproxy/caddyfile.go b/modules/caddyhttp/reverseproxy/caddyfile.go index 774f889ea07..a986f89f250 100644 --- a/modules/caddyhttp/reverseproxy/caddyfile.go +++ b/modules/caddyhttp/reverseproxy/caddyfile.go @@ -21,6 +21,8 @@ import ( "strconv" "strings" + "github.com/dustin/go-humanize" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" @@ -28,7 +30,6 @@ import ( "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" - "github.com/dustin/go-humanize" ) func init() { diff --git a/modules/caddyhttp/reverseproxy/command.go b/modules/caddyhttp/reverseproxy/command.go index 9359f3d0b35..d40500523b0 100644 --- a/modules/caddyhttp/reverseproxy/command.go +++ b/modules/caddyhttp/reverseproxy/command.go @@ -15,21 +15,23 @@ package reverseproxy import ( + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "encoding/json" "fmt" "net/http" "strconv" "strings" + "github.com/spf13/cobra" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" - caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddytls" - "github.com/spf13/cobra" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go index 4560cc144fd..31febdd4efe 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go @@ -24,12 +24,13 @@ import ( "strings" "time" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy" "github.com/caddyserver/caddy/v2/modules/caddytls" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" ) var noopLogger = zap.NewNop() diff --git a/modules/caddyhttp/reverseproxy/healthchecks.go b/modules/caddyhttp/reverseproxy/healthchecks.go index 80b635adc0a..1b4f2d05534 100644 --- a/modules/caddyhttp/reverseproxy/healthchecks.go +++ b/modules/caddyhttp/reverseproxy/healthchecks.go @@ -26,9 +26,10 @@ import ( "strconv" "time" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "go.uber.org/zap" ) // HealthChecks configures active and passive health checks. diff --git a/modules/caddyhttp/reverseproxy/httptransport.go b/modules/caddyhttp/reverseproxy/httptransport.go index 8334f25ad48..bcce67b476e 100644 --- a/modules/caddyhttp/reverseproxy/httptransport.go +++ b/modules/caddyhttp/reverseproxy/httptransport.go @@ -28,12 +28,13 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "github.com/caddyserver/caddy/v2/modules/caddytls" "github.com/mastercactapus/proxyprotocol" "go.uber.org/zap" "golang.org/x/net/http2" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" + "github.com/caddyserver/caddy/v2/modules/caddytls" ) func init() { diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index b65dce7202a..249326dd932 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -32,14 +32,15 @@ import ( "sync" "time" + "go.uber.org/zap" + "golang.org/x/net/http/httpguts" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyevents" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" - "go.uber.org/zap" - "golang.org/x/net/http/httpguts" ) func init() { diff --git a/modules/caddyhttp/reverseproxy/upstreams.go b/modules/caddyhttp/reverseproxy/upstreams.go index 19e4f3cbc66..8bdc60dd5ff 100644 --- a/modules/caddyhttp/reverseproxy/upstreams.go +++ b/modules/caddyhttp/reverseproxy/upstreams.go @@ -11,8 +11,9 @@ import ( "sync" "time" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddyhttp/rewrite/rewrite.go b/modules/caddyhttp/rewrite/rewrite.go index 499d2173fb0..77ef668bfa3 100644 --- a/modules/caddyhttp/rewrite/rewrite.go +++ b/modules/caddyhttp/rewrite/rewrite.go @@ -22,9 +22,10 @@ import ( "strconv" "strings" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index 69b02c754f0..9cdc76b5275 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -30,14 +30,15 @@ import ( "sync/atomic" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyevents" - "github.com/caddyserver/caddy/v2/modules/caddytls" "github.com/caddyserver/certmagic" "github.com/quic-go/quic-go" "github.com/quic-go/quic-go/http3" "go.uber.org/zap" "go.uber.org/zap/zapcore" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyevents" + "github.com/caddyserver/caddy/v2/modules/caddytls" ) // Server describes an HTTP server. diff --git a/modules/caddyhttp/staticresp.go b/modules/caddyhttp/staticresp.go index 0584916f183..38b01c3eeb8 100644 --- a/modules/caddyhttp/staticresp.go +++ b/modules/caddyhttp/staticresp.go @@ -15,6 +15,8 @@ package caddyhttp import ( + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "bytes" "encoding/json" "fmt" @@ -27,12 +29,12 @@ import ( "text/template" "time" + "github.com/spf13/cobra" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/spf13/cobra" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go index 89158f49251..6b2b4954d39 100644 --- a/modules/caddyhttp/templates/tplcontext.go +++ b/modules/caddyhttp/templates/tplcontext.go @@ -31,14 +31,15 @@ import ( "github.com/Masterminds/sprig/v3" chromahtml "github.com/alecthomas/chroma/v2/formatters/html" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/dustin/go-humanize" "github.com/yuin/goldmark" highlighting "github.com/yuin/goldmark-highlighting/v2" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" gmhtml "github.com/yuin/goldmark/renderer/html" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) // TemplateContext is the TemplateContext with which HTTP templates are executed. diff --git a/modules/caddyhttp/tracing/module.go b/modules/caddyhttp/tracing/module.go index e3eb84d203d..fd117c53757 100644 --- a/modules/caddyhttp/tracing/module.go +++ b/modules/caddyhttp/tracing/module.go @@ -4,11 +4,12 @@ import ( "fmt" "net/http" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "go.uber.org/zap" ) func init() { diff --git a/modules/caddyhttp/tracing/tracer.go b/modules/caddyhttp/tracing/tracer.go index c6dd7aab862..ecd415fa0cd 100644 --- a/modules/caddyhttp/tracing/tracer.go +++ b/modules/caddyhttp/tracing/tracer.go @@ -5,8 +5,6 @@ import ( "fmt" "net/http" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyhttp" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/contrib/propagators/autoprop" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" @@ -16,6 +14,9 @@ import ( semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) const ( diff --git a/modules/caddypki/acmeserver/acmeserver.go b/modules/caddypki/acmeserver/acmeserver.go index 454720bf36a..86896150c4a 100644 --- a/modules/caddypki/acmeserver/acmeserver.go +++ b/modules/caddypki/acmeserver/acmeserver.go @@ -26,9 +26,6 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "github.com/caddyserver/caddy/v2/modules/caddypki" "github.com/go-chi/chi" "github.com/smallstep/certificates/acme" "github.com/smallstep/certificates/acme/api" @@ -38,6 +35,10 @@ import ( "github.com/smallstep/certificates/db" "github.com/smallstep/nosql" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" + "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { diff --git a/modules/caddypki/adminapi.go b/modules/caddypki/adminapi.go index 24371e74687..435af349a4a 100644 --- a/modules/caddypki/adminapi.go +++ b/modules/caddypki/adminapi.go @@ -20,8 +20,9 @@ import ( "net/http" "strings" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddypki/ca.go b/modules/caddypki/ca.go index d52fc5f360f..6c48da6f9a2 100644 --- a/modules/caddypki/ca.go +++ b/modules/caddypki/ca.go @@ -25,12 +25,13 @@ import ( "sync" "time" - "github.com/caddyserver/caddy/v2" "github.com/caddyserver/certmagic" "github.com/smallstep/certificates/authority" "github.com/smallstep/certificates/db" "github.com/smallstep/truststore" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) // CA describes a certificate authority, which consists of diff --git a/modules/caddypki/command.go b/modules/caddypki/command.go index e78f35c88d0..3a023cb2c6d 100644 --- a/modules/caddypki/command.go +++ b/modules/caddypki/command.go @@ -15,6 +15,8 @@ package caddypki import ( + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "crypto/x509" "encoding/json" "encoding/pem" @@ -23,10 +25,10 @@ import ( "os" "path" - "github.com/caddyserver/caddy/v2" - caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/smallstep/truststore" "github.com/spf13/cobra" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddypki/pki.go b/modules/caddypki/pki.go index 2caeb2b5976..9f974a956bb 100644 --- a/modules/caddypki/pki.go +++ b/modules/caddypki/pki.go @@ -17,8 +17,9 @@ package caddypki import ( "fmt" - "github.com/caddyserver/caddy/v2" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddytls/acmeissuer.go b/modules/caddytls/acmeissuer.go index ca7998179b3..5e79c2d2ed3 100644 --- a/modules/caddytls/acmeissuer.go +++ b/modules/caddytls/acmeissuer.go @@ -24,13 +24,14 @@ import ( "strconv" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/certmagic" "github.com/mholt/acmez" "github.com/mholt/acmez/acme" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/caddytls/automation.go b/modules/caddytls/automation.go index 114d7aad706..be36c9788b0 100644 --- a/modules/caddytls/automation.go +++ b/modules/caddytls/automation.go @@ -22,10 +22,11 @@ import ( "strings" "time" - "github.com/caddyserver/caddy/v2" "github.com/caddyserver/certmagic" "github.com/mholt/acmez" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) // AutomationConfig governs the automated management of TLS certificates. diff --git a/modules/caddytls/certmanagers.go b/modules/caddytls/certmanagers.go index 23af19d44ac..ad26468a9dd 100644 --- a/modules/caddytls/certmanagers.go +++ b/modules/caddytls/certmanagers.go @@ -9,11 +9,12 @@ import ( "net/url" "strings" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/certmagic" "github.com/tailscale/tscert" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/caddytls/connpolicy.go b/modules/caddytls/connpolicy.go index 74c83241107..64fdd513861 100644 --- a/modules/caddytls/connpolicy.go +++ b/modules/caddytls/connpolicy.go @@ -25,9 +25,10 @@ import ( "path/filepath" "strings" - "github.com/caddyserver/caddy/v2" "github.com/mholt/acmez" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddytls/distributedstek/distributedstek.go b/modules/caddytls/distributedstek/distributedstek.go index 18ed69496c5..f6d0de064c0 100644 --- a/modules/caddytls/distributedstek/distributedstek.go +++ b/modules/caddytls/distributedstek/distributedstek.go @@ -33,9 +33,10 @@ import ( "runtime/debug" "time" + "github.com/caddyserver/certmagic" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddytls" - "github.com/caddyserver/certmagic" ) func init() { diff --git a/modules/caddytls/internalissuer.go b/modules/caddytls/internalissuer.go index 3dd6c359fca..1cf2461ab7c 100644 --- a/modules/caddytls/internalissuer.go +++ b/modules/caddytls/internalissuer.go @@ -21,12 +21,13 @@ import ( "encoding/pem" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" - "github.com/caddyserver/caddy/v2/modules/caddypki" "github.com/caddyserver/certmagic" "github.com/smallstep/certificates/authority/provisioner" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" + "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { diff --git a/modules/caddytls/matchers.go b/modules/caddytls/matchers.go index f541220fc03..af1f898bb27 100644 --- a/modules/caddytls/matchers.go +++ b/modules/caddytls/matchers.go @@ -21,9 +21,10 @@ import ( "net/netip" "strings" - "github.com/caddyserver/caddy/v2" "github.com/caddyserver/certmagic" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddytls/storageloader.go b/modules/caddytls/storageloader.go index ef9d51e7c9f..ddaaa51560c 100644 --- a/modules/caddytls/storageloader.go +++ b/modules/caddytls/storageloader.go @@ -18,8 +18,9 @@ import ( "crypto/tls" "fmt" - "github.com/caddyserver/caddy/v2" "github.com/caddyserver/certmagic" + + "github.com/caddyserver/caddy/v2" ) func init() { diff --git a/modules/caddytls/tls.go b/modules/caddytls/tls.go index 1456d294dca..02d5aae756b 100644 --- a/modules/caddytls/tls.go +++ b/modules/caddytls/tls.go @@ -25,10 +25,11 @@ import ( "sync" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/modules/caddyevents" "github.com/caddyserver/certmagic" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyevents" ) func init() { diff --git a/modules/caddytls/zerosslissuer.go b/modules/caddytls/zerosslissuer.go index 02092944b11..697bab07d1d 100644 --- a/modules/caddytls/zerosslissuer.go +++ b/modules/caddytls/zerosslissuer.go @@ -25,11 +25,12 @@ import ( "strings" "sync" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/certmagic" "github.com/mholt/acmez/acme" "go.uber.org/zap" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/filestorage/filestorage.go b/modules/filestorage/filestorage.go index 629dc27edfc..672c66cbe3c 100644 --- a/modules/filestorage/filestorage.go +++ b/modules/filestorage/filestorage.go @@ -15,9 +15,10 @@ package filestorage import ( + "github.com/caddyserver/certmagic" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" - "github.com/caddyserver/certmagic" ) func init() { diff --git a/modules/logging/encoders.go b/modules/logging/encoders.go index 1cfab8ea607..a4409e7e459 100644 --- a/modules/logging/encoders.go +++ b/modules/logging/encoders.go @@ -17,11 +17,12 @@ package logging import ( "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/logging/filewriter.go b/modules/logging/filewriter.go index afc4afccd97..11c051d783f 100644 --- a/modules/logging/filewriter.go +++ b/modules/logging/filewriter.go @@ -22,10 +22,11 @@ import ( "path/filepath" "strconv" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/dustin/go-humanize" "gopkg.in/natefinch/lumberjack.v2" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/logging/filterencoder.go b/modules/logging/filterencoder.go index 1a6842e1890..4d51e645c36 100644 --- a/modules/logging/filterencoder.go +++ b/modules/logging/filterencoder.go @@ -19,12 +19,13 @@ import ( "fmt" "time" - "github.com/caddyserver/caddy/v2" - "github.com/caddyserver/caddy/v2/caddyconfig" - "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { diff --git a/modules/logging/filters.go b/modules/logging/filters.go index af9be745b0f..ed4c7affb3e 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -25,10 +25,11 @@ import ( "strconv" "strings" + "go.uber.org/zap/zapcore" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "go.uber.org/zap/zapcore" ) func init() { diff --git a/modules/metrics/metrics.go b/modules/metrics/metrics.go index e832737af0f..a9e0f0efa54 100644 --- a/modules/metrics/metrics.go +++ b/modules/metrics/metrics.go @@ -17,13 +17,14 @@ package metrics import ( "net/http" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "go.uber.org/zap" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - "go.uber.org/zap" ) func init() { From 4b47929936146a98cda6c528dc17114e4cfdd549 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 17:03:20 +0800 Subject: [PATCH 07/31] linter autofixes --- caddytest/caddytest.go | 4 ++-- modules/caddyhttp/caddyauth/command.go | 4 ++-- modules/caddyhttp/fileserver/command.go | 4 ++-- modules/caddyhttp/reverseproxy/command.go | 4 ++-- modules/caddyhttp/staticresp.go | 4 ++-- modules/caddypki/command.go | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/caddytest/caddytest.go b/caddytest/caddytest.go index a563a12cde5..76e594913a4 100644 --- a/caddytest/caddytest.go +++ b/caddytest/caddytest.go @@ -1,8 +1,6 @@ package caddytest import ( - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "bytes" "context" "crypto/tls" @@ -23,6 +21,8 @@ import ( "testing" "time" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/aryann/difflib" "github.com/caddyserver/caddy/v2/caddyconfig" diff --git a/modules/caddyhttp/caddyauth/command.go b/modules/caddyhttp/caddyauth/command.go index 416849f6472..58c93bd0460 100644 --- a/modules/caddyhttp/caddyauth/command.go +++ b/modules/caddyhttp/caddyauth/command.go @@ -15,8 +15,6 @@ package caddyauth import ( - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "bufio" "bytes" "encoding/base64" @@ -24,6 +22,8 @@ import ( "os" "os/signal" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/spf13/cobra" "golang.org/x/term" diff --git a/modules/caddyhttp/fileserver/command.go b/modules/caddyhttp/fileserver/command.go index 459dd6a0a64..dd1e0ffa3de 100644 --- a/modules/caddyhttp/fileserver/command.go +++ b/modules/caddyhttp/fileserver/command.go @@ -15,8 +15,6 @@ package fileserver import ( - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "encoding/json" "io" "log" @@ -24,6 +22,8 @@ import ( "strconv" "time" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/certmagic" "github.com/spf13/cobra" "go.uber.org/zap" diff --git a/modules/caddyhttp/reverseproxy/command.go b/modules/caddyhttp/reverseproxy/command.go index d40500523b0..9cd6913fc3f 100644 --- a/modules/caddyhttp/reverseproxy/command.go +++ b/modules/caddyhttp/reverseproxy/command.go @@ -15,14 +15,14 @@ package reverseproxy import ( - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "encoding/json" "fmt" "net/http" "strconv" "strings" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/spf13/cobra" "go.uber.org/zap" diff --git a/modules/caddyhttp/staticresp.go b/modules/caddyhttp/staticresp.go index 38b01c3eeb8..e0fd40509f4 100644 --- a/modules/caddyhttp/staticresp.go +++ b/modules/caddyhttp/staticresp.go @@ -15,8 +15,6 @@ package caddyhttp import ( - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "bytes" "encoding/json" "fmt" @@ -29,6 +27,8 @@ import ( "text/template" "time" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/spf13/cobra" "go.uber.org/zap" diff --git a/modules/caddypki/command.go b/modules/caddypki/command.go index 3a023cb2c6d..f563d61265f 100644 --- a/modules/caddypki/command.go +++ b/modules/caddypki/command.go @@ -15,8 +15,6 @@ package caddypki import ( - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "crypto/x509" "encoding/json" "encoding/pem" @@ -25,6 +23,8 @@ import ( "os" "path" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/smallstep/truststore" "github.com/spf13/cobra" From c4a08bda1a8650996bfbae62bd4bb346f7c4992c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 17:07:49 +0800 Subject: [PATCH 08/31] rearrange imports a little --- .golangci.yml | 2 +- caddytest/caddytest.go | 4 ++-- modules/caddyhttp/caddyauth/command.go | 4 ++-- modules/caddyhttp/fileserver/command.go | 4 ++-- modules/caddyhttp/reverseproxy/command.go | 4 ++-- modules/caddyhttp/staticresp.go | 4 ++-- modules/caddypki/command.go | 4 ++-- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index daa825ce468..5f018970eb7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -4,9 +4,9 @@ linters-settings: ignoretests: true gci: sections: - - prefix(github.com/caddyserver/caddy/v2/cmd) # ensure that this is always at the top and always has a line break. - standard # Standard section: captures all standard packages. - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/caddyserver/caddy/v2/cmd) # ensure that this is always at the top and always has a line break. - prefix(github.com/caddyserver/caddy) # Custom section: groups all imports with the specified Prefix. # Skip generated files. # Default: true diff --git a/caddytest/caddytest.go b/caddytest/caddytest.go index 76e594913a4..9c170703c57 100644 --- a/caddytest/caddytest.go +++ b/caddytest/caddytest.go @@ -21,10 +21,10 @@ import ( "testing" "time" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/aryann/difflib" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/caddy/v2/caddyconfig" // plug in Caddy modules here _ "github.com/caddyserver/caddy/v2/modules/standard" diff --git a/modules/caddyhttp/caddyauth/command.go b/modules/caddyhttp/caddyauth/command.go index 58c93bd0460..b93b7a402f3 100644 --- a/modules/caddyhttp/caddyauth/command.go +++ b/modules/caddyhttp/caddyauth/command.go @@ -22,11 +22,11 @@ import ( "os" "os/signal" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/spf13/cobra" "golang.org/x/term" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/caddy/v2" ) diff --git a/modules/caddyhttp/fileserver/command.go b/modules/caddyhttp/fileserver/command.go index dd1e0ffa3de..fb145cb06ca 100644 --- a/modules/caddyhttp/fileserver/command.go +++ b/modules/caddyhttp/fileserver/command.go @@ -22,12 +22,12 @@ import ( "strconv" "time" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/caddyserver/certmagic" "github.com/spf13/cobra" "go.uber.org/zap" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/modules/caddyhttp" diff --git a/modules/caddyhttp/reverseproxy/command.go b/modules/caddyhttp/reverseproxy/command.go index 9cd6913fc3f..11f935cf96a 100644 --- a/modules/caddyhttp/reverseproxy/command.go +++ b/modules/caddyhttp/reverseproxy/command.go @@ -21,11 +21,11 @@ import ( "strconv" "strings" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/spf13/cobra" "go.uber.org/zap" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" diff --git a/modules/caddyhttp/staticresp.go b/modules/caddyhttp/staticresp.go index e0fd40509f4..4fe5910e40e 100644 --- a/modules/caddyhttp/staticresp.go +++ b/modules/caddyhttp/staticresp.go @@ -27,11 +27,11 @@ import ( "text/template" "time" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/spf13/cobra" "go.uber.org/zap" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" diff --git a/modules/caddypki/command.go b/modules/caddypki/command.go index f563d61265f..b7fa1bb7ce1 100644 --- a/modules/caddypki/command.go +++ b/modules/caddypki/command.go @@ -23,11 +23,11 @@ import ( "os" "path" - caddycmd "github.com/caddyserver/caddy/v2/cmd" - "github.com/smallstep/truststore" "github.com/spf13/cobra" + caddycmd "github.com/caddyserver/caddy/v2/cmd" + "github.com/caddyserver/caddy/v2" ) From 8cd113410b6975c636f3e5bf699b485591920e03 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 20:37:15 +0800 Subject: [PATCH 09/31] all changes other than unused-parameter --- .golangci.yml | 1 + caddyconfig/caddyfile/dispenser.go | 4 ++-- caddyconfig/caddyfile/formatter.go | 6 ++--- caddyconfig/caddyfile/parse.go | 8 +++---- caddyconfig/httploader.go | 8 +++---- cmd/commandfuncs.go | 2 +- listeners.go | 14 ++++++------ modules/caddyhttp/encode/encode.go | 3 +-- modules/caddyhttp/ip_range.go | 6 ++--- modules/caddyhttp/push/handler.go | 7 ++---- modules/caddyhttp/reverseproxy/command.go | 4 ++-- .../reverseproxy/selectionpolicies.go | 2 +- modules/caddyhttp/staticresp.go | 4 ++-- modules/logging/filters.go | 22 +++++++++---------- 14 files changed, 44 insertions(+), 47 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 5f018970eb7..d2880695fa6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -29,6 +29,7 @@ linters: - ineffassign - misspell - prealloc + - revive - staticcheck - typecheck - unconvert diff --git a/caddyconfig/caddyfile/dispenser.go b/caddyconfig/caddyfile/dispenser.go index 6c33f4fe6f3..817e229541b 100644 --- a/caddyconfig/caddyfile/dispenser.go +++ b/caddyconfig/caddyfile/dispenser.go @@ -236,8 +236,8 @@ func (d *Dispenser) ScalarVal() any { if num, err := strconv.ParseFloat(text, 64); err == nil { return num } - if bool, err := strconv.ParseBool(text); err == nil { - return bool + if boolean, err := strconv.ParseBool(text); err == nil { + return boolean } return text } diff --git a/caddyconfig/caddyfile/formatter.go b/caddyconfig/caddyfile/formatter.go index 82581a3d31e..0614ab607b7 100644 --- a/caddyconfig/caddyfile/formatter.go +++ b/caddyconfig/caddyfile/formatter.go @@ -81,10 +81,10 @@ func Format(input []byte) []byte { space = true nextLine() continue - } else { - write(ch) - continue } + write(ch) + continue + } if !escaped && ch == '\\' { diff --git a/caddyconfig/caddyfile/parse.go b/caddyconfig/caddyfile/parse.go index 65d6ee92765..c4cb2b51ea4 100644 --- a/caddyconfig/caddyfile/parse.go +++ b/caddyconfig/caddyfile/parse.go @@ -446,7 +446,7 @@ func (p *parser) doImport(nesting int) error { var ( maybeSnippet bool - maybeSnippetId bool + maybeSnippetID bool index int ) @@ -472,16 +472,16 @@ func (p *parser) doImport(nesting int) error { } if index == 0 && len(token.Text) >= 3 && strings.HasPrefix(token.Text, "(") && strings.HasSuffix(token.Text, ")") { - maybeSnippetId = true + maybeSnippetID = true } } switch token.Text { case "{": nesting++ - if index == 1 && maybeSnippetId && nesting == 1 { + if index == 1 && maybeSnippetID && nesting == 1 { maybeSnippet = true - maybeSnippetId = false + maybeSnippetID = false } case "}": nesting-- diff --git a/caddyconfig/httploader.go b/caddyconfig/httploader.go index e0ce4ebf7a6..6397b7aa25a 100644 --- a/caddyconfig/httploader.go +++ b/caddyconfig/httploader.go @@ -105,7 +105,7 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) { } } - resp, err := doHttpCallWithRetries(ctx, client, req) + resp, err := doHTTPCallWithRetries(ctx, client, req) if err != nil { return nil, err } @@ -135,7 +135,7 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) { return result, nil } -func attemptHttpCall(client *http.Client, request *http.Request) (*http.Response, error) { +func attemptHTTPCall(client *http.Client, request *http.Request) (*http.Response, error) { resp, err := client.Do(request) if err != nil { return nil, fmt.Errorf("problem calling http loader url: %v", err) @@ -146,13 +146,13 @@ func attemptHttpCall(client *http.Client, request *http.Request) (*http.Response return resp, nil } -func doHttpCallWithRetries(ctx caddy.Context, client *http.Client, request *http.Request) (*http.Response, error) { +func doHTTPCallWithRetries(ctx caddy.Context, client *http.Client, request *http.Request) (*http.Response, error) { var resp *http.Response var err error const maxAttempts = 10 for i := 0; i < maxAttempts; i++ { - resp, err = attemptHttpCall(client, request) + resp, err = attemptHTTPCall(client, request) if err != nil && i < maxAttempts-1 { select { case <-time.After(time.Millisecond * 500): diff --git a/cmd/commandfuncs.go b/cmd/commandfuncs.go index 11b42a1ff52..db573942e5b 100644 --- a/cmd/commandfuncs.go +++ b/cmd/commandfuncs.go @@ -630,7 +630,7 @@ func AdminAPIRequest(adminAddr, method, uri string, headers http.Header, body io if err != nil { return nil, fmt.Errorf("making request: %v", err) } - if parsedAddr.IsUnixNetwork() { + if parsedAddr.IsUnixNetwork() { //nolint:revive // We used to conform to RFC 2616 Section 14.26 which requires // an empty host header when there is no host, as is the case // with unix sockets. However, Go required a Host value so we diff --git a/listeners.go b/listeners.go index 768d977115c..26f4b77b46c 100644 --- a/listeners.go +++ b/listeners.go @@ -479,8 +479,8 @@ func ListenQUIC(ln net.PacketConn, tlsConf *tls.Config, activeRequests *int64) ( sqtc := newSharedQUICTLSConfig(tlsConf) // http3.ConfigureTLSConfig only uses this field and tls App sets this field as well //nolint:gosec - quicTlsConfig := &tls.Config{GetConfigForClient: sqtc.getConfigForClient} - earlyLn, err := quic.ListenEarly(ln, http3.ConfigureTLSConfig(quicTlsConfig), &quic.Config{ + quicTLSConfig := &tls.Config{GetConfigForClient: sqtc.getConfigForClient} + earlyLn, err := quic.ListenEarly(ln, http3.ConfigureTLSConfig(quicTLSConfig), &quic.Config{ Allow0RTT: true, RequireAddressValidation: func(clientAddr net.Addr) bool { var highLoad bool @@ -539,14 +539,14 @@ type contextAndCancelFunc struct { type sharedQUICTLSConfig struct { rmu sync.RWMutex tlsConfs map[*tls.Config]contextAndCancelFunc - activeTlsConf *tls.Config + activeTLSConf *tls.Config } // newSharedQUICTLSConfig creates a new sharedQUICTLSConfig func newSharedQUICTLSConfig(tlsConfig *tls.Config) *sharedQUICTLSConfig { sqtc := &sharedQUICTLSConfig{ tlsConfs: make(map[*tls.Config]contextAndCancelFunc), - activeTlsConf: tlsConfig, + activeTLSConf: tlsConfig, } sqtc.addTLSConfig(tlsConfig) return sqtc @@ -556,7 +556,7 @@ func newSharedQUICTLSConfig(tlsConfig *tls.Config) *sharedQUICTLSConfig { func (sqtc *sharedQUICTLSConfig) getConfigForClient(ch *tls.ClientHelloInfo) (*tls.Config, error) { sqtc.rmu.RLock() defer sqtc.rmu.RUnlock() - return sqtc.activeTlsConf.GetConfigForClient(ch) + return sqtc.activeTLSConf.GetConfigForClient(ch) } // addTLSConfig adds tls.Config to the map if not present and returns the corresponding context and its cancelFunc @@ -577,11 +577,11 @@ func (sqtc *sharedQUICTLSConfig) addTLSConfig(tlsConfig *tls.Config) (context.Co defer sqtc.rmu.Unlock() delete(sqtc.tlsConfs, tlsConfig) - if sqtc.activeTlsConf == tlsConfig { + if sqtc.activeTLSConf == tlsConfig { // select another tls.Config, if there is none, // related sharedQuicListener will be destroyed anyway for tc := range sqtc.tlsConfs { - sqtc.activeTlsConf = tc + sqtc.activeTLSConf = tc break } } diff --git a/modules/caddyhttp/encode/encode.go b/modules/caddyhttp/encode/encode.go index ed3e59dae1d..18dd129bc4a 100644 --- a/modules/caddyhttp/encode/encode.go +++ b/modules/caddyhttp/encode/encode.go @@ -269,9 +269,8 @@ func (rw *responseWriter) Write(p []byte) (int, error) { if rw.w != nil { return rw.w.Write(p) - } else { - return rw.ResponseWriter.Write(p) } + return rw.ResponseWriter.Write(p) } // Close writes any remaining buffered response and diff --git a/modules/caddyhttp/ip_range.go b/modules/caddyhttp/ip_range.go index b1db254752f..6b03ef75196 100644 --- a/modules/caddyhttp/ip_range.go +++ b/modules/caddyhttp/ip_range.go @@ -86,16 +86,16 @@ func (s *StaticIPRange) GetIPRanges(_ *http.Request) []netip.Prefix { } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. -func (m *StaticIPRange) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (f *StaticIPRange) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if !d.Next() { return nil } for d.NextArg() { if d.Val() == "private_ranges" { - m.Ranges = append(m.Ranges, PrivateRangesCIDR()...) + f.Ranges = append(f.Ranges, PrivateRangesCIDR()...) continue } - m.Ranges = append(m.Ranges, d.Val()) + f.Ranges = append(f.Ranges, d.Val()) } return nil } diff --git a/modules/caddyhttp/push/handler.go b/modules/caddyhttp/push/handler.go index 031a8991fb5..3204debeffa 100644 --- a/modules/caddyhttp/push/handler.go +++ b/modules/caddyhttp/push/handler.go @@ -122,11 +122,8 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhtt } // serve only after pushing! - if err := next.ServeHTTP(lp, r); err != nil { - return err - } - - return nil + err := next.ServeHTTP(lp, r) + return err } func (h Handler) initializePushHeaders(r *http.Request, repl *caddy.Replacer) http.Header { diff --git a/modules/caddyhttp/reverseproxy/command.go b/modules/caddyhttp/reverseproxy/command.go index 11f935cf96a..464bccfb320 100644 --- a/modules/caddyhttp/reverseproxy/command.go +++ b/modules/caddyhttp/reverseproxy/command.go @@ -284,12 +284,12 @@ func cmdReverseProxy(fs caddycmd.Flags) (int, error) { appsRaw["tls"] = caddyconfig.JSON(tlsApp, nil) } - var false bool + var falseBool bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ - Persist: &false, + Persist: &falseBool, }, }, AppsRaw: appsRaw, diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index bc6de35160e..d3dad3859f1 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -770,7 +770,7 @@ func leastRequests(upstreams []*Upstream) *Upstream { return nil } var best []*Upstream - var bestReqs int = -1 + bestReqs := -1 for _, upstream := range upstreams { if upstream == nil { continue diff --git a/modules/caddyhttp/staticresp.go b/modules/caddyhttp/staticresp.go index 4fe5910e40e..9b7754eba84 100644 --- a/modules/caddyhttp/staticresp.go +++ b/modules/caddyhttp/staticresp.go @@ -394,12 +394,12 @@ func cmdRespond(fl caddycmd.Flags) (int, error) { } // finish building the config - var false bool + var falseBool bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ - Persist: &false, + Persist: &falseBool, }, }, AppsRaw: caddy.ModuleMap{ diff --git a/modules/logging/filters.go b/modules/logging/filters.go index ed4c7affb3e..1ef2bdf5cf0 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -322,7 +322,7 @@ func (QueryFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (m *QueryFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (f *QueryFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { qfa := queryFilterAction{} @@ -360,21 +360,21 @@ func (m *QueryFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return d.Errf("unrecognized subdirective %s", d.Val()) } - m.Actions = append(m.Actions, qfa) + f.Actions = append(f.Actions, qfa) } } return nil } // Filter filters the input field. -func (m QueryFilter) Filter(in zapcore.Field) zapcore.Field { +func (f QueryFilter) Filter(in zapcore.Field) zapcore.Field { u, err := url.Parse(in.String) if err != nil { return in } q := u.Query() - for _, a := range m.Actions { + for _, a := range f.Actions { switch a.Type { case replaceAction: for i := range q[a.Parameter] { @@ -442,7 +442,7 @@ func (CookieFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (m *CookieFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (f *CookieFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { cfa := cookieFilterAction{} @@ -480,14 +480,14 @@ func (m *CookieFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return d.Errf("unrecognized subdirective %s", d.Val()) } - m.Actions = append(m.Actions, cfa) + f.Actions = append(f.Actions, cfa) } } return nil } // Filter filters the input field. -func (m CookieFilter) Filter(in zapcore.Field) zapcore.Field { +func (f CookieFilter) Filter(in zapcore.Field) zapcore.Field { cookiesSlice, ok := in.Interface.(caddyhttp.LoggableStringArray) if !ok { return in @@ -500,7 +500,7 @@ func (m CookieFilter) Filter(in zapcore.Field) zapcore.Field { OUTER: for _, c := range cookies { - for _, a := range m.Actions { + for _, a := range f.Actions { if c.Name != a.Name { continue } @@ -566,13 +566,13 @@ func (f *RegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision compiles m's regexp. -func (m *RegexpFilter) Provision(ctx caddy.Context) error { - r, err := regexp.Compile(m.RawRegexp) +func (f *RegexpFilter) Provision(ctx caddy.Context) error { + r, err := regexp.Compile(f.RawRegexp) if err != nil { return err } - m.regexp = r + f.regexp = r return nil } From c416fb85261eb38c1d31998dfa22c8d549632f1f Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 20:54:57 +0800 Subject: [PATCH 10/31] use revive linter --- .golangci.yml | 2 + admin.go | 4 +- caddyconfig/httpcaddyfile/options.go | 2 +- caddyconfig/httpcaddyfile/pkiapp.go | 2 +- caddyconfig/httpcaddyfile/serveroptions.go | 2 +- caddyconfig/httpcaddyfile/tlsapp.go | 2 +- modules/caddyhttp/caddyhttp.go | 2 +- modules/caddyhttp/celmatcher.go | 8 +-- modules/caddyhttp/duplex_go120.go | 2 +- modules/caddyhttp/encode/gzip/gzip.go | 2 +- modules/caddyhttp/encode/zstd/zstd.go | 2 +- modules/caddyhttp/fileserver/command.go | 4 +- modules/caddyhttp/fileserver/matcher.go | 4 +- modules/caddyhttp/http2listener.go | 4 +- modules/caddyhttp/httpredirectlistener.go | 2 +- modules/caddyhttp/ip_range.go | 8 +-- .../proxyprotocol/listenerwrapper.go | 2 +- .../caddyhttp/reverseproxy/healthchecks.go | 2 +- .../caddyhttp/reverseproxy/reverseproxy.go | 2 +- .../reverseproxy/selectionpolicies.go | 6 +-- modules/caddyhttp/routes.go | 2 +- modules/caddyhttp/staticerror.go | 2 +- modules/caddyhttp/templates/templates.go | 2 +- modules/caddytls/certmanagers.go | 2 +- modules/caddytls/internalissuer.go | 2 +- modules/caddytls/tls.go | 2 +- modules/logging/filewriter.go | 2 +- modules/logging/filters.go | 8 +-- modules/logging/netwriter.go | 2 +- modules/logging/nopencoder.go | 52 +++++++++---------- modules/metrics/metrics.go | 2 +- 31 files changed, 72 insertions(+), 70 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index d2880695fa6..976bb0a46ea 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -89,6 +89,8 @@ output: print-linter-name: true issues: + max-issues-per-linter: 10000 + max-same-issues: 10000 exclude-rules: # we aren't calling unknown URL - text: 'G107' # G107: Url provided to HTTP request as taint input diff --git a/admin.go b/admin.go index 335b8e89545..5c5eee733ab 100644 --- a/admin.go +++ b/admin.go @@ -1022,7 +1022,7 @@ func handleConfig(w http.ResponseWriter, r *http.Request) error { return nil } -func handleConfigID(w http.ResponseWriter, r *http.Request) error { +func handleConfigID(_ http.ResponseWriter, r *http.Request) error { idPath := r.URL.Path parts := strings.Split(idPath, "/") @@ -1058,7 +1058,7 @@ func handleConfigID(w http.ResponseWriter, r *http.Request) error { return errInternalRedir } -func handleStop(w http.ResponseWriter, r *http.Request) error { +func handleStop(_ http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodPost { return APIError{ HTTPStatus: http.StatusMethodNotAllowed, diff --git a/caddyconfig/httpcaddyfile/options.go b/caddyconfig/httpcaddyfile/options.go index ba1896b6b84..3b5b80cb3e0 100644 --- a/caddyconfig/httpcaddyfile/options.go +++ b/caddyconfig/httpcaddyfile/options.go @@ -59,7 +59,7 @@ func init() { RegisterGlobalOption("persist_config", parseOptPersistConfig) } -func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil } +func parseOptTrue(_ *caddyfile.Dispenser, _ any) (any, error) { return true, nil } func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) { var httpPort int diff --git a/caddyconfig/httpcaddyfile/pkiapp.go b/caddyconfig/httpcaddyfile/pkiapp.go index b5c682187d9..16ec73dc9a3 100644 --- a/caddyconfig/httpcaddyfile/pkiapp.go +++ b/caddyconfig/httpcaddyfile/pkiapp.go @@ -47,7 +47,7 @@ func init() { // } // // When the CA ID is unspecified, 'local' is assumed. -func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) { +func parsePKIApp(d *caddyfile.Dispenser, _ any) (any, error) { pki := &caddypki.PKI{CAs: make(map[string]*caddypki.CA)} for d.Next() { diff --git a/caddyconfig/httpcaddyfile/serveroptions.go b/caddyconfig/httpcaddyfile/serveroptions.go index 6d7c6787f37..c79944123bb 100644 --- a/caddyconfig/httpcaddyfile/serveroptions.go +++ b/caddyconfig/httpcaddyfile/serveroptions.go @@ -284,7 +284,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) { func applyServerOptions( servers map[string]*caddyhttp.Server, options map[string]any, - warnings *[]caddyconfig.Warning, + _ *[]caddyconfig.Warning, ) error { serverOpts, ok := options["servers"].([]serverOptions) if !ok { diff --git a/caddyconfig/httpcaddyfile/tlsapp.go b/caddyconfig/httpcaddyfile/tlsapp.go index 927f225df3a..1b95273c0b2 100644 --- a/caddyconfig/httpcaddyfile/tlsapp.go +++ b/caddyconfig/httpcaddyfile/tlsapp.go @@ -485,7 +485,7 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e // for any other automation policies. A nil policy (and no error) will be // returned if there are no default/global options. However, if always is // true, a non-nil value will always be returned (unless there is an error). -func newBaseAutomationPolicy(options map[string]any, warnings []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) { +func newBaseAutomationPolicy(options map[string]any, _ []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) { issuers, hasIssuers := options["cert_issuer"] _, hasLocalCerts := options["local_certs"] keyType, hasKeyType := options["key_type"] diff --git a/modules/caddyhttp/caddyhttp.go b/modules/caddyhttp/caddyhttp.go index f15aec5ed4b..a17dc7dada9 100644 --- a/modules/caddyhttp/caddyhttp.go +++ b/modules/caddyhttp/caddyhttp.go @@ -294,7 +294,7 @@ func (tlsPlaceholderWrapper) CaddyModule() caddy.ModuleInfo { func (tlsPlaceholderWrapper) WrapListener(ln net.Listener) net.Listener { return ln } -func (tlsPlaceholderWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } +func (tlsPlaceholderWrapper) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } const ( // DefaultHTTPPort is the default port for HTTP. diff --git a/modules/caddyhttp/celmatcher.go b/modules/caddyhttp/celmatcher.go index e997336ff8a..f1c2eeb1171 100644 --- a/modules/caddyhttp/celmatcher.go +++ b/modules/caddyhttp/celmatcher.go @@ -232,11 +232,11 @@ func (cr celHTTPRequest) Parent() interpreter.Activation { return nil } -func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) { +func (cr celHTTPRequest) ConvertToNative(_ reflect.Type) (any, error) { return cr.Request, nil } -func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val { +func (celHTTPRequest) ConvertToType(_ ref.Type) ref.Val { panic("not implemented") } @@ -255,7 +255,7 @@ var pkixNameCELType = types.NewTypeValue("pkix.Name", traits.ReceiverType) // methods to satisfy the ref.Val interface. type celPkixName struct{ *pkix.Name } -func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) { +func (pn celPkixName) ConvertToNative(_ reflect.Type) (any, error) { return pn.Name, nil } @@ -442,7 +442,7 @@ func CELMatcherDecorator(funcName string, fac CELMatcherFactory) interpreter.Int // CELMatcherRuntimeFunction creates a function binding for when the input to the matcher // is dynamically resolved rather than a set of static constant values. -func CELMatcherRuntimeFunction(funcName string, fac CELMatcherFactory) functions.BinaryOp { +func CELMatcherRuntimeFunction(_ string, fac CELMatcherFactory) functions.BinaryOp { return func(celReq, matcherData ref.Val) ref.Val { matcher, err := fac(matcherData) if err != nil { diff --git a/modules/caddyhttp/duplex_go120.go b/modules/caddyhttp/duplex_go120.go index 462f2c0c151..c7d03f73b0d 100644 --- a/modules/caddyhttp/duplex_go120.go +++ b/modules/caddyhttp/duplex_go120.go @@ -20,6 +20,6 @@ import ( "net/http" ) -func enableFullDuplex(w http.ResponseWriter) { +func enableFullDuplex(_ http.ResponseWriter) { // Do nothing, Go 1.20 and earlier do not support full duplex } diff --git a/modules/caddyhttp/encode/gzip/gzip.go b/modules/caddyhttp/encode/gzip/gzip.go index 0af38b92776..529436cf49d 100644 --- a/modules/caddyhttp/encode/gzip/gzip.go +++ b/modules/caddyhttp/encode/gzip/gzip.go @@ -59,7 +59,7 @@ func (g *Gzip) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision provisions g's configuration. -func (g *Gzip) Provision(ctx caddy.Context) error { +func (g *Gzip) Provision(_ caddy.Context) error { if g.Level == 0 { g.Level = defaultGzipLevel } diff --git a/modules/caddyhttp/encode/zstd/zstd.go b/modules/caddyhttp/encode/zstd/zstd.go index b5a0299d1ae..7a4b2e9dd87 100644 --- a/modules/caddyhttp/encode/zstd/zstd.go +++ b/modules/caddyhttp/encode/zstd/zstd.go @@ -38,7 +38,7 @@ func (Zstd) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. -func (z *Zstd) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (z *Zstd) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } diff --git a/modules/caddyhttp/fileserver/command.go b/modules/caddyhttp/fileserver/command.go index fb145cb06ca..5dd70083171 100644 --- a/modules/caddyhttp/fileserver/command.go +++ b/modules/caddyhttp/fileserver/command.go @@ -131,12 +131,12 @@ func cmdFileServer(fs caddycmd.Flags) (int, error) { Servers: map[string]*caddyhttp.Server{"static": server}, } - var false bool + var falseBool bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ - Persist: &false, + Persist: &falseBool, }, }, AppsRaw: caddy.ModuleMap{ diff --git a/modules/caddyhttp/fileserver/matcher.go b/modules/caddyhttp/fileserver/matcher.go index c8f5b226e90..2619d4f9d57 100644 --- a/modules/caddyhttp/fileserver/matcher.go +++ b/modules/caddyhttp/fileserver/matcher.go @@ -181,7 +181,7 @@ func (MatchFile) CELLibrary(ctx caddy.Context) (cel.Library, error) { root = values["root"][0] } - var try_policy string + var tryPolicy string if len(values["try_policy"]) > 0 { root = values["try_policy"][0] } @@ -189,7 +189,7 @@ func (MatchFile) CELLibrary(ctx caddy.Context) (cel.Library, error) { m := MatchFile{ Root: root, TryFiles: values["try_files"], - TryPolicy: try_policy, + TryPolicy: tryPolicy, SplitPath: values["split_path"], } diff --git a/modules/caddyhttp/http2listener.go b/modules/caddyhttp/http2listener.go index 51b356a7779..7a3634e9701 100644 --- a/modules/caddyhttp/http2listener.go +++ b/modules/caddyhttp/http2listener.go @@ -40,7 +40,7 @@ func (h *http2Listener) Accept() (net.Conn, error) { if csc, ok := conn.(connectionStateConn); ok { // *tls.Conn will return empty string because it's only populated after handshake is complete if csc.ConnectionState().NegotiatedProtocol == http2.NextProtoTLS { - go h.serveHttp2(csc) + go h.serveHTTP2(csc) continue } } @@ -49,7 +49,7 @@ func (h *http2Listener) Accept() (net.Conn, error) { } } -func (h *http2Listener) serveHttp2(csc connectionStateConn) { +func (h *http2Listener) serveHTTP2(csc connectionStateConn) { atomic.AddUint64(&h.cnt, 1) h.runHook(csc, http.StateNew) defer func() { diff --git a/modules/caddyhttp/httpredirectlistener.go b/modules/caddyhttp/httpredirectlistener.go index 3ff79ff8c91..e75969baf49 100644 --- a/modules/caddyhttp/httpredirectlistener.go +++ b/modules/caddyhttp/httpredirectlistener.go @@ -51,7 +51,7 @@ func (HTTPRedirectListenerWrapper) CaddyModule() caddy.ModuleInfo { } } -func (h *HTTPRedirectListenerWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (h *HTTPRedirectListenerWrapper) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } diff --git a/modules/caddyhttp/ip_range.go b/modules/caddyhttp/ip_range.go index 6b03ef75196..65e2336e56b 100644 --- a/modules/caddyhttp/ip_range.go +++ b/modules/caddyhttp/ip_range.go @@ -69,7 +69,7 @@ func (StaticIPRange) CaddyModule() caddy.ModuleInfo { } } -func (s *StaticIPRange) Provision(ctx caddy.Context) error { +func (s *StaticIPRange) Provision(_ caddy.Context) error { for _, str := range s.Ranges { prefix, err := CIDRExpressionToPrefix(str) if err != nil { @@ -86,16 +86,16 @@ func (s *StaticIPRange) GetIPRanges(_ *http.Request) []netip.Prefix { } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. -func (f *StaticIPRange) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (s *StaticIPRange) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if !d.Next() { return nil } for d.NextArg() { if d.Val() == "private_ranges" { - f.Ranges = append(f.Ranges, PrivateRangesCIDR()...) + s.Ranges = append(s.Ranges, PrivateRangesCIDR()...) continue } - f.Ranges = append(f.Ranges, d.Val()) + s.Ranges = append(s.Ranges, d.Val()) } return nil } diff --git a/modules/caddyhttp/proxyprotocol/listenerwrapper.go b/modules/caddyhttp/proxyprotocol/listenerwrapper.go index f404c06fe51..6b6f1165d61 100644 --- a/modules/caddyhttp/proxyprotocol/listenerwrapper.go +++ b/modules/caddyhttp/proxyprotocol/listenerwrapper.go @@ -43,7 +43,7 @@ type ListenerWrapper struct { } // Provision sets up the listener wrapper. -func (pp *ListenerWrapper) Provision(ctx caddy.Context) error { +func (pp *ListenerWrapper) Provision(_ caddy.Context) error { rules := make([]proxyprotocol.Rule, 0, len(pp.Allow)) for _, s := range pp.Allow { _, n, err := net.ParseCIDR(s) diff --git a/modules/caddyhttp/reverseproxy/healthchecks.go b/modules/caddyhttp/reverseproxy/healthchecks.go index 1b4f2d05534..e70264ee5f4 100644 --- a/modules/caddyhttp/reverseproxy/healthchecks.go +++ b/modules/caddyhttp/reverseproxy/healthchecks.go @@ -107,7 +107,7 @@ type ActiveHealthChecks struct { } // Provision ensures that a is set up properly before use. -func (a *ActiveHealthChecks) Provision(ctx caddy.Context, h *Handler) error { +func (a *ActiveHealthChecks) Provision(_ caddy.Context, h *Handler) error { if !a.IsEnabled() { return nil } diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index 249326dd932..b4760304ad8 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -629,7 +629,7 @@ func (h Handler) prepareRequest(req *http.Request, repl *caddy.Replacer) (*http. if err != nil { // OK; probably didn't have a port addr, err := netip.ParseAddr(address) - if err != nil { + if err != nil { //nolint:revive // Doesn't seem like a valid ip address at all } else { // Ok, only the port was missing diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index d3dad3859f1..de5a35df56a 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -62,7 +62,7 @@ func (RandomSelection) CaddyModule() caddy.ModuleInfo { } // Select returns an available host, if any. -func (r RandomSelection) Select(pool UpstreamPool, request *http.Request, _ http.ResponseWriter) *Upstream { +func (r RandomSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { return selectRandomHost(pool) } @@ -119,7 +119,7 @@ func (r *WeightedRoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) } // Provision sets up r. -func (r *WeightedRoundRobinSelection) Provision(ctx caddy.Context) error { +func (r *WeightedRoundRobinSelection) Provision(_ caddy.Context) error { for _, weight := range r.Weights { r.totalWeight += weight } @@ -194,7 +194,7 @@ func (r *RandomChoiceSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error } // Provision sets up r. -func (r *RandomChoiceSelection) Provision(ctx caddy.Context) error { +func (r *RandomChoiceSelection) Provision(_ caddy.Context) error { if r.Choose == 0 { r.Choose = 2 } diff --git a/modules/caddyhttp/routes.go b/modules/caddyhttp/routes.go index 9be3d01a463..9db4f252044 100644 --- a/modules/caddyhttp/routes.go +++ b/modules/caddyhttp/routes.go @@ -311,7 +311,7 @@ func wrapRoute(route Route) Middleware { // we need to pull this particular MiddlewareHandler // pointer into its own stack frame to preserve it so it // won't be overwritten in future loop iterations. -func wrapMiddleware(ctx caddy.Context, mh MiddlewareHandler, metrics *Metrics) Middleware { +func wrapMiddleware(_ caddy.Context, mh MiddlewareHandler, metrics *Metrics) Middleware { handlerToUse := mh if metrics != nil { // wrap the middleware with metrics instrumentation diff --git a/modules/caddyhttp/staticerror.go b/modules/caddyhttp/staticerror.go index 7cf1a3e9543..c30610f0807 100644 --- a/modules/caddyhttp/staticerror.go +++ b/modules/caddyhttp/staticerror.go @@ -95,7 +95,7 @@ func (e *StaticError) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } -func (e StaticError) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler) error { +func (e StaticError) ServeHTTP(_ http.ResponseWriter, r *http.Request, _ Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) statusCode := http.StatusInternalServerError diff --git a/modules/caddyhttp/templates/templates.go b/modules/caddyhttp/templates/templates.go index 65359d9e9aa..1caa3d9976e 100644 --- a/modules/caddyhttp/templates/templates.go +++ b/modules/caddyhttp/templates/templates.go @@ -324,7 +324,7 @@ func (Templates) CaddyModule() caddy.ModuleInfo { } // Provision provisions t. -func (t *Templates) Provision(ctx caddy.Context) error { +func (t *Templates) Provision(_ caddy.Context) error { fnModInfos := caddy.GetModules("http.handlers.templates.functions") customFuncs := make([]template.FuncMap, 0, len(fnModInfos)) for _, modInfo := range fnModInfos { diff --git a/modules/caddytls/certmanagers.go b/modules/caddytls/certmanagers.go index ad26468a9dd..d271083c8f2 100644 --- a/modules/caddytls/certmanagers.go +++ b/modules/caddytls/certmanagers.go @@ -118,7 +118,7 @@ func (hcg *HTTPCertGetter) Provision(ctx caddy.Context) error { return nil } -func (hcg HTTPCertGetter) GetCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (*tls.Certificate, error) { +func (hcg HTTPCertGetter) GetCertificate(_ context.Context, hello *tls.ClientHelloInfo) (*tls.Certificate, error) { sigs := make([]string, len(hello.SignatureSchemes)) for i, sig := range hello.SignatureSchemes { sigs[i] = fmt.Sprintf("%x", uint16(sig)) // you won't believe what %x uses if the val is a Stringer diff --git a/modules/caddytls/internalissuer.go b/modules/caddytls/internalissuer.go index 1cf2461ab7c..68de0be5e69 100644 --- a/modules/caddytls/internalissuer.go +++ b/modules/caddytls/internalissuer.go @@ -100,7 +100,7 @@ func (iss InternalIssuer) IssuerKey() string { } // Issue issues a certificate to satisfy the CSR. -func (iss InternalIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { +func (iss InternalIssuer) Issue(_ context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { // prepare the signing authority authCfg := caddypki.AuthorityConfig{ SignWithRoot: iss.SignWithRoot, diff --git a/modules/caddytls/tls.go b/modules/caddytls/tls.go index 02d5aae756b..3beedd6beed 100644 --- a/modules/caddytls/tls.go +++ b/modules/caddytls/tls.go @@ -609,7 +609,7 @@ func (t *TLS) storageCleanInterval() time.Duration { } // onEvent translates CertMagic events into Caddy events then dispatches them. -func (t *TLS) onEvent(ctx context.Context, eventName string, data map[string]any) error { +func (t *TLS) onEvent(_ context.Context, eventName string, data map[string]any) error { evt := t.events.Emit(t.ctx, eventName, data) return evt.Aborted } diff --git a/modules/logging/filewriter.go b/modules/logging/filewriter.go index 11c051d783f..a8b852ba954 100644 --- a/modules/logging/filewriter.go +++ b/modules/logging/filewriter.go @@ -73,7 +73,7 @@ func (FileWriter) CaddyModule() caddy.ModuleInfo { } // Provision sets up the module -func (fw *FileWriter) Provision(ctx caddy.Context) error { +func (fw *FileWriter) Provision(caddy.Context) error { // Replace placeholder in filename repl := caddy.NewReplacer() filename, err := repl.ReplaceOrErr(fw.Filename, true, true) diff --git a/modules/logging/filters.go b/modules/logging/filters.go index 1ef2bdf5cf0..0ea19adc480 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -62,7 +62,7 @@ func (DeleteFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (DeleteFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (DeleteFilter) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } @@ -93,7 +93,7 @@ func (HashFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (f *HashFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (f *HashFilter) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } @@ -198,7 +198,7 @@ func (m *IPMaskFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision parses m's IP masks, from integers. -func (m *IPMaskFilter) Provision(ctx caddy.Context) error { +func (m *IPMaskFilter) Provision(_ caddy.Context) error { parseRawToMask := func(rawField int, bitLen int) net.IPMask { if rawField == 0 { return nil @@ -566,7 +566,7 @@ func (f *RegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision compiles m's regexp. -func (f *RegexpFilter) Provision(ctx caddy.Context) error { +func (f *RegexpFilter) Provision(_ caddy.Context) error { r, err := regexp.Compile(f.RawRegexp) if err != nil { return err diff --git a/modules/logging/netwriter.go b/modules/logging/netwriter.go index 1939cb711dc..844f2add316 100644 --- a/modules/logging/netwriter.go +++ b/modules/logging/netwriter.go @@ -57,7 +57,7 @@ func (NetWriter) CaddyModule() caddy.ModuleInfo { } // Provision sets up the module. -func (nw *NetWriter) Provision(ctx caddy.Context) error { +func (nw *NetWriter) Provision(_ caddy.Context) error { repl := caddy.NewReplacer() address, err := repl.ReplaceOrErr(nw.Address, true, true) if err != nil { diff --git a/modules/logging/nopencoder.go b/modules/logging/nopencoder.go index 62c1f787fa9..68f748f9bbe 100644 --- a/modules/logging/nopencoder.go +++ b/modules/logging/nopencoder.go @@ -26,79 +26,79 @@ type nopEncoder struct{} // AddArray is part of the zapcore.ObjectEncoder interface. // Array elements do not get filtered. -func (nopEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { return nil } +func (nopEncoder) AddArray(_ string, _ zapcore.ArrayMarshaler) error { return nil } // AddObject is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { return nil } +func (nopEncoder) AddObject(_ string, _ zapcore.ObjectMarshaler) error { return nil } // AddBinary is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddBinary(key string, value []byte) {} +func (nopEncoder) AddBinary(_ string, _ []byte) {} // AddByteString is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddByteString(key string, value []byte) {} +func (nopEncoder) AddByteString(_ string, _ []byte) {} // AddBool is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddBool(key string, value bool) {} +func (nopEncoder) AddBool(_ string, _ bool) {} // AddComplex128 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddComplex128(key string, value complex128) {} +func (nopEncoder) AddComplex128(_ string, _ complex128) {} // AddComplex64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddComplex64(key string, value complex64) {} +func (nopEncoder) AddComplex64(_ string, _ complex64) {} // AddDuration is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddDuration(key string, value time.Duration) {} +func (nopEncoder) AddDuration(_ string, _ time.Duration) {} // AddFloat64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddFloat64(key string, value float64) {} +func (nopEncoder) AddFloat64(_ string, _ float64) {} // AddFloat32 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddFloat32(key string, value float32) {} +func (nopEncoder) AddFloat32(_ string, _ float32) {} // AddInt is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt(key string, value int) {} +func (nopEncoder) AddInt(_ string, _ int) {} // AddInt64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt64(key string, value int64) {} +func (nopEncoder) AddInt64(_ string, _ int64) {} // AddInt32 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt32(key string, value int32) {} +func (nopEncoder) AddInt32(_ string, _ int32) {} // AddInt16 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt16(key string, value int16) {} +func (nopEncoder) AddInt16(_ string, _ int16) {} // AddInt8 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt8(key string, value int8) {} +func (nopEncoder) AddInt8(_ string, _ int8) {} // AddString is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddString(key, value string) {} +func (nopEncoder) AddString(_, _ string) {} // AddTime is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddTime(key string, value time.Time) {} +func (nopEncoder) AddTime(_ string, _ time.Time) {} // AddUint is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint(key string, value uint) {} +func (nopEncoder) AddUint(_ string, _ uint) {} // AddUint64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint64(key string, value uint64) {} +func (nopEncoder) AddUint64(_ string, _ uint64) {} // AddUint32 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint32(key string, value uint32) {} +func (nopEncoder) AddUint32(_ string, _ uint32) {} // AddUint16 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint16(key string, value uint16) {} +func (nopEncoder) AddUint16(_ string, _ uint16) {} // AddUint8 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint8(key string, value uint8) {} +func (nopEncoder) AddUint8(_ string, _ uint8) {} // AddUintptr is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUintptr(key string, value uintptr) {} +func (nopEncoder) AddUintptr(_ string, _ uintptr) {} // AddReflected is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddReflected(key string, value any) error { return nil } +func (nopEncoder) AddReflected(_ string, _ any) error { return nil } // OpenNamespace is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) OpenNamespace(key string) {} +func (nopEncoder) OpenNamespace(_ string) {} // Clone is part of the zapcore.ObjectEncoder interface. // We don't use it as of Oct 2019 (v2 beta 7), I'm not @@ -106,7 +106,7 @@ func (nopEncoder) OpenNamespace(key string) {} func (ne nopEncoder) Clone() zapcore.Encoder { return ne } // EncodeEntry partially implements the zapcore.Encoder interface. -func (nopEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { +func (nopEncoder) EncodeEntry(_ zapcore.Entry, _ []zapcore.Field) (*buffer.Buffer, error) { return bufferpool.Get(), nil } diff --git a/modules/metrics/metrics.go b/modules/metrics/metrics.go index a9e0f0efa54..0fd6fe77d32 100644 --- a/modules/metrics/metrics.go +++ b/modules/metrics/metrics.go @@ -96,7 +96,7 @@ func (m *Metrics) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } -func (m Metrics) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { +func (m Metrics) ServeHTTP(w http.ResponseWriter, r *http.Request, _ caddyhttp.Handler) error { m.metricsHandler.ServeHTTP(w, r) return nil } From db5de9b962e2601df66004130b1d981e869355a8 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 21:02:52 +0800 Subject: [PATCH 11/31] enable thelper --- .golangci.yml | 2 +- caddytest/caddytest.go | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 976bb0a46ea..b97286e98b8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -31,6 +31,7 @@ linters: - prealloc - revive - staticcheck + - thelper - typecheck - unconvert - unused @@ -52,7 +53,6 @@ linters: # - godot # - godox # - goerr113 - # - gofumpt # - goheader # - golint # - gomnd diff --git a/caddytest/caddytest.go b/caddytest/caddytest.go index 9c170703c57..60964bd69f5 100644 --- a/caddytest/caddytest.go +++ b/caddytest/caddytest.go @@ -64,6 +64,7 @@ type Tester struct { // NewTester will create a new testing client with an attached cookie jar func NewTester(t *testing.T) *Tester { + t.Helper() jar, err := cookiejar.New(nil) if err != nil { t.Fatalf("failed to create cookiejar: %s", err) @@ -230,6 +231,7 @@ const initConfig = `{ // validateTestPrerequisites ensures the certificates are available in the // designated path and Caddy sub-process is running. func validateTestPrerequisites(t *testing.T) error { + t.Helper() // check certificates are found for _, certName := range Default.Certifcates { if _, err := os.Stat(getIntegrationDir() + certName); os.IsNotExist(err) { @@ -327,6 +329,7 @@ func CreateTestingTransport() *http.Transport { // AssertLoadError will load a config and expect an error func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) { + t.Helper() tc := NewTester(t) err := tc.initServer(rawConfig, configType) @@ -374,6 +377,7 @@ func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, e // CompareAdapt adapts a config and then compares it against an expected result func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string, expectedResponse string) bool { + t.Helper() cfgAdapter := caddyconfig.GetAdapter(adapterName) if cfgAdapter == nil { t.Logf("unrecognized config adapter '%s'", adapterName) @@ -433,6 +437,7 @@ func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string, // AssertAdapt adapts a config and then tests it against an expected result func AssertAdapt(t *testing.T, rawConfig string, adapterName string, expectedResponse string) { + t.Helper() ok := CompareAdapt(t, "Caddyfile", rawConfig, adapterName, expectedResponse) if !ok { t.Fail() @@ -442,6 +447,7 @@ func AssertAdapt(t *testing.T, rawConfig string, adapterName string, expectedRes // Generic request functions func applyHeaders(t *testing.T, req *http.Request, requestHeaders []string) { + t.Helper() requestContentType := "" for _, requestHeader := range requestHeaders { arr := strings.SplitAfterN(requestHeader, ":", 2) From ba34aa4770d79773ad853f76399cd305f8300b71 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 21:07:07 +0800 Subject: [PATCH 12/31] autofixes (golangci-lint run ./... --fix) --- caddytest/integration/stream_test.go | 3 ++- modules/logging/filters_test.go | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/caddytest/integration/stream_test.go b/caddytest/integration/stream_test.go index ef3ea498d33..8f24ddfc9af 100644 --- a/caddytest/integration/stream_test.go +++ b/caddytest/integration/stream_test.go @@ -13,9 +13,10 @@ import ( "testing" "time" - "github.com/caddyserver/caddy/v2/caddytest" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" + + "github.com/caddyserver/caddy/v2/caddytest" ) // (see https://github.com/caddyserver/caddy/issues/3556 for use case) diff --git a/modules/logging/filters_test.go b/modules/logging/filters_test.go index e9c3e77fea9..427e652a7d9 100644 --- a/modules/logging/filters_test.go +++ b/modules/logging/filters_test.go @@ -3,9 +3,10 @@ package logging import ( "testing" + "go.uber.org/zap/zapcore" + "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" - "go.uber.org/zap/zapcore" ) func TestIPMaskSingleValue(t *testing.T) { From 968dbc103a288b8c0f5d8931cc9d6b4a2a5ee831 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 21:16:34 +0800 Subject: [PATCH 13/31] further clean tests --- admin_test.go | 7 ++++-- caddyconfig/caddyfile/lexer_test.go | 1 + caddyconfig/caddyfile/parse_test.go | 5 ++-- caddytest/integration/stream_test.go | 2 ++ .../reverseproxy/fastcgi/client_test.go | 1 + modules/caddyhttp/rewrite/rewrite_test.go | 1 + .../caddyhttp/templates/tplcontext_test.go | 1 + modules/logging/filters_test.go | 25 +++++++++++++++---- 8 files changed, 34 insertions(+), 9 deletions(-) diff --git a/admin_test.go b/admin_test.go index 04aa8867fc3..634bb04d997 100644 --- a/admin_test.go +++ b/admin_test.go @@ -131,7 +131,7 @@ func TestUnsyncedConfigAccess(t *testing.T) { // TestLoadConcurrent exercises Load under concurrent conditions // and is most useful under test with `-race` enabled. -func TestLoadConcurrent(t *testing.T) { +func TestLoadConcurrent(_ *testing.T) { var wg sync.WaitGroup for i := 0; i < 100; i++ { @@ -194,6 +194,9 @@ func TestETags(t *testing.T) { func BenchmarkLoad(b *testing.B) { for i := 0; i < b.N; i++ { - Load(testCfg, true) + err := Load(testCfg, true) + if err != nil { + b.Fatal(err) + } } } diff --git a/caddyconfig/caddyfile/lexer_test.go b/caddyconfig/caddyfile/lexer_test.go index 801d81e2229..e81c0b7eb43 100644 --- a/caddyconfig/caddyfile/lexer_test.go +++ b/caddyconfig/caddyfile/lexer_test.go @@ -427,6 +427,7 @@ EOF same-line-arg } func lexerCompare(t *testing.T, n int, expected, actual []Token) { + t.Helper() if len(expected) != len(actual) { t.Fatalf("Test case %d: expected %d token(s) but got %d", n, len(expected), len(actual)) } diff --git a/caddyconfig/caddyfile/parse_test.go b/caddyconfig/caddyfile/parse_test.go index c4b8c1b9067..675accec021 100644 --- a/caddyconfig/caddyfile/parse_test.go +++ b/caddyconfig/caddyfile/parse_test.go @@ -437,7 +437,7 @@ func TestRecursiveImport(t *testing.T) { err = os.WriteFile(recursiveFile1, []byte( `localhost dir1 - import `+recursiveFile2), 0o644) + import `+recursiveFile2), 0o600) if err != nil { t.Fatal(err) } @@ -491,7 +491,7 @@ func TestDirectiveImport(t *testing.T) { } err = os.WriteFile(directiveFile, []byte(`prop1 1 - prop2 2`), 0o644) + prop2 2`), 0o600) if err != nil { t.Fatal(err) } @@ -780,6 +780,7 @@ func TestSnippets(t *testing.T) { } func writeStringToTempFileOrDie(t *testing.T, str string) (pathToFile string) { + t.Helper() file, err := os.CreateTemp("", t.Name()) if err != nil { panic(err) // get a stack trace so we know where this was called from. diff --git a/caddytest/integration/stream_test.go b/caddytest/integration/stream_test.go index 8f24ddfc9af..e67b61c13f6 100644 --- a/caddytest/integration/stream_test.go +++ b/caddytest/integration/stream_test.go @@ -151,6 +151,7 @@ func TestH2ToH2CStream(t *testing.T) { } func testH2ToH2CStreamServeH2C(t *testing.T) *http.Server { + t.Helper() h2s := &http2.Server{} handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rstring, err := httputil.DumpRequest(r, false) @@ -360,6 +361,7 @@ func TestH2ToH1ChunkedResponse(t *testing.T) { } func testH2ToH1ChunkedResponseServeH1(t *testing.T) *http.Server { + t.Helper() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Host != "127.0.0.1:9443" { t.Errorf("r.Host doesn't match, %v!", r.Host) diff --git a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go index 5568a49c468..0f9f274be17 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go @@ -210,6 +210,7 @@ func generateRandFile(size int) (p string, m string) { } func DisabledTest(t *testing.T) { + t.Helper() // TODO: test chunked reader globalt = t diff --git a/modules/caddyhttp/rewrite/rewrite_test.go b/modules/caddyhttp/rewrite/rewrite_test.go index aaa142bc23e..605c4acf849 100644 --- a/modules/caddyhttp/rewrite/rewrite_test.go +++ b/modules/caddyhttp/rewrite/rewrite_test.go @@ -388,6 +388,7 @@ func TestRewrite(t *testing.T) { } func newRequest(t *testing.T, method, uri string) *http.Request { + t.Helper() req, err := http.NewRequest(method, uri, nil) if err != nil { t.Fatalf("error creating request: %v", err) diff --git a/modules/caddyhttp/templates/tplcontext_test.go b/modules/caddyhttp/templates/tplcontext_test.go index 6b8d2a7b18d..94997bcd30b 100644 --- a/modules/caddyhttp/templates/tplcontext_test.go +++ b/modules/caddyhttp/templates/tplcontext_test.go @@ -650,6 +650,7 @@ func TestHumanize(t *testing.T) { } func getContextOrFail(t *testing.T) TemplateContext { + t.Helper() tplContext, err := initTestContext() t.Cleanup(func() { os.RemoveAll(string(tplContext.Root.(http.Dir))) diff --git a/modules/logging/filters_test.go b/modules/logging/filters_test.go index 427e652a7d9..7870dbbb6d6 100644 --- a/modules/logging/filters_test.go +++ b/modules/logging/filters_test.go @@ -11,7 +11,10 @@ import ( func TestIPMaskSingleValue(t *testing.T) { f := IPMaskFilter{IPv4MaskRaw: 16, IPv6MaskRaw: 32} - f.Provision(caddy.Context{}) + err := f.Provision(caddy.Context{}) + if err != nil { + t.Fatalf("provisioning failed: %v", err) + } out := f.Filter(zapcore.Field{String: "255.255.255.255"}) if out.String != "255.255.0.0" { @@ -31,7 +34,10 @@ func TestIPMaskSingleValue(t *testing.T) { func TestIPMaskCommaValue(t *testing.T) { f := IPMaskFilter{IPv4MaskRaw: 16, IPv6MaskRaw: 32} - f.Provision(caddy.Context{}) + err := f.Provision(caddy.Context{}) + if err != nil { + t.Fatalf("provisioning failed: %v", err) + } out := f.Filter(zapcore.Field{String: "255.255.255.255, 244.244.244.244"}) if out.String != "255.255.0.0, 244.244.0.0" { @@ -51,7 +57,10 @@ func TestIPMaskCommaValue(t *testing.T) { func TestIPMaskMultiValue(t *testing.T) { f := IPMaskFilter{IPv4MaskRaw: 16, IPv6MaskRaw: 32} - f.Provision(caddy.Context{}) + err := f.Provision(caddy.Context{}) + if err != nil { + t.Fatalf("provisioning failed: %v", err) + } out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{ "255.255.255.255", @@ -156,7 +165,10 @@ func TestValidateCookieFilter(t *testing.T) { func TestRegexpFilterSingleValue(t *testing.T) { f := RegexpFilter{RawRegexp: `secret`, Value: "REDACTED"} - f.Provision(caddy.Context{}) + err := f.Provision(caddy.Context{}) + if err != nil { + t.Fatalf("provisioning failed: %v", err) + } out := f.Filter(zapcore.Field{String: "foo-secret-bar"}) if out.String != "foo-REDACTED-bar" { @@ -166,7 +178,10 @@ func TestRegexpFilterSingleValue(t *testing.T) { func TestRegexpFilterMultiValue(t *testing.T) { f := RegexpFilter{RawRegexp: `secret`, Value: "REDACTED"} - f.Provision(caddy.Context{}) + err := f.Provision(caddy.Context{}) + if err != nil { + t.Fatalf("provisioning failed: %v", err) + } out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{"foo-secret-bar", "bar-secret-foo"}}) arr, ok := out.Interface.(caddyhttp.LoggableStringArray) From 23588526375a57cdf700be03cb12dfd20272df73 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sun, 6 Aug 2023 22:27:38 +0800 Subject: [PATCH 14/31] continue linting tests --- caddytest/integration/autohttps_test.go | 10 +++++++--- caddytest/integration/caddyfile_test.go | 3 ++- modules/caddyhttp/reverseproxy/fastcgi/client_test.go | 4 ++++ modules/caddyhttp/staticresp_test.go | 1 + 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/caddytest/integration/autohttps_test.go b/caddytest/integration/autohttps_test.go index 1dbdbcee209..f4195f218ea 100644 --- a/caddytest/integration/autohttps_test.go +++ b/caddytest/integration/autohttps_test.go @@ -20,7 +20,8 @@ func TestAutoHTTPtoHTTPSRedirectsImplicitPort(t *testing.T) { respond "Yahaha! You found me!" `, "caddyfile") - tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) + resp := tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) + resp.Body.Close() } func TestAutoHTTPtoHTTPSRedirectsExplicitPortSameAsHTTPSPort(t *testing.T) { @@ -36,7 +37,9 @@ func TestAutoHTTPtoHTTPSRedirectsExplicitPortSameAsHTTPSPort(t *testing.T) { respond "Yahaha! You found me!" `, "caddyfile") - tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) + resp := tester.AssertRedirect("http://localhost:9080/", "https://localhost/", http.StatusPermanentRedirect) + resp.Body.Close() + resp.Body.Close() } func TestAutoHTTPtoHTTPSRedirectsExplicitPortDifferentFromHTTPSPort(t *testing.T) { @@ -52,7 +55,8 @@ func TestAutoHTTPtoHTTPSRedirectsExplicitPortDifferentFromHTTPSPort(t *testing.T respond "Yahaha! You found me!" `, "caddyfile") - tester.AssertRedirect("http://localhost:9080/", "https://localhost:1234/", http.StatusPermanentRedirect) + resp := tester.AssertRedirect("http://localhost:9080/", "https://localhost:1234/", http.StatusPermanentRedirect) + resp.Body.Close() } func TestAutoHTTPRedirectsWithHTTPListenerFirstInAddresses(t *testing.T) { diff --git a/caddytest/integration/caddyfile_test.go b/caddytest/integration/caddyfile_test.go index 2eae704e2e1..fcc4216a72b 100644 --- a/caddytest/integration/caddyfile_test.go +++ b/caddytest/integration/caddyfile_test.go @@ -128,5 +128,6 @@ func TestReplIndex(t *testing.T) { `, "caddyfile") // act and assert - tester.AssertGetResponse("http://localhost:9080/", 200, "") + resp, _ := tester.AssertGetResponse("http://localhost:9080/", 200, "") + resp.Body.Close() } diff --git a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go index 0f9f274be17..256ce414b31 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/client_test.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/client_test.go @@ -134,6 +134,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ length = len(data) rd := bytes.NewReader(data) resp, err = fcgi.Post(fcgiParams, "", "", rd, int64(rd.Len())) + resp.Body.Close() } else if len(posts) > 0 { values := url.Values{} for k, v := range posts { @@ -141,9 +142,11 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ length += len(k) + 2 + len(v) } resp, err = fcgi.PostForm(fcgiParams, values) + resp.Body.Close() } else { rd := bytes.NewReader(data) resp, err = fcgi.Get(fcgiParams, rd, int64(rd.Len())) + resp.Body.Close() } default: @@ -158,6 +161,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[ length += len(k) + int(fi.Size()) } resp, err = fcgi.PostFile(fcgiParams, values, files) + resp.Body.Close() } if err != nil { diff --git a/modules/caddyhttp/staticresp_test.go b/modules/caddyhttp/staticresp_test.go index 5844f43f354..554c7f2a7f7 100644 --- a/modules/caddyhttp/staticresp_test.go +++ b/modules/caddyhttp/staticresp_test.go @@ -44,6 +44,7 @@ func TestStaticResponseHandler(t *testing.T) { } resp := w.Result() + resp.Body.Close() respBody, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusNotFound { From 273455cfb3f61047e7ed85b99009da9a6c014986 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 00:51:43 +0800 Subject: [PATCH 15/31] update test lints --- .golangci.yml | 74 ++++++++++++++++++- caddyconfig/caddyfile/formatter.go | 4 +- modules/caddyhttp/logging.go | 4 +- .../caddyhttp/reverseproxy/fastcgi/record.go | 10 +-- modules/caddyhttp/reverseproxy/upstreams.go | 4 +- modules/caddypki/adminapi.go | 6 +- usagepool.go | 4 +- 7 files changed, 86 insertions(+), 20 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index e9b04172fa6..15c976bc7fe 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,71 @@ linters-settings: + revive: + enable-all-rules: true + # Do NOT whine about the following, full explanation found in: + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#description-of-available-rules + rules: + - name: use-any + disabled: true + - name: if-return + disabled: true + - name: max-public-structs + disabled: true + - name: cognitive-complexity + disabled: true + - name: argument-limit + disabled: true + - name: cyclomatic + disabled: true + - name: file-header + disabled: true + - name: function-length + disabled: true + - name: function-result-limit + disabled: true + - name: line-length-limit + disabled: true + - name: flag-parameter + disabled: true + - name: add-constant + disabled: true + - name: empty-lines + disabled: true + - name: banned-characters + disabled: true + - name: deep-exit + disabled: true + - name: confusing-results + disabled: true + - name: unused-parameter + disabled: true + - name: modifies-value-receiver + disabled: true + - name: early-return + disabled: true + - name: unnecessary-stmt + disabled: true + - name: defer + disabled: true + - name: nested-structs + disabled: true + - name: unhandled-error + disabled: false + # Arguments added below do not trigger the rule. + arguments: + - 'fmt.Printf' + - 'c.Conn.Close' + - 'w.Write' + - 'server.Serve' + - 'http.ListenAndServe' + - 'conn.Close' + - 'sb.WriteString' + - 'buf.WriteString' + - 'out.WriteRune' + - 'fmt.Print' + - 'fmt.Println' + - 'fmt.Printf' + - 'fmt.Fprint' + - 'sb.WriteRune' errcheck: ignore: fmt:.*,go.uber.org/zap/zapcore:^Add.* ignoretests: true @@ -27,7 +94,6 @@ linters: - gosimple - govet - ineffassign - - nakedret - misspell - prealloc - revive @@ -81,7 +147,7 @@ run: # concurrency: 4 # explicitly omit this value to fully utilize available resources. deadline: 5m issues-exit-code: 1 - tests: true + tests: false # output configuration options output: @@ -90,8 +156,8 @@ output: print-linter-name: true issues: - max-issues-per-linter: 10000 - max-same-issues: 10000 + max-issues-per-linter: 0 + max-same-issues: 0 exclude-rules: # we aren't calling unknown URL - text: 'G107' # G107: Url provided to HTTP request as taint input diff --git a/caddyconfig/caddyfile/formatter.go b/caddyconfig/caddyfile/formatter.go index 0614ab607b7..814185c3c4e 100644 --- a/caddyconfig/caddyfile/formatter.go +++ b/caddyconfig/caddyfile/formatter.go @@ -125,13 +125,13 @@ func Format(input []byte) []byte { spacePrior := space space = false - ////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////// // I find it helpful to think of the formatting loop in two // main sections; by the time we reach this point, we // know we are in a "regular" part of the file: we know // the character is not a space, not in a literal segment // like a comment or quoted, it's not escaped, etc. - ////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////// if ch == '#' { comment = true diff --git a/modules/caddyhttp/logging.go b/modules/caddyhttp/logging.go index 8ecc49a63db..298dd2859ff 100644 --- a/modules/caddyhttp/logging.go +++ b/modules/caddyhttp/logging.go @@ -134,11 +134,11 @@ func errLogValues(err error) (status int, msg string, fields []zapcore.Field) { zap.String("err_id", handlerErr.ID), zap.String("err_trace", handlerErr.Trace), } - return + return status, msg, fields } status = http.StatusInternalServerError msg = err.Error() - return + return status, msg, fields } // ExtraLogFields is a list of extra fields to log with every request. diff --git a/modules/caddyhttp/reverseproxy/fastcgi/record.go b/modules/caddyhttp/reverseproxy/fastcgi/record.go index 46c1f17bb4d..9132ca64792 100644 --- a/modules/caddyhttp/reverseproxy/fastcgi/record.go +++ b/modules/caddyhttp/reverseproxy/fastcgi/record.go @@ -30,23 +30,23 @@ func (rec *record) fill(r io.Reader) (err error) { rec.lr.N = rec.padding rec.lr.R = r if _, err = io.Copy(io.Discard, rec); err != nil { - return + return err } if err = binary.Read(r, binary.BigEndian, &rec.h); err != nil { - return + return err } if rec.h.Version != 1 { err = errors.New("fcgi: invalid header version") - return + return err } if rec.h.Type == EndRequest { err = io.EOF - return + return err } rec.lr.N = int64(rec.h.ContentLength) rec.padding = int64(rec.h.PaddingLength) - return + return nil } func (rec *record) Read(p []byte) (n int, err error) { diff --git a/modules/caddyhttp/reverseproxy/upstreams.go b/modules/caddyhttp/reverseproxy/upstreams.go index 8bdc60dd5ff..b4881fcd0b7 100644 --- a/modules/caddyhttp/reverseproxy/upstreams.go +++ b/modules/caddyhttp/reverseproxy/upstreams.go @@ -189,12 +189,12 @@ func (su SRVUpstreams) expandedAddr(r *http.Request) (addr, service, proto, name name = repl.ReplaceAll(su.Name, "") if su.Service == "" && su.Proto == "" { addr = name - return + return addr, service, proto, name } service = repl.ReplaceAll(su.Service, "") proto = repl.ReplaceAll(su.Proto, "") addr = su.formattedAddr(service, proto, name) - return + return addr, service, proto, name } // formattedAddr the RFC 2782 representation of the SRV domain, in diff --git a/modules/caddypki/adminapi.go b/modules/caddypki/adminapi.go index 435af349a4a..9cd4a2554ec 100644 --- a/modules/caddypki/adminapi.go +++ b/modules/caddypki/adminapi.go @@ -217,13 +217,13 @@ func (a *adminAPI) getCAFromAPIRequestPath(r *http.Request) (*CA, error) { func rootAndIntermediatePEM(ca *CA) (root, inter []byte, err error) { root, err = pemEncodeCert(ca.RootCertificate().Raw) if err != nil { - return + return nil, nil, err } inter, err = pemEncodeCert(ca.IntermediateCertificate().Raw) if err != nil { - return + return nil, nil, err } - return + return root, inter, nil } // caInfo is the response structure for the CA info API endpoint. diff --git a/usagepool.go b/usagepool.go index ea37b07f61e..7c019b537e1 100644 --- a/usagepool.go +++ b/usagepool.go @@ -134,7 +134,7 @@ func (up *UsagePool) LoadOrStore(key, val any) (value any, loaded bool) { up.Unlock() value = val } - return + return value, loaded } // Range iterates the pool similarly to how sync.Map.Range() does: @@ -191,7 +191,7 @@ func (up *UsagePool) Delete(key any) (deleted bool, err error) { upv.value, upv.refs)) } } - return + return deleted, err } // References returns the number of references (count of usages) to a From 2bf86fa84fbe3fade8c7f4ae5a848712cd1aa593 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 00:59:52 +0800 Subject: [PATCH 16/31] unused-recievers --- .golangci.yml | 1 + admin.go | 2 +- caddyconfig/httpcaddyfile/addresses.go | 4 ++-- caddyconfig/httpcaddyfile/directives.go | 2 +- caddyconfig/httpcaddyfile/httptype.go | 2 +- caddyconfig/httpcaddyfile/pkiapp.go | 2 +- caddyconfig/httpcaddyfile/tlsapp.go | 2 +- listeners.go | 4 ++-- logging.go | 2 +- modules/caddyevents/app.go | 2 +- modules/caddyhttp/autohttps.go | 2 +- modules/caddyhttp/celmatcher.go | 2 +- modules/caddyhttp/encode/zstd/zstd.go | 4 ++-- modules/caddyhttp/fileserver/browse.go | 2 +- modules/caddyhttp/httpredirectlistener.go | 4 ++-- modules/caddyhttp/push/handler.go | 2 +- modules/caddyhttp/requestbody/requestbody.go | 2 +- modules/caddyhttp/reverseproxy/reverseproxy.go | 8 ++++---- .../caddyhttp/reverseproxy/selectionpolicies.go | 16 ++++++++-------- modules/caddyhttp/reverseproxy/streaming.go | 9 ++++----- modules/caddyhttp/templates/tplcontext.go | 4 ++-- modules/caddyhttp/tracing/tracer.go | 6 +++--- modules/caddypki/pki.go | 2 +- modules/caddytls/certmanagers.go | 4 ++-- modules/caddytls/sessiontickets.go | 2 +- modules/logging/filters.go | 4 ++-- modules/metrics/adminmetrics.go | 2 +- 27 files changed, 49 insertions(+), 49 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 15c976bc7fe..fb8d42867bd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -58,6 +58,7 @@ linters-settings: - 'server.Serve' - 'http.ListenAndServe' - 'conn.Close' + - 'w.buf.Write' - 'sb.WriteString' - 'buf.WriteString' - 'out.WriteRune' diff --git a/admin.go b/admin.go index 5c5eee733ab..131f18fff83 100644 --- a/admin.go +++ b/admin.go @@ -915,7 +915,7 @@ func (h adminHandler) checkOrigin(r *http.Request) (string, error) { return origin.String(), nil } -func (h adminHandler) getOrigin(r *http.Request) (string, *url.URL) { +func (adminHandler) getOrigin(r *http.Request) (string, *url.URL) { origin := r.Header.Get("Origin") if origin == "" { origin = r.Header.Get("Referer") diff --git a/caddyconfig/httpcaddyfile/addresses.go b/caddyconfig/httpcaddyfile/addresses.go index b6a8ac07254..a441b607b4b 100644 --- a/caddyconfig/httpcaddyfile/addresses.go +++ b/caddyconfig/httpcaddyfile/addresses.go @@ -150,7 +150,7 @@ func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBloc // entries are deleted from the addrToServerBlocks map. Essentially, each pairing (each // association from multiple addresses to multiple server blocks; i.e. each element of // the returned slice) becomes a server definition in the output JSON. -func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]serverBlock) []sbAddrAssociation { +func (*ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]serverBlock) []sbAddrAssociation { sbaddrs := make([]sbAddrAssociation, 0, len(addrToServerBlocks)) for addr, sblocks := range addrToServerBlocks { // we start with knowing that at least this address @@ -188,7 +188,7 @@ func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]se // listenerAddrsForServerBlockKey essentially converts the Caddyfile // site addresses to Caddy listener addresses for each server block. -func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string, +func (*ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string, options map[string]any, ) ([]string, error) { addr, err := ParseAddress(key) diff --git a/caddyconfig/httpcaddyfile/directives.go b/caddyconfig/httpcaddyfile/directives.go index 13229ed5cd4..ca2004f2d35 100644 --- a/caddyconfig/httpcaddyfile/directives.go +++ b/caddyconfig/httpcaddyfile/directives.go @@ -272,7 +272,7 @@ func (h Helper) GroupRoutes(vals []ConfigValue) { // NewBindAddresses returns config values relevant to adding // listener bind addresses to the config. -func (h Helper) NewBindAddresses(addrs []string) []ConfigValue { +func (Helper) NewBindAddresses(addrs []string) []ConfigValue { return []ConfigValue{{Class: "bind", Value: addrs}} } diff --git a/caddyconfig/httpcaddyfile/httptype.go b/caddyconfig/httpcaddyfile/httptype.go index 6fa5a9f7c4d..596d6884d68 100644 --- a/caddyconfig/httpcaddyfile/httptype.go +++ b/caddyconfig/httpcaddyfile/httptype.go @@ -1284,7 +1284,7 @@ func matcherSetFromMatcherToken( return nil, false, nil } -func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.ModuleMap, error) { +func (*ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.ModuleMap, error) { type hostPathPair struct { hostm caddyhttp.MatchHost pathm caddyhttp.MatchPath diff --git a/caddyconfig/httpcaddyfile/pkiapp.go b/caddyconfig/httpcaddyfile/pkiapp.go index 16ec73dc9a3..1886d5964bf 100644 --- a/caddyconfig/httpcaddyfile/pkiapp.go +++ b/caddyconfig/httpcaddyfile/pkiapp.go @@ -169,7 +169,7 @@ func parsePKIApp(d *caddyfile.Dispenser, _ any) (any, error) { return pki, nil } -func (st ServerType) buildPKIApp( +func (ServerType) buildPKIApp( pairings []sbAddrAssociation, options map[string]any, warnings []caddyconfig.Warning, diff --git a/caddyconfig/httpcaddyfile/tlsapp.go b/caddyconfig/httpcaddyfile/tlsapp.go index 1b95273c0b2..b14a35434d8 100644 --- a/caddyconfig/httpcaddyfile/tlsapp.go +++ b/caddyconfig/httpcaddyfile/tlsapp.go @@ -32,7 +32,7 @@ import ( "github.com/caddyserver/caddy/v2/modules/caddytls" ) -func (st ServerType) buildTLSApp( +func (ServerType) buildTLSApp( pairings []sbAddrAssociation, options map[string]any, warnings []caddyconfig.Warning, diff --git a/listeners.go b/listeners.go index 26f4b77b46c..9383d1641c1 100644 --- a/listeners.go +++ b/listeners.go @@ -392,11 +392,11 @@ func SplitNetworkAddress(a string) (network, host, port string, err error) { } if IsUnixNetwork(network) { host = a - return + return network, host, port, nil } host, port, err = net.SplitHostPort(a) if err == nil || a == "" { - return + return network, host, port, err } // in general, if there was an error, it was likely "missing port", // so try adding a bogus port to take advantage of standard library's diff --git a/logging.go b/logging.go index 98b031c6a2a..e975c0b9307 100644 --- a/logging.go +++ b/logging.go @@ -627,7 +627,7 @@ func (DiscardWriter) OpenWriter() (io.WriteCloser, error) { // notClosable is an io.WriteCloser that can't be closed. type notClosable struct{ io.Writer } -func (fc notClosable) Close() error { return nil } +func (notClosable) Close() error { return nil } type defaultCustomLog struct { *CustomLog diff --git a/modules/caddyevents/app.go b/modules/caddyevents/app.go index 1684cfd2a6c..34c18c30d53 100644 --- a/modules/caddyevents/app.go +++ b/modules/caddyevents/app.go @@ -156,7 +156,7 @@ func (app *App) Start() error { } // Stop gracefully shuts down the app. -func (app *App) Stop() error { +func (*App) Stop() error { return nil } diff --git a/modules/caddyhttp/autohttps.go b/modules/caddyhttp/autohttps.go index aec43c7c7af..f75d805b401 100644 --- a/modules/caddyhttp/autohttps.go +++ b/modules/caddyhttp/autohttps.go @@ -68,7 +68,7 @@ type AutoHTTPSConfig struct { // Skipped returns true if name is in skipSlice, which // should be either the Skip or SkipCerts field on ahc. -func (ahc AutoHTTPSConfig) Skipped(name string, skipSlice []string) bool { +func (AutoHTTPSConfig) Skipped(name string, skipSlice []string) bool { for _, n := range skipSlice { if name == n { return true diff --git a/modules/caddyhttp/celmatcher.go b/modules/caddyhttp/celmatcher.go index 278227d8848..ad2f69a5203 100644 --- a/modules/caddyhttp/celmatcher.go +++ b/modules/caddyhttp/celmatcher.go @@ -228,7 +228,7 @@ func (cr celHTTPRequest) ResolveName(name string) (any, bool) { return nil, false } -func (cr celHTTPRequest) Parent() interpreter.Activation { +func (celHTTPRequest) Parent() interpreter.Activation { return nil } diff --git a/modules/caddyhttp/encode/zstd/zstd.go b/modules/caddyhttp/encode/zstd/zstd.go index 7a4b2e9dd87..d420a561a67 100644 --- a/modules/caddyhttp/encode/zstd/zstd.go +++ b/modules/caddyhttp/encode/zstd/zstd.go @@ -38,7 +38,7 @@ func (Zstd) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. -func (z *Zstd) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (*Zstd) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } @@ -47,7 +47,7 @@ func (z *Zstd) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { func (Zstd) AcceptEncoding() string { return "zstd" } // NewEncoder returns a new Zstandard writer. -func (z Zstd) NewEncoder() encode.Encoder { +func (Zstd) NewEncoder() encode.Encoder { // The default of 8MB for the window is // too large for many clients, so we limit // it to 128K to lighten their load. diff --git a/modules/caddyhttp/fileserver/browse.go b/modules/caddyhttp/fileserver/browse.go index 917d14fded5..f16a5b9ba5b 100644 --- a/modules/caddyhttp/fileserver/browse.go +++ b/modules/caddyhttp/fileserver/browse.go @@ -152,7 +152,7 @@ func (fsrv *FileServer) loadDirectoryContents(ctx context.Context, dir fs.ReadDi // browseApplyQueryParams applies query parameters to the listing. // It mutates the listing and may set cookies. -func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) { +func (*FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) { layoutParam := r.URL.Query().Get("layout") sortParam := r.URL.Query().Get("sort") orderParam := r.URL.Query().Get("order") diff --git a/modules/caddyhttp/httpredirectlistener.go b/modules/caddyhttp/httpredirectlistener.go index e75969baf49..db6a4722710 100644 --- a/modules/caddyhttp/httpredirectlistener.go +++ b/modules/caddyhttp/httpredirectlistener.go @@ -51,11 +51,11 @@ func (HTTPRedirectListenerWrapper) CaddyModule() caddy.ModuleInfo { } } -func (h *HTTPRedirectListenerWrapper) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (*HTTPRedirectListenerWrapper) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } -func (h *HTTPRedirectListenerWrapper) WrapListener(l net.Listener) net.Listener { +func (*HTTPRedirectListenerWrapper) WrapListener(l net.Listener) net.Listener { return &httpRedirectListener{l} } diff --git a/modules/caddyhttp/push/handler.go b/modules/caddyhttp/push/handler.go index 3204debeffa..37ecdf45c24 100644 --- a/modules/caddyhttp/push/handler.go +++ b/modules/caddyhttp/push/handler.go @@ -156,7 +156,7 @@ func (h Handler) initializePushHeaders(r *http.Request, repl *caddy.Replacer) ht // resources described by them. If a resource has the "nopush" // attribute or describes an external entity (meaning, the resource // URI includes a scheme), it will not be pushed. -func (h Handler) servePreloadLinks(pusher http.Pusher, hdr http.Header, resources []string) { +func (Handler) servePreloadLinks(pusher http.Pusher, hdr http.Header, resources []string) { for _, resource := range resources { for _, resource := range parseLinkHeader(resource) { if _, ok := resource.params["nopush"]; ok { diff --git a/modules/caddyhttp/requestbody/requestbody.go b/modules/caddyhttp/requestbody/requestbody.go index dfc0fd92891..ccd8a2bbc3c 100644 --- a/modules/caddyhttp/requestbody/requestbody.go +++ b/modules/caddyhttp/requestbody/requestbody.go @@ -62,7 +62,7 @@ func (ew errorWrapper) Read(p []byte) (n int, err error) { if err != nil && err.Error() == "http: request body too large" { err = caddyhttp.Error(http.StatusRequestEntityTooLarge, err) } - return + return n, err } // Interface guard diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index b4760304ad8..7439a21c4b5 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -1097,7 +1097,7 @@ func (h Handler) provisionUpstream(upstream *Upstream) { // then returns a reader for the buffer along with how many bytes were buffered. Always close // the return value when done with it, just like if it was the original body! If limit is 0 // (which it shouldn't be), this function returns its input; i.e. is a no-op, for safety. -func (h Handler) bufferedBody(originalBody io.ReadCloser, limit int64) (io.ReadCloser, int64) { +func (Handler) bufferedBody(originalBody io.ReadCloser, limit int64) (io.ReadCloser, int64) { if limit == 0 { return originalBody, 0 } @@ -1410,15 +1410,15 @@ type ignoreClientGoneContext struct { context.Context } -func (c ignoreClientGoneContext) Deadline() (deadline time.Time, ok bool) { +func (ignoreClientGoneContext) Deadline() (deadline time.Time, ok bool) { return } -func (c ignoreClientGoneContext) Done() <-chan struct{} { +func (ignoreClientGoneContext) Done() <-chan struct{} { return nil } -func (c ignoreClientGoneContext) Err() error { +func (ignoreClientGoneContext) Err() error { return nil } diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index de5a35df56a..90026f4b2dc 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -62,12 +62,12 @@ func (RandomSelection) CaddyModule() caddy.ModuleInfo { } // Select returns an available host, if any. -func (r RandomSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream { +func (RandomSelection) Select(pool UpstreamPool, req *http.Request, res http.ResponseWriter) *Upstream { return selectRandomHost(pool) } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *RandomSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*RandomSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() @@ -279,7 +279,7 @@ func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.Resp } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *LeastConnSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*LeastConnSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() @@ -319,7 +319,7 @@ func (r *RoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http. } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *RoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*RoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() @@ -351,7 +351,7 @@ func (FirstSelection) Select(pool UpstreamPool, _ *http.Request, _ http.Response } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *FirstSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*FirstSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() @@ -382,7 +382,7 @@ func (IPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.Respo } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *IPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*IPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() @@ -415,7 +415,7 @@ func (ClientIPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *ClientIPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*ClientIPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() @@ -442,7 +442,7 @@ func (URIHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.Resp } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (r *URIHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +func (*URIHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if d.NextArg() { return d.ArgErr() diff --git a/modules/caddyhttp/reverseproxy/streaming.go b/modules/caddyhttp/reverseproxy/streaming.go index c5369d8c3c5..ffc4148a1c7 100644 --- a/modules/caddyhttp/reverseproxy/streaming.go +++ b/modules/caddyhttp/reverseproxy/streaming.go @@ -170,7 +170,7 @@ func (h Handler) flushInterval(req *http.Request, res *http.Response) time.Durat // isBidirectionalStream returns whether we should work in bi-directional stream mode. // // See https://github.com/caddyserver/caddy/pull/3620 for discussion of nuances. -func (h Handler) isBidirectionalStream(req *http.Request, res *http.Response) bool { +func (Handler) isBidirectionalStream(req *http.Request, res *http.Response) bool { // We have to check the encoding here; only flush headers with identity encoding. // Non-identity encoding might combine with "encode" directive, and in that case, // if body size larger than enc.MinLength, upper level encode handle might have @@ -459,12 +459,11 @@ func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { defer m.mu.Unlock() n, err = m.dst.Write(p) if m.latency < 0 { - //nolint:errcheck m.flush() - return + return n, err } if m.flushPending { - return + return n, err } if m.t == nil { m.t = time.AfterFunc(m.latency, m.delayedFlush) @@ -472,7 +471,7 @@ func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { m.t.Reset(m.latency) } m.flushPending = true - return + return n, err } func (m *maxLatencyWriter) delayedFlush() { diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go index 6b2b4954d39..eb1cbb6688c 100644 --- a/modules/caddyhttp/templates/tplcontext.go +++ b/modules/caddyhttp/templates/tplcontext.go @@ -430,7 +430,7 @@ func (c TemplateContext) funcFileStat(filename string) (fs.FileInfo, error) { // funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL; SUBJECT TO CHANGE. // Example usage: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}` -func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) { +func (TemplateContext) funcHTTPError(statusCode int) (bool, error) { return false, caddyhttp.Error(statusCode, nil) } @@ -442,7 +442,7 @@ func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) { // Time inputs are parsed using the given layout (default layout is RFC1123Z) // and are formatted as a relative time, such as "2 weeks ago". // See https://pkg.go.dev/time#pkg-constants for time layout docs. -func (c TemplateContext) funcHumanize(formatType, data string) (string, error) { +func (TemplateContext) funcHumanize(formatType, data string) (string, error) { // The format type can optionally be followed // by a colon to provide arguments for the format parts := strings.Split(formatType, ":") diff --git a/modules/caddyhttp/tracing/tracer.go b/modules/caddyhttp/tracing/tracer.go index ecd415fa0cd..4065aa96c2c 100644 --- a/modules/caddyhttp/tracing/tracer.go +++ b/modules/caddyhttp/tracing/tracer.go @@ -107,12 +107,12 @@ func (ot *openTelemetryWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request } // cleanup flush all remaining data and shutdown a tracerProvider -func (ot *openTelemetryWrapper) cleanup(logger *zap.Logger) error { +func (*openTelemetryWrapper) cleanup(logger *zap.Logger) error { return globalTracerProvider.cleanupTracerProvider(logger) } // newResource creates a resource that describe current handler instance and merge it with a default attributes value. -func (ot *openTelemetryWrapper) newResource( +func (*openTelemetryWrapper) newResource( webEngineName, webEngineVersion string, ) (*resource.Resource, error) { @@ -123,6 +123,6 @@ func (ot *openTelemetryWrapper) newResource( } // spanNameFormatter performs the replacement of placeholders in the span name -func (ot *openTelemetryWrapper) spanNameFormatter(operation string, r *http.Request) string { +func (*openTelemetryWrapper) spanNameFormatter(operation string, r *http.Request) string { return r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer).ReplaceAll(operation, "") } diff --git a/modules/caddypki/pki.go b/modules/caddypki/pki.go index 9f974a956bb..b1063f24232 100644 --- a/modules/caddypki/pki.go +++ b/modules/caddypki/pki.go @@ -116,7 +116,7 @@ func (p *PKI) Start() error { } // Stop stops the PKI app. -func (p *PKI) Stop() error { +func (*PKI) Stop() error { return nil } diff --git a/modules/caddytls/certmanagers.go b/modules/caddytls/certmanagers.go index d271083c8f2..94a41be8e17 100644 --- a/modules/caddytls/certmanagers.go +++ b/modules/caddytls/certmanagers.go @@ -52,7 +52,7 @@ func (ts Tailscale) GetCertificate(ctx context.Context, hello *tls.ClientHelloIn } // canHazCertificate returns true if Tailscale reports it can get a certificate for the given ClientHello. -func (ts Tailscale) canHazCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (bool, error) { +func (Tailscale) canHazCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (bool, error) { if !strings.HasSuffix(strings.ToLower(hello.ServerName), tailscaleDomainAliasEnding) { return false, nil } @@ -103,7 +103,7 @@ type HTTPCertGetter struct { } // CaddyModule returns the Caddy module information. -func (hcg HTTPCertGetter) CaddyModule() caddy.ModuleInfo { +func (HTTPCertGetter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.get_certificate.http", New: func() caddy.Module { return new(HTTPCertGetter) }, diff --git a/modules/caddytls/sessiontickets.go b/modules/caddytls/sessiontickets.go index bfc5628ac2d..762cfac6a16 100644 --- a/modules/caddytls/sessiontickets.go +++ b/modules/caddytls/sessiontickets.go @@ -216,7 +216,7 @@ func (s SessionTicketService) RotateSTEKs(keys [][32]byte) ([][32]byte, error) { // generateSTEK generates key material suitable for use as a // session ticket ephemeral key. -func (s *SessionTicketService) generateSTEK() ([32]byte, error) { +func (*SessionTicketService) generateSTEK() ([32]byte, error) { var newTicketKey [32]byte _, err := io.ReadFull(rand.Reader, newTicketKey[:]) return newTicketKey, err diff --git a/modules/logging/filters.go b/modules/logging/filters.go index 0ea19adc480..623a7bcf82d 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -93,12 +93,12 @@ func (HashFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (f *HashFilter) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (*HashFilter) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } // Filter filters the input field with the replacement value. -func (f *HashFilter) Filter(in zapcore.Field) zapcore.Field { +func (*HashFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { for i, s := range array { array[i] = hash(s) diff --git a/modules/metrics/adminmetrics.go b/modules/metrics/adminmetrics.go index 1cf398e4cb6..f20521e0163 100644 --- a/modules/metrics/adminmetrics.go +++ b/modules/metrics/adminmetrics.go @@ -40,7 +40,7 @@ func (AdminMetrics) CaddyModule() caddy.ModuleInfo { } // Routes returns a route for the /metrics endpoint. -func (m *AdminMetrics) Routes() []caddy.AdminRoute { +func (*AdminMetrics) Routes() []caddy.AdminRoute { metricsHandler := createMetricsHandler(nil, false) h := caddy.AdminHandlerFunc(func(w http.ResponseWriter, r *http.Request) error { metricsHandler.ServeHTTP(w, r) From c41a8cd4dc817b7396a838d8780ca82f756767c1 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:19:28 +0800 Subject: [PATCH 17/31] lint tests --- .golangci.yml | 24 ++++++++++--------- admin.go | 2 ++ listeners.go | 2 +- .../caddyhttp/reverseproxy/reverseproxy.go | 2 +- modules/caddyhttp/reverseproxy/streaming.go | 2 +- 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index fb8d42867bd..35ebcbf4057 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -44,29 +44,31 @@ linters-settings: disabled: true - name: unnecessary-stmt disabled: true + - name: import-shadowing + disabled: true - name: defer disabled: true + - name: confusing-naming + disabled: true - name: nested-structs disabled: true - name: unhandled-error - disabled: false + disabled: true # Arguments added below do not trigger the rule. + # arguments =["os\.(Create|WriteFile|Chmod)", "fmt\.Print", "myFunction", "net\..*", "bytes\.Buffer\.Write"] arguments: - - 'fmt.Printf' + - 'fmt\..*' - 'c.Conn.Close' - - 'w.Write' - 'server.Serve' - 'http.ListenAndServe' - 'conn.Close' - - 'w.buf.Write' - - 'sb.WriteString' - - 'buf.WriteString' + - 'os.Stderr.Write' + - 'buf\.(WriteString|Write)' + - 'csc.Close' + - 'cl.Close' - 'out.WriteRune' - - 'fmt.Print' - - 'fmt.Println' - - 'fmt.Printf' - - 'fmt.Fprint' - - 'sb.WriteRune' + - 'sb\.(WriteRune|WriteString)' + - 'reconn.Conn.Close' errcheck: ignore: fmt:.*,go.uber.org/zap/zapcore:^Add.* ignoretests: true diff --git a/admin.go b/admin.go index 131f18fff83..24ac47cf0b8 100644 --- a/admin.go +++ b/admin.go @@ -961,9 +961,11 @@ func handleConfig(w http.ResponseWriter, r *http.Request) error { // Set the ETag as a trailer header. // The alternative is to write the config to a buffer, and // then hash that. + w.Header().Set("Trailer", "ETag") hash := etagHasher() + configWriter := io.MultiWriter(w, hash) err := readConfig(r.URL.Path, configWriter) if err != nil { diff --git a/listeners.go b/listeners.go index 9383d1641c1..756e39d7b05 100644 --- a/listeners.go +++ b/listeners.go @@ -408,7 +408,7 @@ func SplitNetworkAddress(a string) (network, host, port string, err error) { err = nil port = "" } - return + return network, host, port, err } // JoinNetworkAddress combines network, host, and port into a single diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index 7439a21c4b5..d039d856c7a 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -1411,7 +1411,7 @@ type ignoreClientGoneContext struct { } func (ignoreClientGoneContext) Deadline() (deadline time.Time, ok bool) { - return + return deadline, ok } func (ignoreClientGoneContext) Done() <-chan struct{} { diff --git a/modules/caddyhttp/reverseproxy/streaming.go b/modules/caddyhttp/reverseproxy/streaming.go index ffc4148a1c7..10bb6b90c74 100644 --- a/modules/caddyhttp/reverseproxy/streaming.go +++ b/modules/caddyhttp/reverseproxy/streaming.go @@ -459,7 +459,7 @@ func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { defer m.mu.Unlock() n, err = m.dst.Write(p) if m.latency < 0 { - m.flush() + err = m.flush() return n, err } if m.flushPending { From 6790811913336ecc13459c847d3377285e8a8600 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:22:28 +0800 Subject: [PATCH 18/31] remove a _ --- modules/caddytls/tls.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/caddytls/tls.go b/modules/caddytls/tls.go index 3beedd6beed..02d5aae756b 100644 --- a/modules/caddytls/tls.go +++ b/modules/caddytls/tls.go @@ -609,7 +609,7 @@ func (t *TLS) storageCleanInterval() time.Duration { } // onEvent translates CertMagic events into Caddy events then dispatches them. -func (t *TLS) onEvent(_ context.Context, eventName string, data map[string]any) error { +func (t *TLS) onEvent(ctx context.Context, eventName string, data map[string]any) error { evt := t.events.Emit(t.ctx, eventName, data) return evt.Aborted } From e7d92a1a1ff247758242d6f88e913b872972612a Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:24:56 +0800 Subject: [PATCH 19/31] reverse some unused-reciever changes --- modules/caddyhttp/caddyhttp.go | 2 +- modules/caddyhttp/encode/zstd/zstd.go | 2 +- modules/caddyhttp/httpredirectlistener.go | 2 +- modules/logging/filters.go | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/caddyhttp/caddyhttp.go b/modules/caddyhttp/caddyhttp.go index a17dc7dada9..f15aec5ed4b 100644 --- a/modules/caddyhttp/caddyhttp.go +++ b/modules/caddyhttp/caddyhttp.go @@ -294,7 +294,7 @@ func (tlsPlaceholderWrapper) CaddyModule() caddy.ModuleInfo { func (tlsPlaceholderWrapper) WrapListener(ln net.Listener) net.Listener { return ln } -func (tlsPlaceholderWrapper) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { return nil } +func (tlsPlaceholderWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } const ( // DefaultHTTPPort is the default port for HTTP. diff --git a/modules/caddyhttp/encode/zstd/zstd.go b/modules/caddyhttp/encode/zstd/zstd.go index d420a561a67..df472964a76 100644 --- a/modules/caddyhttp/encode/zstd/zstd.go +++ b/modules/caddyhttp/encode/zstd/zstd.go @@ -38,7 +38,7 @@ func (Zstd) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. -func (*Zstd) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (*Zstd) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } diff --git a/modules/caddyhttp/httpredirectlistener.go b/modules/caddyhttp/httpredirectlistener.go index db6a4722710..e8653e53b0e 100644 --- a/modules/caddyhttp/httpredirectlistener.go +++ b/modules/caddyhttp/httpredirectlistener.go @@ -51,7 +51,7 @@ func (HTTPRedirectListenerWrapper) CaddyModule() caddy.ModuleInfo { } } -func (*HTTPRedirectListenerWrapper) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (*HTTPRedirectListenerWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } diff --git a/modules/logging/filters.go b/modules/logging/filters.go index 623a7bcf82d..c59713fc19e 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -62,7 +62,7 @@ func (DeleteFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (DeleteFilter) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (DeleteFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } @@ -93,7 +93,7 @@ func (HashFilter) CaddyModule() caddy.ModuleInfo { } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. -func (*HashFilter) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error { +func (*HashFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } From 3fbbfa3db0dcc472512aacf3c5ba0f609441a702 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:26:59 +0800 Subject: [PATCH 20/31] _ -> ctx --- modules/caddyhttp/encode/gzip/gzip.go | 2 +- modules/caddyhttp/headers/headers.go | 2 +- modules/caddyhttp/ip_range.go | 2 +- modules/caddyhttp/map/map.go | 2 +- modules/caddyhttp/matchers.go | 12 ++++++------ modules/caddyhttp/proxyprotocol/listenerwrapper.go | 2 +- modules/caddyhttp/reverseproxy/healthchecks.go | 2 +- modules/caddyhttp/reverseproxy/selectionpolicies.go | 4 ++-- modules/caddyhttp/reverseproxy/upstreams.go | 2 +- modules/caddyhttp/routes.go | 2 +- modules/caddyhttp/templates/templates.go | 2 +- modules/caddytls/connpolicy.go | 2 +- modules/logging/encoders.go | 4 ++-- modules/logging/filters.go | 4 ++-- modules/logging/netwriter.go | 2 +- 15 files changed, 23 insertions(+), 23 deletions(-) diff --git a/modules/caddyhttp/encode/gzip/gzip.go b/modules/caddyhttp/encode/gzip/gzip.go index 529436cf49d..0af38b92776 100644 --- a/modules/caddyhttp/encode/gzip/gzip.go +++ b/modules/caddyhttp/encode/gzip/gzip.go @@ -59,7 +59,7 @@ func (g *Gzip) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision provisions g's configuration. -func (g *Gzip) Provision(_ caddy.Context) error { +func (g *Gzip) Provision(ctx caddy.Context) error { if g.Level == 0 { g.Level = defaultGzipLevel } diff --git a/modules/caddyhttp/headers/headers.go b/modules/caddyhttp/headers/headers.go index ed503ef5633..f1ed77633c8 100644 --- a/modules/caddyhttp/headers/headers.go +++ b/modules/caddyhttp/headers/headers.go @@ -132,7 +132,7 @@ type HeaderOps struct { } // Provision sets up the header operations. -func (ops *HeaderOps) Provision(_ caddy.Context) error { +func (ops *HeaderOps) Provision(ctx caddy.Context) error { for fieldName, replacements := range ops.Replace { for i, r := range replacements { if r.SearchRegexp != "" { diff --git a/modules/caddyhttp/ip_range.go b/modules/caddyhttp/ip_range.go index 65e2336e56b..a1d74afc4ed 100644 --- a/modules/caddyhttp/ip_range.go +++ b/modules/caddyhttp/ip_range.go @@ -69,7 +69,7 @@ func (StaticIPRange) CaddyModule() caddy.ModuleInfo { } } -func (s *StaticIPRange) Provision(_ caddy.Context) error { +func (s *StaticIPRange) Provision(ctx caddy.Context) error { for _, str := range s.Ranges { prefix, err := CIDRExpressionToPrefix(str) if err != nil { diff --git a/modules/caddyhttp/map/map.go b/modules/caddyhttp/map/map.go index 336f2572319..289934354ac 100644 --- a/modules/caddyhttp/map/map.go +++ b/modules/caddyhttp/map/map.go @@ -61,7 +61,7 @@ func (Handler) CaddyModule() caddy.ModuleInfo { } // Provision sets up h. -func (h *Handler) Provision(_ caddy.Context) error { +func (h *Handler) Provision(ctx caddy.Context) error { for j, dest := range h.Destinations { if strings.Count(dest, "{") != 1 || !strings.HasPrefix(dest, "{") { return fmt.Errorf("destination must be a placeholder and only a placeholder") diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go index b3859797083..85d14de8c41 100644 --- a/modules/caddyhttp/matchers.go +++ b/modules/caddyhttp/matchers.go @@ -234,7 +234,7 @@ func (m *MatchHost) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision sets up and validates m, including making it more efficient for large lists. -func (m MatchHost) Provision(_ caddy.Context) error { +func (m MatchHost) Provision(ctx caddy.Context) error { // check for duplicates; they are nonsensical and reduce efficiency // (we could just remove them, but the user should know their config is erroneous) seen := make(map[string]int) @@ -370,7 +370,7 @@ func (MatchPath) CaddyModule() caddy.ModuleInfo { } // Provision lower-cases the paths in m to ensure case-insensitive matching. -func (m MatchPath) Provision(_ caddy.Context) error { +func (m MatchPath) Provision(ctx caddy.Context) error { for i := range m { if m[i] == "*" && i > 0 { // will always match, so just put it first @@ -740,7 +740,7 @@ func (m MatchMethod) Match(r *http.Request) bool { // Example: // // expression method('PUT', 'POST') -func (MatchMethod) CELLibrary(_ caddy.Context) (cel.Library, error) { +func (MatchMethod) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( "method", "method_request_list", @@ -827,7 +827,7 @@ func (m MatchQuery) Match(r *http.Request) bool { // Example: // // expression query({'sort': 'asc'}) || query({'foo': ['*bar*', 'baz']}) -func (MatchQuery) CELLibrary(_ caddy.Context) (cel.Library, error) { +func (MatchQuery) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( "query", "query_matcher_request_map", @@ -904,7 +904,7 @@ func (m MatchHeader) Match(r *http.Request) bool { // // expression header({'content-type': 'image/png'}) // expression header({'foo': ['bar', 'baz']}) // match bar or baz -func (MatchHeader) CELLibrary(_ caddy.Context) (cel.Library, error) { +func (MatchHeader) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( "header", "header_matcher_request_map", @@ -1169,7 +1169,7 @@ func (m *MatchProtocol) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // Example: // // expression protocol('https') -func (MatchProtocol) CELLibrary(_ caddy.Context) (cel.Library, error) { +func (MatchProtocol) CELLibrary(ctx caddy.Context) (cel.Library, error) { return CELMatcherImpl( "protocol", "protocol_request_string", diff --git a/modules/caddyhttp/proxyprotocol/listenerwrapper.go b/modules/caddyhttp/proxyprotocol/listenerwrapper.go index 6b6f1165d61..f404c06fe51 100644 --- a/modules/caddyhttp/proxyprotocol/listenerwrapper.go +++ b/modules/caddyhttp/proxyprotocol/listenerwrapper.go @@ -43,7 +43,7 @@ type ListenerWrapper struct { } // Provision sets up the listener wrapper. -func (pp *ListenerWrapper) Provision(_ caddy.Context) error { +func (pp *ListenerWrapper) Provision(ctx caddy.Context) error { rules := make([]proxyprotocol.Rule, 0, len(pp.Allow)) for _, s := range pp.Allow { _, n, err := net.ParseCIDR(s) diff --git a/modules/caddyhttp/reverseproxy/healthchecks.go b/modules/caddyhttp/reverseproxy/healthchecks.go index e70264ee5f4..1b4f2d05534 100644 --- a/modules/caddyhttp/reverseproxy/healthchecks.go +++ b/modules/caddyhttp/reverseproxy/healthchecks.go @@ -107,7 +107,7 @@ type ActiveHealthChecks struct { } // Provision ensures that a is set up properly before use. -func (a *ActiveHealthChecks) Provision(_ caddy.Context, h *Handler) error { +func (a *ActiveHealthChecks) Provision(ctx caddy.Context, h *Handler) error { if !a.IsEnabled() { return nil } diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index 90026f4b2dc..02621a59e32 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -119,7 +119,7 @@ func (r *WeightedRoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) } // Provision sets up r. -func (r *WeightedRoundRobinSelection) Provision(_ caddy.Context) error { +func (r *WeightedRoundRobinSelection) Provision(ctx caddy.Context) error { for _, weight := range r.Weights { r.totalWeight += weight } @@ -194,7 +194,7 @@ func (r *RandomChoiceSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error } // Provision sets up r. -func (r *RandomChoiceSelection) Provision(_ caddy.Context) error { +func (r *RandomChoiceSelection) Provision(ctx caddy.Context) error { if r.Choose == 0 { r.Choose = 2 } diff --git a/modules/caddyhttp/reverseproxy/upstreams.go b/modules/caddyhttp/reverseproxy/upstreams.go index b4881fcd0b7..7e63a718b01 100644 --- a/modules/caddyhttp/reverseproxy/upstreams.go +++ b/modules/caddyhttp/reverseproxy/upstreams.go @@ -261,7 +261,7 @@ func (AUpstreams) CaddyModule() caddy.ModuleInfo { } } -func (au *AUpstreams) Provision(_ caddy.Context) error { +func (au *AUpstreams) Provision(ctx caddy.Context) error { if au.Refresh == 0 { au.Refresh = caddy.Duration(time.Minute) } diff --git a/modules/caddyhttp/routes.go b/modules/caddyhttp/routes.go index 9db4f252044..9be3d01a463 100644 --- a/modules/caddyhttp/routes.go +++ b/modules/caddyhttp/routes.go @@ -311,7 +311,7 @@ func wrapRoute(route Route) Middleware { // we need to pull this particular MiddlewareHandler // pointer into its own stack frame to preserve it so it // won't be overwritten in future loop iterations. -func wrapMiddleware(_ caddy.Context, mh MiddlewareHandler, metrics *Metrics) Middleware { +func wrapMiddleware(ctx caddy.Context, mh MiddlewareHandler, metrics *Metrics) Middleware { handlerToUse := mh if metrics != nil { // wrap the middleware with metrics instrumentation diff --git a/modules/caddyhttp/templates/templates.go b/modules/caddyhttp/templates/templates.go index 1caa3d9976e..65359d9e9aa 100644 --- a/modules/caddyhttp/templates/templates.go +++ b/modules/caddyhttp/templates/templates.go @@ -324,7 +324,7 @@ func (Templates) CaddyModule() caddy.ModuleInfo { } // Provision provisions t. -func (t *Templates) Provision(_ caddy.Context) error { +func (t *Templates) Provision(ctx caddy.Context) error { fnModInfos := caddy.GetModules("http.handlers.templates.functions") customFuncs := make([]template.FuncMap, 0, len(fnModInfos)) for _, modInfo := range fnModInfos { diff --git a/modules/caddytls/connpolicy.go b/modules/caddytls/connpolicy.go index 64fdd513861..b896b0e6379 100644 --- a/modules/caddytls/connpolicy.go +++ b/modules/caddytls/connpolicy.go @@ -81,7 +81,7 @@ func (cp ConnectionPolicies) Provision(ctx caddy.Context) error { // TLSConfig returns a standard-lib-compatible TLS configuration which // selects the first matching policy based on the ClientHello. -func (cp ConnectionPolicies) TLSConfig(_ caddy.Context) *tls.Config { +func (cp ConnectionPolicies) TLSConfig(ctx caddy.Context) *tls.Config { // using ServerName to match policies is extremely common, especially in configs // with lots and lots of different policies; we can fast-track those by indexing // them by SNI, so we don't have to iterate potentially thousands of policies diff --git a/modules/logging/encoders.go b/modules/logging/encoders.go index a4409e7e459..d127c6332f7 100644 --- a/modules/logging/encoders.go +++ b/modules/logging/encoders.go @@ -45,7 +45,7 @@ func (ConsoleEncoder) CaddyModule() caddy.ModuleInfo { } // Provision sets up the encoder. -func (ce *ConsoleEncoder) Provision(_ caddy.Context) error { +func (ce *ConsoleEncoder) Provision(ctx caddy.Context) error { if ce.LevelFormat == "" { ce.LevelFormat = "color" } @@ -92,7 +92,7 @@ func (JSONEncoder) CaddyModule() caddy.ModuleInfo { } // Provision sets up the encoder. -func (je *JSONEncoder) Provision(_ caddy.Context) error { +func (je *JSONEncoder) Provision(ctx caddy.Context) error { je.Encoder = zapcore.NewJSONEncoder(je.ZapcoreEncoderConfig()) return nil } diff --git a/modules/logging/filters.go b/modules/logging/filters.go index c59713fc19e..5092fa92f39 100644 --- a/modules/logging/filters.go +++ b/modules/logging/filters.go @@ -198,7 +198,7 @@ func (m *IPMaskFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision parses m's IP masks, from integers. -func (m *IPMaskFilter) Provision(_ caddy.Context) error { +func (m *IPMaskFilter) Provision(ctx caddy.Context) error { parseRawToMask := func(rawField int, bitLen int) net.IPMask { if rawField == 0 { return nil @@ -566,7 +566,7 @@ func (f *RegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } // Provision compiles m's regexp. -func (f *RegexpFilter) Provision(_ caddy.Context) error { +func (f *RegexpFilter) Provision(ctx caddy.Context) error { r, err := regexp.Compile(f.RawRegexp) if err != nil { return err diff --git a/modules/logging/netwriter.go b/modules/logging/netwriter.go index fa0ba7001a8..65f9c1ab1c7 100644 --- a/modules/logging/netwriter.go +++ b/modules/logging/netwriter.go @@ -57,7 +57,7 @@ func (NetWriter) CaddyModule() caddy.ModuleInfo { } // Provision sets up the module. -func (nw *NetWriter) Provision(_ caddy.Context) error { +func (nw *NetWriter) Provision(ctx caddy.Context) error { repl := caddy.NewReplacer() address, err := repl.ReplaceOrErr(nw.Address, true, true) if err != nil { From b71f517427da9f84ff2b36ad36ebea0c3dc18d49 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:29:42 +0800 Subject: [PATCH 21/31] revert changes to dependabot --- .github/dependabot.yml | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 13eb3e01e96..64284b90748 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,11 +1,7 @@ --- version: 2 updates: - - package-ecosystem: 'github-actions' - directory: '/' + - package-ecosystem: "github-actions" + directory: "/" schedule: - interval: 'weekly' - - package-ecosystem: 'gomod' - directory: '/' - schedule: - interval: 'weekly' + interval: "monthly" From 4b22b11ec933745d596e3b5cedf74bf7b5f30c8a Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:35:24 +0800 Subject: [PATCH 22/31] restore an "unused parameter" --- caddyconfig/httpcaddyfile/pkiapp.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/caddyconfig/httpcaddyfile/pkiapp.go b/caddyconfig/httpcaddyfile/pkiapp.go index 1886d5964bf..366e60b2001 100644 --- a/caddyconfig/httpcaddyfile/pkiapp.go +++ b/caddyconfig/httpcaddyfile/pkiapp.go @@ -47,7 +47,7 @@ func init() { // } // // When the CA ID is unspecified, 'local' is assumed. -func parsePKIApp(d *caddyfile.Dispenser, _ any) (any, error) { +func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) { pki := &caddypki.PKI{CAs: make(map[string]*caddypki.CA)} for d.Next() { From 54fcb8eea9f86471cb6a22b0aafce58429887060 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:38:55 +0800 Subject: [PATCH 23/31] add nolintlint --- .golangci.yml | 1 + cmd/main.go | 1 - modules/caddyhttp/reverseproxy/selectionpolicies.go | 8 ++++---- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 35ebcbf4057..6b74098af5d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -97,6 +97,7 @@ linters: - gosimple - govet - ineffassign + - nolintlint - misspell - prealloc - revive diff --git a/cmd/main.go b/cmd/main.go index 1d6478a4737..47c486f71b7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -211,7 +211,6 @@ func watchConfigFile(filename, adapterName string) { logger().Info("watching config file for changes") // begin poller - //nolint:staticcheck for range time.Tick(1 * time.Second) { // get current config newCfg, _, err := loadConfigWithLogger(nil, filename, adapterName) diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index 02621a59e32..56f24df645c 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -220,7 +220,7 @@ func (r RandomChoiceSelection) Select(pool UpstreamPool, _ *http.Request, _ http if !upstream.Available() { continue } - j := weakrand.Intn(i + 1) //nolint:gosec + j := weakrand.Intn(i + 1) if j < k { choices[j] = upstream } @@ -269,7 +269,7 @@ func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.Resp // sample: https://en.wikipedia.org/wiki/Reservoir_sampling if numReqs == leastReqs { count++ - if count > 1 || (weakrand.Int()%count) == 0 { //nolint:gosec + if count > 1 || (weakrand.Int()%count) == 0 { bestHost = host } } @@ -753,7 +753,7 @@ func selectRandomHost(pool []*Upstream) *Upstream { // upstream will always be chosen if there is at // least one available count++ - if (weakrand.Int() % count) == 0 { //nolint:gosec + if (weakrand.Int() % count) == 0 { randomHost = upstream } } @@ -792,7 +792,7 @@ func leastRequests(upstreams []*Upstream) *Upstream { if len(best) == 1 { return best[0] } - return best[weakrand.Intn(len(best))] //nolint:gosec + return best[weakrand.Intn(len(best))] } // hostByHashing returns an available host from pool based on a hashable string s. From eb5741f9a1123edeab19981d9b094f6d90938f9c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:39:52 +0800 Subject: [PATCH 24/31] nolintlint --- modules/caddyhttp/reverseproxy/selectionpolicies.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index 56f24df645c..276bb3973d7 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -220,7 +220,7 @@ func (r RandomChoiceSelection) Select(pool UpstreamPool, _ *http.Request, _ http if !upstream.Available() { continue } - j := weakrand.Intn(i + 1) + j := weakrand.Intn(i + 1) if j < k { choices[j] = upstream } @@ -269,7 +269,7 @@ func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.Resp // sample: https://en.wikipedia.org/wiki/Reservoir_sampling if numReqs == leastReqs { count++ - if count > 1 || (weakrand.Int()%count) == 0 { + if count > 1 || (weakrand.Int()%count) == 0 { bestHost = host } } @@ -753,7 +753,7 @@ func selectRandomHost(pool []*Upstream) *Upstream { // upstream will always be chosen if there is at // least one available count++ - if (weakrand.Int() % count) == 0 { + if (weakrand.Int() % count) == 0 { randomHost = upstream } } @@ -792,7 +792,7 @@ func leastRequests(upstreams []*Upstream) *Upstream { if len(best) == 1 { return best[0] } - return best[weakrand.Intn(len(best))] + return best[weakrand.Intn(len(best))] } // hostByHashing returns an available host from pool based on a hashable string s. From 89446328aa492d7f10b805a22f9f82b3f3ae51e1 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 01:50:50 +0800 Subject: [PATCH 25/31] return the error cleanly (handler.go) --- modules/caddyhttp/push/handler.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/caddyhttp/push/handler.go b/modules/caddyhttp/push/handler.go index 37ecdf45c24..b1be9f2fe9d 100644 --- a/modules/caddyhttp/push/handler.go +++ b/modules/caddyhttp/push/handler.go @@ -122,8 +122,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhtt } // serve only after pushing! - err := next.ServeHTTP(lp, r) - return err + return next.ServeHTTP(lp, r) } func (h Handler) initializePushHeaders(r *http.Request, repl *caddy.Replacer) http.Header { From 813b684ee5c4b98dff9d6389cd3abb5ccbf2de7c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 02:23:36 +0800 Subject: [PATCH 26/31] revert addition of blanks --- caddyconfig/httpcaddyfile/serveroptions.go | 2 +- modules/caddyhttp/celmatcher.go | 2 +- modules/logging/nopencoder.go | 52 +++++++++++----------- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/caddyconfig/httpcaddyfile/serveroptions.go b/caddyconfig/httpcaddyfile/serveroptions.go index c79944123bb..6d7c6787f37 100644 --- a/caddyconfig/httpcaddyfile/serveroptions.go +++ b/caddyconfig/httpcaddyfile/serveroptions.go @@ -284,7 +284,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) { func applyServerOptions( servers map[string]*caddyhttp.Server, options map[string]any, - _ *[]caddyconfig.Warning, + warnings *[]caddyconfig.Warning, ) error { serverOpts, ok := options["servers"].([]serverOptions) if !ok { diff --git a/modules/caddyhttp/celmatcher.go b/modules/caddyhttp/celmatcher.go index ad2f69a5203..fe82022c2df 100644 --- a/modules/caddyhttp/celmatcher.go +++ b/modules/caddyhttp/celmatcher.go @@ -442,7 +442,7 @@ func CELMatcherDecorator(funcName string, fac CELMatcherFactory) interpreter.Int // CELMatcherRuntimeFunction creates a function binding for when the input to the matcher // is dynamically resolved rather than a set of static constant values. -func CELMatcherRuntimeFunction(_ string, fac CELMatcherFactory) functions.BinaryOp { +func CELMatcherRuntimeFunction(funcName string, fac CELMatcherFactory) functions.BinaryOp { return func(celReq, matcherData ref.Val) ref.Val { matcher, err := fac(matcherData) if err != nil { diff --git a/modules/logging/nopencoder.go b/modules/logging/nopencoder.go index 68f748f9bbe..62c1f787fa9 100644 --- a/modules/logging/nopencoder.go +++ b/modules/logging/nopencoder.go @@ -26,79 +26,79 @@ type nopEncoder struct{} // AddArray is part of the zapcore.ObjectEncoder interface. // Array elements do not get filtered. -func (nopEncoder) AddArray(_ string, _ zapcore.ArrayMarshaler) error { return nil } +func (nopEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { return nil } // AddObject is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddObject(_ string, _ zapcore.ObjectMarshaler) error { return nil } +func (nopEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { return nil } // AddBinary is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddBinary(_ string, _ []byte) {} +func (nopEncoder) AddBinary(key string, value []byte) {} // AddByteString is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddByteString(_ string, _ []byte) {} +func (nopEncoder) AddByteString(key string, value []byte) {} // AddBool is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddBool(_ string, _ bool) {} +func (nopEncoder) AddBool(key string, value bool) {} // AddComplex128 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddComplex128(_ string, _ complex128) {} +func (nopEncoder) AddComplex128(key string, value complex128) {} // AddComplex64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddComplex64(_ string, _ complex64) {} +func (nopEncoder) AddComplex64(key string, value complex64) {} // AddDuration is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddDuration(_ string, _ time.Duration) {} +func (nopEncoder) AddDuration(key string, value time.Duration) {} // AddFloat64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddFloat64(_ string, _ float64) {} +func (nopEncoder) AddFloat64(key string, value float64) {} // AddFloat32 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddFloat32(_ string, _ float32) {} +func (nopEncoder) AddFloat32(key string, value float32) {} // AddInt is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt(_ string, _ int) {} +func (nopEncoder) AddInt(key string, value int) {} // AddInt64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt64(_ string, _ int64) {} +func (nopEncoder) AddInt64(key string, value int64) {} // AddInt32 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt32(_ string, _ int32) {} +func (nopEncoder) AddInt32(key string, value int32) {} // AddInt16 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt16(_ string, _ int16) {} +func (nopEncoder) AddInt16(key string, value int16) {} // AddInt8 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddInt8(_ string, _ int8) {} +func (nopEncoder) AddInt8(key string, value int8) {} // AddString is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddString(_, _ string) {} +func (nopEncoder) AddString(key, value string) {} // AddTime is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddTime(_ string, _ time.Time) {} +func (nopEncoder) AddTime(key string, value time.Time) {} // AddUint is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint(_ string, _ uint) {} +func (nopEncoder) AddUint(key string, value uint) {} // AddUint64 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint64(_ string, _ uint64) {} +func (nopEncoder) AddUint64(key string, value uint64) {} // AddUint32 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint32(_ string, _ uint32) {} +func (nopEncoder) AddUint32(key string, value uint32) {} // AddUint16 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint16(_ string, _ uint16) {} +func (nopEncoder) AddUint16(key string, value uint16) {} // AddUint8 is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUint8(_ string, _ uint8) {} +func (nopEncoder) AddUint8(key string, value uint8) {} // AddUintptr is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddUintptr(_ string, _ uintptr) {} +func (nopEncoder) AddUintptr(key string, value uintptr) {} // AddReflected is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) AddReflected(_ string, _ any) error { return nil } +func (nopEncoder) AddReflected(key string, value any) error { return nil } // OpenNamespace is part of the zapcore.ObjectEncoder interface. -func (nopEncoder) OpenNamespace(_ string) {} +func (nopEncoder) OpenNamespace(key string) {} // Clone is part of the zapcore.ObjectEncoder interface. // We don't use it as of Oct 2019 (v2 beta 7), I'm not @@ -106,7 +106,7 @@ func (nopEncoder) OpenNamespace(_ string) {} func (ne nopEncoder) Clone() zapcore.Encoder { return ne } // EncodeEntry partially implements the zapcore.Encoder interface. -func (nopEncoder) EncodeEntry(_ zapcore.Entry, _ []zapcore.Field) (*buffer.Buffer, error) { +func (nopEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { return bufferpool.Get(), nil } From cd0e19e5d646a2018b11b561e234d16ee351874c Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 02:25:16 +0800 Subject: [PATCH 27/31] revert addition of blanks --- admin.go | 2 +- admin_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/admin.go b/admin.go index 24ac47cf0b8..3bf828228ab 100644 --- a/admin.go +++ b/admin.go @@ -1060,7 +1060,7 @@ func handleConfigID(_ http.ResponseWriter, r *http.Request) error { return errInternalRedir } -func handleStop(_ http.ResponseWriter, r *http.Request) error { +func handleStop(w http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodPost { return APIError{ HTTPStatus: http.StatusMethodNotAllowed, diff --git a/admin_test.go b/admin_test.go index 634bb04d997..e93d09b8d33 100644 --- a/admin_test.go +++ b/admin_test.go @@ -131,7 +131,7 @@ func TestUnsyncedConfigAccess(t *testing.T) { // TestLoadConcurrent exercises Load under concurrent conditions // and is most useful under test with `-race` enabled. -func TestLoadConcurrent(_ *testing.T) { +func TestLoadConcurrent(t *testing.T) { var wg sync.WaitGroup for i := 0; i < 100; i++ { From b113c3a578a1c3ed436469e34f3251b38c846d6a Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 02:25:54 +0800 Subject: [PATCH 28/31] revert addition of blanks --- caddyconfig/httpcaddyfile/tlsapp.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/caddyconfig/httpcaddyfile/tlsapp.go b/caddyconfig/httpcaddyfile/tlsapp.go index b14a35434d8..5b1d231af1e 100644 --- a/caddyconfig/httpcaddyfile/tlsapp.go +++ b/caddyconfig/httpcaddyfile/tlsapp.go @@ -485,7 +485,7 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e // for any other automation policies. A nil policy (and no error) will be // returned if there are no default/global options. However, if always is // true, a non-nil value will always be returned (unless there is an error). -func newBaseAutomationPolicy(options map[string]any, _ []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) { +func newBaseAutomationPolicy(options map[string]any, warnings []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) { issuers, hasIssuers := options["cert_issuer"] _, hasLocalCerts := options["local_certs"] keyType, hasKeyType := options["key_type"] From 756ae1193762d5928e03db7f9c26f04ff5dae78f Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 02:30:46 +0800 Subject: [PATCH 29/31] revert addition of blanks --- modules/caddyhttp/celmatcher.go | 4 ++-- modules/caddyhttp/staticerror.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/caddyhttp/celmatcher.go b/modules/caddyhttp/celmatcher.go index fe82022c2df..3a5a3fb6688 100644 --- a/modules/caddyhttp/celmatcher.go +++ b/modules/caddyhttp/celmatcher.go @@ -232,7 +232,7 @@ func (celHTTPRequest) Parent() interpreter.Activation { return nil } -func (cr celHTTPRequest) ConvertToNative(_ reflect.Type) (any, error) { +func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) { return cr.Request, nil } @@ -255,7 +255,7 @@ var pkixNameCELType = types.NewTypeValue("pkix.Name", traits.ReceiverType) // methods to satisfy the ref.Val interface. type celPkixName struct{ *pkix.Name } -func (pn celPkixName) ConvertToNative(_ reflect.Type) (any, error) { +func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) { return pn.Name, nil } diff --git a/modules/caddyhttp/staticerror.go b/modules/caddyhttp/staticerror.go index c30610f0807..ae26ddef2c2 100644 --- a/modules/caddyhttp/staticerror.go +++ b/modules/caddyhttp/staticerror.go @@ -95,7 +95,7 @@ func (e *StaticError) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } -func (e StaticError) ServeHTTP(_ http.ResponseWriter, r *http.Request, _ Handler) error { +func (e StaticError) ServeHTTP(w http.ResponseWriter, r *http.Request, h Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) statusCode := http.StatusInternalServerError From 14b54e914281a4228f7c44cce8dee68c71a6c414 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 02:32:02 +0800 Subject: [PATCH 30/31] revert addition of blanks --- modules/caddytls/certmanagers.go | 2 +- modules/caddytls/internalissuer.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/caddytls/certmanagers.go b/modules/caddytls/certmanagers.go index 94a41be8e17..fa98b367fbc 100644 --- a/modules/caddytls/certmanagers.go +++ b/modules/caddytls/certmanagers.go @@ -118,7 +118,7 @@ func (hcg *HTTPCertGetter) Provision(ctx caddy.Context) error { return nil } -func (hcg HTTPCertGetter) GetCertificate(_ context.Context, hello *tls.ClientHelloInfo) (*tls.Certificate, error) { +func (hcg HTTPCertGetter) GetCertificate(ctx context.Context, hello *tls.ClientHelloInfo) (*tls.Certificate, error) { sigs := make([]string, len(hello.SignatureSchemes)) for i, sig := range hello.SignatureSchemes { sigs[i] = fmt.Sprintf("%x", uint16(sig)) // you won't believe what %x uses if the val is a Stringer diff --git a/modules/caddytls/internalissuer.go b/modules/caddytls/internalissuer.go index 68de0be5e69..1cf2461ab7c 100644 --- a/modules/caddytls/internalissuer.go +++ b/modules/caddytls/internalissuer.go @@ -100,7 +100,7 @@ func (iss InternalIssuer) IssuerKey() string { } // Issue issues a certificate to satisfy the CSR. -func (iss InternalIssuer) Issue(_ context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { +func (iss InternalIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { // prepare the signing authority authCfg := caddypki.AuthorityConfig{ SignWithRoot: iss.SignWithRoot, From 24ab9f445ef18ddd0242780007af42e20974c2d8 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Tue, 15 Aug 2023 02:33:06 +0800 Subject: [PATCH 31/31] revert additon of blanks --- caddyconfig/httpcaddyfile/options.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/caddyconfig/httpcaddyfile/options.go b/caddyconfig/httpcaddyfile/options.go index 3b5b80cb3e0..ba1896b6b84 100644 --- a/caddyconfig/httpcaddyfile/options.go +++ b/caddyconfig/httpcaddyfile/options.go @@ -59,7 +59,7 @@ func init() { RegisterGlobalOption("persist_config", parseOptPersistConfig) } -func parseOptTrue(_ *caddyfile.Dispenser, _ any) (any, error) { return true, nil } +func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil } func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) { var httpPort int