diff --git a/.golangci.yml b/.golangci.yml index 078682a..8eb57f6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,15 +2,16 @@ version: "2" linters: default: all disable: - - bodyclose + # - bodyclose - containedctx - - contextcheck + # - contextcheck - cyclop - depguard - - dupl + # - dupl - err113 - exhaustive - exhaustruct + - funcorder - forcetypeassert - gochecknoglobals - gochecknoinits @@ -18,7 +19,6 @@ linters: - goconst - gocyclo - gomoddirectives - - gosec - gosmopolitan - ireturn - lll @@ -27,12 +27,10 @@ linters: - mnd - nakedret - nestif - - nilnil - nlreturn - - noctx - nonamedreturns - paralleltest - - prealloc + - revive - rowserrcheck - sqlclosecheck - tagliatelle diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index bf24f6d..ed25d81 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -21,7 +21,7 @@ lint: - markdownlint - yamllint enabled: - - checkov@3.2.416 + - checkov@3.2.432 - golangci-lint2@2.1.6 - hadolint@2.12.1-beta - actionlint@1.7.7 @@ -32,7 +32,7 @@ lint: - prettier@3.5.3 - shellcheck@0.10.0 - shfmt@3.6.0 - - trufflehog@3.88.29 + - trufflehog@3.88.33 actions: disabled: - trunk-announce diff --git a/internal/acl/config.go b/internal/acl/config.go index fe06d47..8d2f306 100644 --- a/internal/acl/config.go +++ b/internal/acl/config.go @@ -45,7 +45,7 @@ func (c *checkCache) Expired() bool { return c.created.Add(cacheTTL).Before(utils.TimeNow()) } -//TODO: add stats +// TODO: add stats const ( ACLAllow = "allow" diff --git a/internal/acl/matcher_test.go b/internal/acl/matcher_test.go index 384b9b8..0d015b4 100644 --- a/internal/acl/matcher_test.go +++ b/internal/acl/matcher_test.go @@ -6,7 +6,7 @@ import ( "testing" maxmind "github.com/yusing/go-proxy/internal/maxmind/types" - "github.com/yusing/go-proxy/internal/utils" + "github.com/yusing/go-proxy/internal/serialization" ) func TestMatchers(t *testing.T) { @@ -16,7 +16,7 @@ func TestMatchers(t *testing.T) { } var mathers Matchers - err := utils.Convert(reflect.ValueOf(strMatchers), reflect.ValueOf(&mathers), false) + err := serialization.Convert(reflect.ValueOf(strMatchers), reflect.ValueOf(&mathers), false) if err != nil { t.Fatal(err) } diff --git a/internal/acl/tcp_listener.go b/internal/acl/tcp_listener.go index b6b4a7a..59e40ee 100644 --- a/internal/acl/tcp_listener.go +++ b/internal/acl/tcp_listener.go @@ -22,12 +22,12 @@ func (noConn) SetDeadline(t time.Time) error { return nil } func (noConn) SetReadDeadline(t time.Time) error { return nil } func (noConn) SetWriteDeadline(t time.Time) error { return nil } -func (cfg *Config) WrapTCP(lis net.Listener) net.Listener { - if cfg == nil { +func (c *Config) WrapTCP(lis net.Listener) net.Listener { + if c == nil { return lis } return &TCPListener{ - acl: cfg, + acl: c, lis: lis, } } diff --git a/internal/auth/oauth_refresh.go b/internal/auth/oauth_refresh.go index fd14332..0fc0335 100644 --- a/internal/auth/oauth_refresh.go +++ b/internal/auth/oauth_refresh.go @@ -190,7 +190,7 @@ func (auth *OIDCProvider) doRefreshToken(ctx context.Context, refreshToken *oaut return nil, refreshToken.err } - idTokenJWT, idToken, err := auth.getIdToken(ctx, newToken) + idTokenJWT, idToken, err := auth.getIDToken(ctx, newToken) if err != nil { refreshToken.err = fmt.Errorf("session: %s - %w: %w", claims.SessionID, ErrRefreshTokenFailure, err) return nil, refreshToken.err diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go index 0b0afc2..312ecd9 100644 --- a/internal/auth/oidc.go +++ b/internal/auth/oidc.go @@ -38,8 +38,8 @@ type ( const ( CookieOauthState = "godoxy_oidc_state" - CookieOauthToken = "godoxy_oauth_token" - CookieOauthSessionToken = "godoxy_session_token" + CookieOauthToken = "godoxy_oauth_token" //nolint:gosec + CookieOauthSessionToken = "godoxy_session_token" //nolint:gosec ) const ( @@ -129,7 +129,7 @@ func optRedirectPostAuth(r *http.Request) oauth2.AuthCodeOption { return oauth2.SetAuthURLParam("redirect_uri", "https://"+requestHost(r)+OIDCPostAuthPath) } -func (auth *OIDCProvider) getIdToken(ctx context.Context, oauthToken *oauth2.Token) (string, *oidc.IDToken, error) { +func (auth *OIDCProvider) getIDToken(ctx context.Context, oauthToken *oauth2.Token) (string, *oidc.IDToken, error) { idTokenJWT, ok := oauthToken.Extra("id_token").(string) if !ok { return "", nil, errMissingIDToken @@ -257,7 +257,7 @@ func (auth *OIDCProvider) PostAuthCallbackHandler(w http.ResponseWriter, r *http return } - idTokenJWT, idToken, err := auth.getIdToken(r.Context(), oauth2Token) + idTokenJWT, idToken, err := auth.getIDToken(r.Context(), oauth2Token) if err != nil { gphttp.ServerError(w, r, err) return diff --git a/internal/autocert/provider_test/custom_test.go b/internal/autocert/provider_test/custom_test.go index af7e1c2..6490761 100644 --- a/internal/autocert/provider_test/custom_test.go +++ b/internal/autocert/provider_test/custom_test.go @@ -212,7 +212,7 @@ func (s *testACMEServer) httpClient() *http.Client { TLSHandshakeTimeout: 30 * time.Second, ResponseHeaderTimeout: 30 * time.Second, TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec }, }, } diff --git a/internal/autocert/provider_test/ovh_test.go b/internal/autocert/provider_test/ovh_test.go index 203e9ef..e268af4 100644 --- a/internal/autocert/provider_test/ovh_test.go +++ b/internal/autocert/provider_test/ovh_test.go @@ -6,7 +6,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/ovh" "github.com/goccy/go-yaml" "github.com/stretchr/testify/require" - "github.com/yusing/go-proxy/internal/utils" + "github.com/yusing/go-proxy/internal/serialization" ) // type Config struct { @@ -45,6 +45,6 @@ oauth2_config: testYaml = testYaml[1:] // remove first \n opt := make(map[string]any) require.NoError(t, yaml.Unmarshal([]byte(testYaml), &opt)) - require.NoError(t, utils.MapUnmarshalValidate(opt, cfg)) + require.NoError(t, serialization.MapUnmarshalValidate(opt, cfg)) require.Equal(t, cfgExpected, cfg) } diff --git a/internal/docker/client.go b/internal/docker/client.go index 3c78806..6d15d88 100644 --- a/internal/docker/client.go +++ b/internal/docker/client.go @@ -190,7 +190,7 @@ func NewClient(host string) (*SharedClient, error) { c.dial = client.Dialer() } if c.addr == "" { - c.addr = c.Client.DaemonHost() + c.addr = c.DaemonHost() } defer log.Debug().Str("host", host).Msg("docker client initialized") diff --git a/internal/homepage/list_icons.go b/internal/homepage/list_icons.go index 2c3d2cf..72497a8 100644 --- a/internal/homepage/list_icons.go +++ b/internal/homepage/list_icons.go @@ -1,6 +1,7 @@ package homepage import ( + "context" "encoding/json" "fmt" "io" @@ -46,30 +47,30 @@ type ( func (icon *IconMeta) Filenames(ref string) []string { filenames := make([]string, 0) if icon.SVG { - filenames = append(filenames, fmt.Sprintf("%s.svg", ref)) + filenames = append(filenames, ref+".svg") if icon.Light { - filenames = append(filenames, fmt.Sprintf("%s-light.svg", ref)) + filenames = append(filenames, ref+"-light.svg") } if icon.Dark { - filenames = append(filenames, fmt.Sprintf("%s-dark.svg", ref)) + filenames = append(filenames, ref+"-dark.svg") } } if icon.PNG { - filenames = append(filenames, fmt.Sprintf("%s.png", ref)) + filenames = append(filenames, ref+".png") if icon.Light { - filenames = append(filenames, fmt.Sprintf("%s-light.png", ref)) + filenames = append(filenames, ref+"-light.png") } if icon.Dark { - filenames = append(filenames, fmt.Sprintf("%s-dark.png", ref)) + filenames = append(filenames, ref+"-dark.png") } } if icon.WebP { - filenames = append(filenames, fmt.Sprintf("%s.webp", ref)) + filenames = append(filenames, ref+".webp") if icon.Light { - filenames = append(filenames, fmt.Sprintf("%s-light.webp", ref)) + filenames = append(filenames, ref+"-light.webp") } if icon.Dark { - filenames = append(filenames, fmt.Sprintf("%s-dark.webp", ref)) + filenames = append(filenames, ref+"-dark.webp") } } return filenames @@ -113,7 +114,7 @@ func InitIconListCache() { } task.OnProgramExit("save_icons_cache", func() { - serialization.SaveJSON(common.IconListCachePath, iconsCache, 0o644) + _ = serialization.SaveJSON(common.IconListCachePath, iconsCache, 0o644) }) } @@ -230,14 +231,17 @@ func updateIcons() error { var httpGet = httpGetImpl -func MockHttpGet(body []byte) { +func MockHTTPGet(body []byte) { httpGet = func(_ string) ([]byte, error) { return body, nil } } func httpGetImpl(url string) ([]byte, error) { - req, err := http.NewRequest(http.MethodGet, url, nil) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } @@ -347,7 +351,7 @@ func UpdateSelfhstIcons() error { } data := make([]SelfhStIcon, 0) - err = json.Unmarshal(body, &data) + err = json.Unmarshal(body, &data) //nolint:musttag if err != nil { return err } diff --git a/internal/homepage/list_icons_test.go b/internal/homepage/list_icons_test.go index 296c635..9569233 100644 --- a/internal/homepage/list_icons_test.go +++ b/internal/homepage/list_icons_test.go @@ -68,6 +68,8 @@ type testCases struct { } func runTests(t *testing.T, iconsCache *Cache, test []testCases) { + t.Helper() + for _, item := range test { icon, ok := iconsCache.Icons[item.Key] if !ok { @@ -89,7 +91,7 @@ func runTests(t *testing.T, iconsCache *Cache, test []testCases) { } func TestListWalkxCodeIcons(t *testing.T) { - MockHttpGet([]byte(walkxcodeIcons)) + MockHTTPGet([]byte(walkxcodeIcons)) if err := UpdateWalkxCodeIcons(); err != nil { t.Fatal(err) } @@ -122,7 +124,7 @@ func TestListWalkxCodeIcons(t *testing.T) { } func TestListSelfhstIcons(t *testing.T) { - MockHttpGet([]byte(selfhstIcons)) + MockHTTPGet([]byte(selfhstIcons)) if err := UpdateSelfhstIcons(); err != nil { t.Fatal(err) } diff --git a/internal/homepage/widgets/widgets.go b/internal/homepage/widgets/widgets.go index 8aea2af..6d62eb4 100644 --- a/internal/homepage/widgets/widgets.go +++ b/internal/homepage/widgets/widgets.go @@ -33,17 +33,18 @@ var widgetProviders = map[string]struct{}{ var ErrInvalidProvider = gperr.New("invalid provider") func (cfg *Config) UnmarshalMap(m map[string]any) error { - cfg.Provider = m["provider"].(string) + var ok bool + cfg.Provider, ok = m["provider"].(string) + if !ok { + return ErrInvalidProvider.Withf("non string") + } if _, ok := widgetProviders[cfg.Provider]; !ok { return ErrInvalidProvider.Subject(cfg.Provider) } delete(m, "provider") - m, ok := m["config"].(map[string]any) + m, ok = m["config"].(map[string]any) if !ok { return gperr.New("invalid config") } - if err := serialization.MapUnmarshalValidate(m, &cfg.Config); err != nil { - return err - } - return nil + return serialization.MapUnmarshalValidate(m, &cfg.Config) } diff --git a/internal/idlewatcher/watcher.go b/internal/idlewatcher/watcher.go index 5d79832..4cf1139 100644 --- a/internal/idlewatcher/watcher.go +++ b/internal/idlewatcher/watcher.go @@ -73,13 +73,13 @@ var dummyHealthCheckConfig = &health.HealthCheckConfig{ } var ( - causeReload = gperr.New("reloaded") - causeContainerDestroy = gperr.New("container destroyed") + causeReload = gperr.New("reloaded") //nolint:errname + causeContainerDestroy = gperr.New("container destroyed") //nolint:errname ) const reqTimeout = 3 * time.Second -// TODO: fix stream type +// TODO: fix stream type. func NewWatcher(parent task.Parent, r routes.Route) (*Watcher, error) { cfg := r.IdlewatcherConfig() key := cfg.Key() diff --git a/internal/jsonstore/jsonstore.go b/internal/jsonstore/jsonstore.go index 25a7506..8fb0df2 100644 --- a/internal/jsonstore/jsonstore.go +++ b/internal/jsonstore/jsonstore.go @@ -2,12 +2,11 @@ package jsonstore import ( "encoding/json" + "maps" "os" "path/filepath" "reflect" - "maps" - "github.com/puzpuzpuz/xsync/v4" "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" @@ -36,8 +35,10 @@ type store interface { json.Unmarshaler } -var stores = make(map[namespace]store) -var storesPath = common.DataDir +var ( + stores = make(map[namespace]store) + storesPath = common.DataDir +) func init() { task.OnProgramExit("save_stores", func() { @@ -117,7 +118,7 @@ func (s *MapStore[VT]) UnmarshalJSON(data []byte) error { } s.Map = xsync.NewMap[string, VT](xsync.WithPresize(len(tmp))) for k, v := range tmp { - s.Map.Store(k, v) + s.Store(k, v) } return nil } diff --git a/internal/logging/accesslog/access_logger.go b/internal/logging/accesslog/access_logger.go index 1568e1a..647181f 100644 --- a/internal/logging/accesslog/access_logger.go +++ b/internal/logging/accesslog/access_logger.go @@ -83,6 +83,9 @@ func NewAccessLogger(parent task.Parent, cfg AnyConfig) (*AccessLogger, error) { if err != nil { return nil, err } + if io == nil { + return nil, nil //nolint:nilnil + } return NewAccessLoggerWithIO(parent, io, cfg), nil } @@ -181,7 +184,7 @@ func (l *AccessLogger) LogError(req *http.Request, err error) { func (l *AccessLogger) LogACL(info *maxmind.IPInfo, blocked bool) { line := l.lineBufPool.Get() defer l.lineBufPool.Put(line) - line = l.ACLFormatter.AppendACLLog(line, info, blocked) + line = l.AppendACLLog(line, info, blocked) if line[len(line)-1] != '\n' { line = append(line, '\n') } @@ -194,7 +197,7 @@ func (l *AccessLogger) ShouldRotate() bool { func (l *AccessLogger) Rotate() (result *RotateResult, err error) { if !l.ShouldRotate() { - return nil, nil + return nil, nil //nolint:nilnil } l.writer.Flush() diff --git a/internal/logging/accesslog/config_test.go b/internal/logging/accesslog/config_test.go index a44199d..37ccc54 100644 --- a/internal/logging/accesslog/config_test.go +++ b/internal/logging/accesslog/config_test.go @@ -5,7 +5,7 @@ import ( "github.com/yusing/go-proxy/internal/docker" . "github.com/yusing/go-proxy/internal/logging/accesslog" - "github.com/yusing/go-proxy/internal/utils" + "github.com/yusing/go-proxy/internal/serialization" expect "github.com/yusing/go-proxy/internal/utils/testing" ) @@ -29,7 +29,7 @@ func TestNewConfig(t *testing.T) { expect.NoError(t, err) var config RequestLoggerConfig - err = utils.MapUnmarshalValidate(parsed, &config) + err = serialization.MapUnmarshalValidate(parsed, &config) expect.NoError(t, err) expect.Equal(t, config.Format, FormatCombined) diff --git a/internal/logging/accesslog/file_logger.go b/internal/logging/accesslog/file_logger.go index 8670aa0..36e791c 100644 --- a/internal/logging/accesslog/file_logger.go +++ b/internal/logging/accesslog/file_logger.go @@ -35,20 +35,19 @@ func newFileIO(path string) (SupportRotate, error) { if opened, ok := openedFiles[path]; ok { opened.refCount.Add() return opened, nil - } else { - // cannot open as O_APPEND as we need Seek and WriteAt - f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644) - if err != nil { - return nil, fmt.Errorf("access log open error: %w", err) - } - if _, err := f.Seek(0, io.SeekEnd); err != nil { - return nil, fmt.Errorf("access log seek error: %w", err) - } - file = &File{f: f, path: path, refCount: utils.NewRefCounter()} - openedFiles[path] = file - go file.closeOnZero() } + // cannot open as O_APPEND as we need Seek and WriteAt + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644) + if err != nil { + return nil, fmt.Errorf("access log open error: %w", err) + } + if _, err := f.Seek(0, io.SeekEnd); err != nil { + return nil, fmt.Errorf("access log seek error: %w", err) + } + file = &File{f: f, path: path, refCount: utils.NewRefCounter()} + openedFiles[path] = file + go file.closeOnZero() return file, nil } diff --git a/internal/logging/logging.go b/internal/logging/logging.go index 787ee27..eae974e 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -1,4 +1,3 @@ -//nolint:zerologlint package logging import ( diff --git a/internal/metrics/period/poller.go b/internal/metrics/period/poller.go index 46a8b11..b068c8f 100644 --- a/internal/metrics/period/poller.go +++ b/internal/metrics/period/poller.go @@ -65,7 +65,7 @@ func NewPoller[T any, AggregateT json.Marshaler]( } func (p *Poller[T, AggregateT]) savePath() string { - return filepath.Join(saveBaseDir, fmt.Sprintf("%s.json", p.name)) + return filepath.Join(saveBaseDir, p.name+".json") } func (p *Poller[T, AggregateT]) load() error { @@ -135,13 +135,14 @@ func (p *Poller[T, AggregateT]) pollWithTimeout(ctx context.Context) { func (p *Poller[T, AggregateT]) Start() { t := task.RootTask("poller." + p.name) + l := log.With().Str("name", p.name).Logger() err := p.load() if err != nil { if !os.IsNotExist(err) { - log.Error().Err(err).Msgf("failed to load last metrics data for %s", p.name) + l.Err(err).Msg("failed to load last metrics data") } } else { - log.Debug().Msgf("Loaded last metrics data for %s, %d entries", p.name, p.period.Total()) + l.Debug().Int("entries", p.period.Total()).Msgf("Loaded last metrics data") } go func() { @@ -154,11 +155,13 @@ func (p *Poller[T, AggregateT]) Start() { gatherErrsTicker.Stop() saveTicker.Stop() - p.save() + if err := p.save(); err != nil { + l.Err(err).Msg("failed to save metrics data") + } t.Finish(nil) }() - log.Debug().Msgf("Starting poller %s with interval %s", p.name, pollInterval) + l.Debug().Dur("interval", pollInterval).Msg("Starting poller") p.pollWithTimeout(t.Context()) diff --git a/internal/net/gphttp/loadbalancer/types/weight.go b/internal/net/gphttp/loadbalancer/types/weight.go index 2bf7d84..2339a27 100644 --- a/internal/net/gphttp/loadbalancer/types/weight.go +++ b/internal/net/gphttp/loadbalancer/types/weight.go @@ -1,3 +1,3 @@ package types -type Weight uint16 +type Weight int diff --git a/internal/net/gphttp/logging.go b/internal/net/gphttp/logging.go index 492b398..9db2f35 100644 --- a/internal/net/gphttp/logging.go +++ b/internal/net/gphttp/logging.go @@ -8,10 +8,10 @@ import ( ) func reqLogger(r *http.Request, level zerolog.Level) *zerolog.Event { - return log.WithLevel(level). - Str("remote", r.RemoteAddr). - Str("host", r.Host). - Str("uri", r.Method+" "+r.RequestURI) + return log.WithLevel(level). //nolint:zerologlint + Str("remote", r.RemoteAddr). + Str("host", r.Host). + Str("uri", r.Method+" "+r.RequestURI) } func LogError(r *http.Request) *zerolog.Event { return reqLogger(r, zerolog.ErrorLevel) } diff --git a/internal/net/gphttp/middleware/cidr_whitelist.go b/internal/net/gphttp/middleware/cidr_whitelist.go index 5b6559b..291b45f 100644 --- a/internal/net/gphttp/middleware/cidr_whitelist.go +++ b/internal/net/gphttp/middleware/cidr_whitelist.go @@ -60,7 +60,7 @@ func (wl *cidrWhitelist) checkIP(w http.ResponseWriter, r *http.Request) bool { ipStr = r.RemoteAddr } ip := net.ParseIP(ipStr) - for _, cidr := range wl.CIDRWhitelistOpts.Allow { + for _, cidr := range wl.Allow { if cidr.Contains(ip) { wl.cachedAddr.Store(r.RemoteAddr, true) allow = true @@ -70,7 +70,7 @@ func (wl *cidrWhitelist) checkIP(w http.ResponseWriter, r *http.Request) bool { } if !allow { wl.cachedAddr.Store(r.RemoteAddr, false) - wl.AddTracef("client %s is forbidden", ipStr).With("allowed CIDRs", wl.CIDRWhitelistOpts.Allow) + wl.AddTracef("client %s is forbidden", ipStr).With("allowed CIDRs", wl.Allow) } } if !allow { diff --git a/internal/net/gphttp/middleware/cidr_whitelist_test.go b/internal/net/gphttp/middleware/cidr_whitelist_test.go index a8c7cee..0d73f29 100644 --- a/internal/net/gphttp/middleware/cidr_whitelist_test.go +++ b/internal/net/gphttp/middleware/cidr_whitelist_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/utils" + "github.com/yusing/go-proxy/internal/serialization" . "github.com/yusing/go-proxy/internal/utils/testing" ) @@ -41,7 +41,7 @@ func TestCIDRWhitelistValidation(t *testing.T) { _, err := CIDRWhiteList.New(OptionsRaw{ "message": testMessage, }) - ExpectError(t, utils.ErrValidationError, err) + ExpectError(t, serialization.ErrValidationError, err) }) t.Run("invalid cidr", func(t *testing.T) { _, err := CIDRWhiteList.New(OptionsRaw{ @@ -56,7 +56,7 @@ func TestCIDRWhitelistValidation(t *testing.T) { "status_code": 600, "message": testMessage, }) - ExpectError(t, utils.ErrValidationError, err) + ExpectError(t, serialization.ErrValidationError, err) }) } diff --git a/internal/net/gphttp/middleware/cloudflare_real_ip.go b/internal/net/gphttp/middleware/cloudflare_real_ip.go index 49da655..59c79d3 100644 --- a/internal/net/gphttp/middleware/cloudflare_real_ip.go +++ b/internal/net/gphttp/middleware/cloudflare_real_ip.go @@ -1,6 +1,7 @@ package middleware import ( + "context" "errors" "fmt" "io" @@ -103,7 +104,15 @@ func tryFetchCFCIDR() (cfCIDRs []*types.CIDR) { } func fetchUpdateCFIPRange(endpoint string, cfCIDRs *[]*types.CIDR) error { - resp, err := http.Get(endpoint) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + + resp, err := http.DefaultClient.Do(req) //nolint:gosec if err != nil { return err } diff --git a/internal/net/gphttp/reverseproxy/reverse_proxy.go b/internal/net/gphttp/reverseproxy/reverse_proxy.go index 886a434..59faafe 100644 --- a/internal/net/gphttp/reverseproxy/reverse_proxy.go +++ b/internal/net/gphttp/reverseproxy/reverse_proxy.go @@ -220,7 +220,6 @@ func (p *ReverseProxy) handler(rw http.ResponseWriter, req *http.Request) { transport := p.Transport ctx := req.Context() - /* trunk-ignore(golangci-lint/revive) */ if ctx.Done() != nil { // CloseNotifier predates context.Context, and has been // entirely superseded by it. If the request contains @@ -352,7 +351,7 @@ func (p *ReverseProxy) handler(rw http.ResponseWriter, req *http.Request) { return nil }, } - outreq = outreq.WithContext(httptrace.WithClientTrace(outreq.Context(), trace)) + outreq = outreq.WithContext(httptrace.WithClientTrace(outreq.Context(), trace)) //nolint:contextcheck res, err := transport.RoundTrip(outreq) @@ -507,18 +506,18 @@ func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.R res.Header = rw.Header() res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above if err := res.Write(brw); err != nil { - /* trunk-ignore(golangci-lint/errorlint) */ + //nolint:errorlint p.errorHandler(rw, req, fmt.Errorf("response write: %s", err), true) return } if err := brw.Flush(); err != nil { - /* trunk-ignore(golangci-lint/errorlint) */ + //nolint:errorlint p.errorHandler(rw, req, fmt.Errorf("response flush: %s", err), true) return } bdp := U.NewBidirectionalPipe(req.Context(), conn, backConn) - /* trunk-ignore(golangci-lint/errcheck) */ + //nolint:errcheck bdp.Start() } diff --git a/internal/net/gphttp/server/server.go b/internal/net/gphttp/server/server.go index d7e71b5..bf2e7f6 100644 --- a/internal/net/gphttp/server/server.go +++ b/internal/net/gphttp/server/server.go @@ -16,7 +16,7 @@ import ( ) type CertProvider interface { - GetCert(*tls.ClientHelloInfo) (*tls.Certificate, error) + GetCert(_ *tls.ClientHelloInfo) (*tls.Certificate, error) } type Server struct { diff --git a/internal/route/provider/docker.go b/internal/route/provider/docker.go index cbe6410..340b628 100755 --- a/internal/route/provider/docker.go +++ b/internal/route/provider/docker.go @@ -106,7 +106,7 @@ func (p *DockerProvider) loadRoutesImpl() (route.Routes, gperr.Error) { // Always non-nil. func (p *DockerProvider) routesFromContainerLabels(container *docker.Container) (route.Routes, gperr.Error) { if !container.IsExplicit && p.IsExplicitOnly() { - return nil, nil + return make(route.Routes, 0), nil } routes := make(route.Routes, len(container.Aliases)) diff --git a/internal/route/rules/rules_test.go b/internal/route/rules/rules_test.go index aa8e8d1..0601e3a 100644 --- a/internal/route/rules/rules_test.go +++ b/internal/route/rules/rules_test.go @@ -3,7 +3,7 @@ package rules import ( "testing" - "github.com/yusing/go-proxy/internal/utils" + "github.com/yusing/go-proxy/internal/serialization" . "github.com/yusing/go-proxy/internal/utils/testing" ) @@ -28,7 +28,7 @@ func TestParseRule(t *testing.T) { var rules struct { Rules Rules } - err := utils.MapUnmarshalValidate(utils.SerializedObject{"rules": test}, &rules) + err := serialization.MapUnmarshalValidate(serialization.SerializedObject{"rules": test}, &rules) ExpectNoError(t, err) ExpectEqual(t, len(rules.Rules), len(test)) ExpectEqual(t, rules.Rules[0].Name, "test") diff --git a/internal/route/types/http_config_test.go b/internal/route/types/http_config_test.go index c6ea8cf..8f41760 100644 --- a/internal/route/types/http_config_test.go +++ b/internal/route/types/http_config_test.go @@ -6,7 +6,7 @@ import ( . "github.com/yusing/go-proxy/internal/route" route "github.com/yusing/go-proxy/internal/route/types" - "github.com/yusing/go-proxy/internal/utils" + "github.com/yusing/go-proxy/internal/serialization" expect "github.com/yusing/go-proxy/internal/utils/testing" ) @@ -40,7 +40,7 @@ func TestHTTPConfigDeserialize(t *testing.T) { t.Run(tt.name, func(t *testing.T) { cfg := Route{} tt.input["host"] = "internal" - err := utils.MapUnmarshalValidate(tt.input, &cfg) + err := serialization.MapUnmarshalValidate(tt.input, &cfg) if err != nil { expect.NoError(t, err) } diff --git a/pkg/version.go b/pkg/version.go index 3c5ea98..c037f0e 100644 --- a/pkg/version.go +++ b/pkg/version.go @@ -18,7 +18,7 @@ func GetLastVersion() Version { func GetVersionHTTPHandler() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(GetVersion().String())) + fmt.Fprint(w, GetVersion().String()) } }