Просмотр исходного кода

Update golangci-lint

tags/v2.1.7^2
9seconds 3 лет назад
Родитель
Сommit
36dad5a2f6
70 измененных файлов: 227 добавлений и 214 удалений
  1. 11
    1
      .golangci.toml
  2. 1
    1
      Makefile
  3. 1
    1
      antireplay/stable_bloom_filter.go
  4. 22
    30
      buildinfo.go
  5. 1
    1
      events/event_stream.go
  6. 12
    12
      internal/cli/access.go
  7. 2
    2
      internal/cli/generate_secret.go
  8. 1
    1
      internal/cli/run.go
  9. 13
    8
      internal/cli/run_proxy.go
  10. 11
    11
      internal/cli/simple_run.go
  11. 2
    2
      internal/config/type_concurrency.go
  12. 2
    2
      internal/config/type_error_rate.go
  13. 1
    1
      internal/config/type_hostport.go
  14. 1
    1
      internal/config/type_port.go
  15. 1
    1
      internal/testlib/capture_output.go
  16. 3
    3
      internal/testlib/mtglib_network_mock.go
  17. 8
    8
      internal/testlib/net_conn_mock.go
  18. 1
    1
      internal/utils/net_listener.go
  19. 8
    0
      ipblocklist/files/doc.go
  20. 1
    1
      ipblocklist/files/http.go
  21. 1
    1
      ipblocklist/files/http_test.go
  22. 1
    1
      ipblocklist/files/local.go
  23. 2
    2
      ipblocklist/firehol.go
  24. 1
    1
      ipblocklist/firehol_test.go
  25. 1
    1
      logger/zerolog_test.go
  26. 3
    3
      mtglib/conns.go
  27. 3
    3
      mtglib/conns_internal_test.go
  28. 3
    3
      mtglib/init.go
  29. 3
    3
      mtglib/internal/faketls/client_hello.go
  30. 6
    6
      mtglib/internal/faketls/conn.go
  31. 7
    7
      mtglib/internal/faketls/conn_test.go
  32. 1
    1
      mtglib/internal/faketls/pools.go
  33. 1
    1
      mtglib/internal/faketls/record/pools.go
  34. 7
    7
      mtglib/internal/faketls/welcome.go
  35. 1
    1
      mtglib/internal/obfuscated2/client_handshake_test.go
  36. 2
    2
      mtglib/internal/obfuscated2/conn.go
  37. 8
    8
      mtglib/internal/obfuscated2/handshake_frame.go
  38. 1
    1
      mtglib/internal/obfuscated2/handshake_frame_internal_test.go
  39. 2
    2
      mtglib/internal/obfuscated2/pools.go
  40. 2
    2
      mtglib/internal/obfuscated2/server_handshake.go
  41. 2
    2
      mtglib/internal/obfuscated2/server_handshake_fuzz_test.go
  42. 2
    2
      mtglib/internal/obfuscated2/server_handshake_test.go
  43. 1
    1
      mtglib/internal/relay/pools.go
  44. 2
    2
      mtglib/internal/relay/relay.go
  45. 3
    3
      mtglib/proxy.go
  46. 4
    4
      mtglib/proxy_test.go
  47. 1
    1
      mtglib/secret.go
  48. 2
    2
      mtglib/stream_context.go
  49. 1
    1
      mtglib/stream_context_internal_test.go
  50. 5
    5
      network/circuit_breaker.go
  51. 4
    4
      network/circuit_breaker_internal_test.go
  52. 2
    2
      network/default.go
  53. 1
    1
      network/default_test.go
  54. 2
    4
      network/dns_resolver.go
  55. 2
    2
      network/init_internal_test.go
  56. 4
    4
      network/init_test.go
  57. 1
    1
      network/load_balanced_socks5_test.go
  58. 1
    1
      network/network.go
  59. 4
    4
      network/network_test.go
  60. 1
    1
      network/proxy_dialer.go
  61. 5
    5
      network/proxy_dialer_internal_test.go
  62. 2
    2
      network/sockopts.go
  63. 3
    3
      network/sockopts_unix.go
  64. 1
    1
      network/socks5.go
  65. 2
    2
      network/socks5_test.go
  66. 1
    1
      stats/pools.go
  67. 3
    3
      stats/prometheus.go
  68. 4
    4
      stats/prometheus_test.go
  69. 1
    1
      stats/statsd.go
  70. 1
    1
      stats/statsd_test.go

+ 11
- 1
.golangci.toml Просмотреть файл

9
 
9
 
10
 [linters]
10
 [linters]
11
 enable-all = true
11
 enable-all = true
12
-disable = ["thelper", "ireturn", "varnamelen", "gochecknoglobals", "gas", "goerr113", "exhaustivestruct", "containedctx"]
12
+disable = [
13
+    "containedctx",
14
+    "exhaustivestruct",
15
+    "exhaustruct",
16
+    "gas",
17
+    "gochecknoglobals",
18
+    "goerr113",
19
+    "ireturn",
20
+    "thelper",
21
+    "varnamelen",
22
+]

+ 1
- 1
Makefile Просмотреть файл

2
 IMAGE_NAME   := mtg
2
 IMAGE_NAME   := mtg
3
 APP_NAME     := $(IMAGE_NAME)
3
 APP_NAME     := $(IMAGE_NAME)
4
 
4
 
5
-GOLANGCI_LINT_VERSION := v1.47.3
5
+GOLANGCI_LINT_VERSION := v1.48.0
6
 
6
 
7
 VERSION            := $(shell git describe --exact-match HEAD 2>/dev/null || git describe --tags --always)
7
 VERSION            := $(shell git describe --exact-match HEAD 2>/dev/null || git describe --tags --always)
8
 COMMON_BUILD_FLAGS := -trimpath -mod=readonly -ldflags="-extldflags '-static' -s -w -X 'main.version=$(VERSION)'"
8
 COMMON_BUILD_FLAGS := -trimpath -mod=readonly -ldflags="-extldflags '-static' -s -w -X 'main.version=$(VERSION)'"

+ 1
- 1
antireplay/stable_bloom_filter.go Просмотреть файл

42
 		errorRate = DefaultStableBloomFilterErrorRate
42
 		errorRate = DefaultStableBloomFilterErrorRate
43
 	}
43
 	}
44
 
44
 
45
-	sf := boom.NewDefaultStableBloomFilter(byteSize*8, errorRate) // nolint: gomnd
45
+	sf := boom.NewDefaultStableBloomFilter(byteSize*8, errorRate) //nolint: gomnd
46
 	sf.SetHash(xxhash.New64())
46
 	sf.SetHash(xxhash.New64())
47
 
47
 
48
 	return &stableBloomFilter{
48
 	return &stableBloomFilter{

+ 22
- 30
buildinfo.go Просмотреть файл

21
 )
21
 )
22
 
22
 
23
 func getVersion() string {
23
 func getVersion() string {
24
-	goVersion, date, commit, modulesChecksum, dirty := getVersionData()
25
-
26
-	dirtySuffix := ""
27
-	if dirty {
28
-		dirtySuffix = " [dirty]"
29
-	}
30
-
31
-	return fmt.Sprintf("%s (%s: %s on %s%s, modules checksum %s)",
32
-		version,
33
-		goVersion,
34
-		date.Format(time.RFC3339),
35
-		commit,
36
-		dirtySuffix,
37
-		modulesChecksum)
38
-}
39
-
40
-func getVersionData() (goVersion string, date time.Time, commit string, modulesChecksum string, dirty bool) {
41
-	date = time.Now()
42
-
43
 	buildInfo, ok := debug.ReadBuildInfo()
24
 	buildInfo, ok := debug.ReadBuildInfo()
44
 	if !ok {
25
 	if !ok {
45
-		return
26
+		return version
46
 	}
27
 	}
47
 
28
 
48
-	goVersion = buildInfo.GoVersion
29
+	date := time.Now()
30
+	commit := ""
31
+	goVersion := buildInfo.GoVersion
32
+	dirtySuffix := ""
49
 
33
 
50
 	for _, setting := range buildInfo.Settings {
34
 	for _, setting := range buildInfo.Settings {
51
 		switch setting.Key {
35
 		switch setting.Key {
54
 		case "vcs.revision":
38
 		case "vcs.revision":
55
 			commit = setting.Value
39
 			commit = setting.Value
56
 		case "vcs.modified":
40
 		case "vcs.modified":
57
-			dirty, _ = strconv.ParseBool(setting.Value)
41
+			if dirty, _ := strconv.ParseBool(setting.Value); dirty {
42
+				dirtySuffix = " [dirty]"
43
+			}
58
 		}
44
 		}
59
 	}
45
 	}
60
 
46
 
62
 	if _, err := io.WriteString(hasher, buildInfo.Path); err != nil {
48
 	if _, err := io.WriteString(hasher, buildInfo.Path); err != nil {
63
 		panic(err)
49
 		panic(err)
64
 	}
50
 	}
65
-	binary.Write(hasher, binary.LittleEndian, uint64(1+len(buildInfo.Deps)))
51
+
52
+	binary.Write(hasher, binary.LittleEndian, uint64(1+len(buildInfo.Deps))) //nolint: errcheck
66
 
53
 
67
 	sort.Slice(buildInfo.Deps, func(i, j int) bool {
54
 	sort.Slice(buildInfo.Deps, func(i, j int) bool {
68
 		return buildInfo.Deps[i].Path > buildInfo.Deps[j].Path
55
 		return buildInfo.Deps[i].Path > buildInfo.Deps[j].Path
69
 	})
56
 	})
70
 
57
 
71
 	buildInfoCheckSumModule(hasher, &buildInfo.Main)
58
 	buildInfoCheckSumModule(hasher, &buildInfo.Main)
59
+
72
 	for _, module := range buildInfo.Deps {
60
 	for _, module := range buildInfo.Deps {
73
 		buildInfoCheckSumModule(hasher, module)
61
 		buildInfoCheckSumModule(hasher, module)
74
 	}
62
 	}
75
 
63
 
76
-	modulesChecksum = base64.StdEncoding.EncodeToString(hasher.Sum(nil))
77
-
78
-	return
64
+	return fmt.Sprintf("%s (%s: %s on %s%s, modules checksum %s)",
65
+		version,
66
+		goVersion,
67
+		date.Format(time.RFC3339),
68
+		commit,
69
+		dirtySuffix,
70
+		base64.StdEncoding.EncodeToString(hasher.Sum(nil)))
79
 }
71
 }
80
 
72
 
81
 func buildInfoCheckSumModule(w io.Writer, module *debug.Module) {
73
 func buildInfoCheckSumModule(w io.Writer, module *debug.Module) {
82
-	w.Write([]byte{buildInfoModuleStart})
74
+	w.Write([]byte{buildInfoModuleStart}) //nolint: errcheck
83
 
75
 
84
 	if _, err := io.WriteString(w, module.Path); err != nil {
76
 	if _, err := io.WriteString(w, module.Path); err != nil {
85
 		panic(err)
77
 		panic(err)
86
 	}
78
 	}
87
 
79
 
88
-	w.Write([]byte{buildInfoModuleDelimeter})
80
+	w.Write([]byte{buildInfoModuleDelimeter}) //nolint: errcheck
89
 
81
 
90
 	if _, err := io.WriteString(w, module.Version); err != nil {
82
 	if _, err := io.WriteString(w, module.Version); err != nil {
91
 		panic(err)
83
 		panic(err)
92
 	}
84
 	}
93
 
85
 
94
-	w.Write([]byte{buildInfoModuleDelimeter})
86
+	w.Write([]byte{buildInfoModuleDelimeter}) //nolint: errcheck
95
 
87
 
96
 	if _, err := io.WriteString(w, module.Sum); err != nil {
88
 	if _, err := io.WriteString(w, module.Sum); err != nil {
97
 		panic(err)
89
 		panic(err)
98
 	}
90
 	}
99
 
91
 
100
-	w.Write([]byte{buildInfoModuleFinish})
92
+	w.Write([]byte{buildInfoModuleFinish}) //nolint: errcheck
101
 }
93
 }

+ 1
- 1
events/event_stream.go Просмотреть файл

77
 	return rv
77
 	return rv
78
 }
78
 }
79
 
79
 
80
-func eventStreamProcessor(ctx context.Context, eventChan <-chan mtglib.Event, observer Observer) { // nolint: cyclop
80
+func eventStreamProcessor(ctx context.Context, eventChan <-chan mtglib.Event, observer Observer) { //nolint: cyclop
81
 	defer observer.Shutdown()
81
 	defer observer.Shutdown()
82
 
82
 
83
 	for {
83
 	for {

+ 12
- 12
internal/cli/access.go Просмотреть файл

31
 type accessResponseURLs struct {
31
 type accessResponseURLs struct {
32
 	IP        net.IP `json:"ip"`
32
 	IP        net.IP `json:"ip"`
33
 	Port      uint   `json:"port"`
33
 	Port      uint   `json:"port"`
34
-	TgURL     string `json:"tg_url"`     // nolint: tagliatelle
35
-	TgQrCode  string `json:"tg_qrcode"`  // nolint: tagliatelle
36
-	TmeURL    string `json:"tme_url"`    // nolint: tagliatelle
37
-	TmeQrCode string `json:"tme_qrcode"` // nolint: tagliatelle
34
+	TgURL     string `json:"tg_url"`     //nolint: tagliatelle
35
+	TgQrCode  string `json:"tg_qrcode"`  //nolint: tagliatelle
36
+	TmeURL    string `json:"tme_url"`    //nolint: tagliatelle
37
+	TmeQrCode string `json:"tme_qrcode"` //nolint: tagliatelle
38
 }
38
 }
39
 
39
 
40
 type Access struct {
40
 type Access struct {
41
-	ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"`                 // nolint: lll
42
-	PublicIPv4 net.IP `kong:"help='Public IPv4 address for proxy. By default it is resolved via remote website',name='ipv4',short='i'"`   // nolint: lll
43
-	PublicIPv6 net.IP `kong:"help='Public IPv6 address for proxy. By default it is resolved via remote website',name='ipv6',short='I'"`   // nolint: lll
44
-	Port       uint   `kong:"help='Port number. Default port is taken from configuration file, bind-to parameter',type:'uint',short='p'"` // nolint: lll
41
+	ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"`                 //nolint: lll
42
+	PublicIPv4 net.IP `kong:"help='Public IPv4 address for proxy. By default it is resolved via remote website',name='ipv4',short='i'"`   //nolint: lll
43
+	PublicIPv6 net.IP `kong:"help='Public IPv6 address for proxy. By default it is resolved via remote website',name='ipv6',short='I'"`   //nolint: lll
44
+	Port       uint   `kong:"help='Port number. Default port is taken from configuration file, bind-to parameter',type:'uint',short='p'"` //nolint: lll
45
 	Hex        bool   `kong:"help='Print secret in hex encoding.',short='x'"`
45
 	Hex        bool   `kong:"help='Print secret in hex encoding.',short='x'"`
46
 }
46
 }
47
 
47
 
61
 	}
61
 	}
62
 
62
 
63
 	wg := &sync.WaitGroup{}
63
 	wg := &sync.WaitGroup{}
64
-	wg.Add(2) // nolint: gomnd
64
+	wg.Add(2) //nolint: gomnd
65
 
65
 
66
 	go func() {
66
 	go func() {
67
 		defer wg.Done()
67
 		defer wg.Done()
108
 
108
 
109
 func (a *Access) getIP(ntw mtglib.Network, protocol string) net.IP {
109
 func (a *Access) getIP(ntw mtglib.Network, protocol string) net.IP {
110
 	client := ntw.MakeHTTPClient(func(ctx context.Context, network, address string) (essentials.Conn, error) {
110
 	client := ntw.MakeHTTPClient(func(ctx context.Context, network, address string) (essentials.Conn, error) {
111
-		return ntw.DialContext(ctx, protocol, address) // nolint: wrapcheck
111
+		return ntw.DialContext(ctx, protocol, address) //nolint: wrapcheck
112
 	})
112
 	})
113
 
113
 
114
-	req, err := http.NewRequest(http.MethodGet, "https://ifconfig.co", nil) // nolint: noctx
114
+	req, err := http.NewRequest(http.MethodGet, "https://ifconfig.co", nil) //nolint: noctx
115
 	if err != nil {
115
 	if err != nil {
116
 		panic(err)
116
 		panic(err)
117
 	}
117
 	}
128
 	}
128
 	}
129
 
129
 
130
 	defer func() {
130
 	defer func() {
131
-		io.Copy(io.Discard, resp.Body) // nolint: errcheck
131
+		io.Copy(io.Discard, resp.Body) //nolint: errcheck
132
 		resp.Body.Close()
132
 		resp.Body.Close()
133
 	}()
133
 	}()
134
 
134
 

+ 2
- 2
internal/cli/generate_secret.go Просмотреть файл

15
 	secret := mtglib.GenerateSecret(cli.GenerateSecret.HostName)
15
 	secret := mtglib.GenerateSecret(cli.GenerateSecret.HostName)
16
 
16
 
17
 	if g.Hex {
17
 	if g.Hex {
18
-		fmt.Println(secret.Hex()) // nolint: forbidigo
18
+		fmt.Println(secret.Hex()) //nolint: forbidigo
19
 	} else {
19
 	} else {
20
-		fmt.Println(secret.Base64()) // nolint: forbidigo
20
+		fmt.Println(secret.Base64()) //nolint: forbidigo
21
 	}
21
 	}
22
 
22
 
23
 	return nil
23
 	return nil

+ 1
- 1
internal/cli/run.go Просмотреть файл

7
 )
7
 )
8
 
8
 
9
 type Run struct {
9
 type Run struct {
10
-	ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` // nolint: lll
10
+	ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
11
 }
11
 }
12
 
12
 
13
 func (r *Run) Run(cli *CLI, version string) error {
13
 func (r *Run) Run(cli *CLI, version string) error {

+ 13
- 8
internal/cli/run_proxy.go Просмотреть файл

49
 	}
49
 	}
50
 
50
 
51
 	if len(conf.Network.Proxies) == 0 {
51
 	if len(conf.Network.Proxies) == 0 {
52
-		return network.NewNetwork(baseDialer, userAgent, dohIP, httpTimeout) // nolint: wrapcheck
52
+		return network.NewNetwork(baseDialer, userAgent, dohIP, httpTimeout) //nolint: wrapcheck
53
 	}
53
 	}
54
 
54
 
55
 	proxyURLs := make([]*url.URL, 0, len(conf.Network.Proxies))
55
 	proxyURLs := make([]*url.URL, 0, len(conf.Network.Proxies))
66
 			return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
66
 			return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
67
 		}
67
 		}
68
 
68
 
69
-		return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) // nolint: wrapcheck
69
+		return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) //nolint: wrapcheck
70
 	}
70
 	}
71
 
71
 
72
 	socksDialer, err := network.NewLoadBalancedSocks5Dialer(baseDialer, proxyURLs)
72
 	socksDialer, err := network.NewLoadBalancedSocks5Dialer(baseDialer, proxyURLs)
74
 		return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
74
 		return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
75
 	}
75
 	}
76
 
76
 
77
-	return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) // nolint: wrapcheck
77
+	return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout) //nolint: wrapcheck
78
 }
78
 }
79
 
79
 
80
 func makeAntiReplayCache(conf *config.Config) mtglib.AntiReplayCache {
80
 func makeAntiReplayCache(conf *config.Config) mtglib.AntiReplayCache {
127
 	logger mtglib.Logger,
127
 	logger mtglib.Logger,
128
 	ntw mtglib.Network,
128
 	ntw mtglib.Network,
129
 	updateCallback ipblocklist.FireholUpdateCallback,
129
 	updateCallback ipblocklist.FireholUpdateCallback,
130
-) (allowlist mtglib.IPBlocklist, err error) {
130
+) (mtglib.IPBlocklist, error) {
131
+	var (
132
+		allowlist mtglib.IPBlocklist
133
+		err       error
134
+	)
135
+
131
 	if !conf.Enabled.Get(false) {
136
 	if !conf.Enabled.Get(false) {
132
 		allowlist, err = ipblocklist.NewFireholFromFiles(
137
 		allowlist, err = ipblocklist.NewFireholFromFiles(
133
 			logger.Named("ipblocklist"),
138
 			logger.Named("ipblocklist"),
159
 }
164
 }
160
 
165
 
161
 func makeEventStream(conf *config.Config, logger mtglib.Logger) (mtglib.EventStream, error) {
166
 func makeEventStream(conf *config.Config, logger mtglib.Logger) (mtglib.EventStream, error) {
162
-	factories := make([]events.ObserverFactory, 0, 2) // nolint: gomnd
167
+	factories := make([]events.ObserverFactory, 0, 2) //nolint: gomnd
163
 
168
 
164
 	if conf.Stats.StatsD.Enabled.Get(false) {
169
 	if conf.Stats.StatsD.Enabled.Get(false) {
165
 		statsdFactory, err := stats.NewStatsd(
170
 		statsdFactory, err := stats.NewStatsd(
185
 			return nil, fmt.Errorf("cannot start a listener for prometheus: %w", err)
190
 			return nil, fmt.Errorf("cannot start a listener for prometheus: %w", err)
186
 		}
191
 		}
187
 
192
 
188
-		go prometheus.Serve(listener) // nolint: errcheck
193
+		go prometheus.Serve(listener) //nolint: errcheck
189
 
194
 
190
 		factories = append(factories, prometheus.Make)
195
 		factories = append(factories, prometheus.Make)
191
 	}
196
 	}
197
 	return events.NewNoopStream(), nil
202
 	return events.NewNoopStream(), nil
198
 }
203
 }
199
 
204
 
200
-func runProxy(conf *config.Config, version string) error { // nolint: funlen
205
+func runProxy(conf *config.Config, version string) error { //nolint: funlen
201
 	logger := makeLogger(conf)
206
 	logger := makeLogger(conf)
202
 
207
 
203
 	logger.BindJSON("configuration", conf.String()).Debug("configuration")
208
 	logger.BindJSON("configuration", conf.String()).Debug("configuration")
263
 
268
 
264
 	ctx := utils.RootContext()
269
 	ctx := utils.RootContext()
265
 
270
 
266
-	go proxy.Serve(listener) // nolint: errcheck
271
+	go proxy.Serve(listener) //nolint: errcheck
267
 
272
 
268
 	<-ctx.Done()
273
 	<-ctx.Done()
269
 	listener.Close()
274
 	listener.Close()

+ 11
- 11
internal/cli/simple_run.go Просмотреть файл

13
 	BindTo string `kong:"arg,required,name='bind-to',help='A host:port to bind proxy to.'"`
13
 	BindTo string `kong:"arg,required,name='bind-to',help='A host:port to bind proxy to.'"`
14
 	Secret string `kong:"arg,required,name='secret',help='Proxy secret.'"`
14
 	Secret string `kong:"arg,required,name='secret',help='Proxy secret.'"`
15
 
15
 
16
-	Debug               bool          `kong:"name='debug',short='d',help='Run in debug mode.'"`                                                                        // nolint: lll
17
-	Concurrency         uint64        `kong:"name='concurrency',short='c',default='8192',help='Max number of concurrent connection to proxy.'"`                        // nolint: lll
18
-	TCPBuffer           string        `kong:"name='tcp-buffer',short='b',default='4KB',help='Deprecated and ignored'"`                                                 // nolint: lll
19
-	PreferIP            string        `kong:"name='prefer-ip',short='i',default='prefer-ipv6',help='IP preference. By default we prefer IPv6 with fallback to IPv4.'"` // nolint: lll
20
-	DomainFrontingPort  uint64        `kong:"name='domain-fronting-port',short='p',default='443',help='A port to access for domain fronting.'"`                        // nolint: lll
21
-	DOHIP               net.IP        `kong:"name='doh-ip',short='n',default='9.9.9.9',help='IP address of DNS-over-HTTP to use.'"`                                    // nolint: lll
22
-	Timeout             time.Duration `kong:"name='timeout',short='t',default='10s',help='Network timeout to use'"`                                                    // nolint: lll
23
-	AntiReplayCacheSize string        `kong:"name='antireplay-cache-size',short='a',default='1MB',help='A size of anti-replay cache to use.'"`                         // nolint: lll
16
+	Debug               bool          `kong:"name='debug',short='d',help='Run in debug mode.'"`                                                                        //nolint: lll
17
+	Concurrency         uint64        `kong:"name='concurrency',short='c',default='8192',help='Max number of concurrent connection to proxy.'"`                        //nolint: lll
18
+	TCPBuffer           string        `kong:"name='tcp-buffer',short='b',default='4KB',help='Deprecated and ignored'"`                                                 //nolint: lll
19
+	PreferIP            string        `kong:"name='prefer-ip',short='i',default='prefer-ipv6',help='IP preference. By default we prefer IPv6 with fallback to IPv4.'"` //nolint: lll
20
+	DomainFrontingPort  uint64        `kong:"name='domain-fronting-port',short='p',default='443',help='A port to access for domain fronting.'"`                        //nolint: lll
21
+	DOHIP               net.IP        `kong:"name='doh-ip',short='n',default='9.9.9.9',help='IP address of DNS-over-HTTP to use.'"`                                    //nolint: lll
22
+	Timeout             time.Duration `kong:"name='timeout',short='t',default='10s',help='Network timeout to use'"`                                                    //nolint: lll
23
+	AntiReplayCacheSize string        `kong:"name='antireplay-cache-size',short='a',default='1MB',help='A size of anti-replay cache to use.'"`                         //nolint: lll
24
 }
24
 }
25
 
25
 
26
-func (s *SimpleRun) Run(cli *CLI, version string) error { // nolint: cyclop
26
+func (s *SimpleRun) Run(cli *CLI, version string) error { //nolint: cyclop
27
 	conf := &config.Config{}
27
 	conf := &config.Config{}
28
 
28
 
29
 	if err := conf.BindTo.Set(s.BindTo); err != nil {
29
 	if err := conf.BindTo.Set(s.BindTo); err != nil {
34
 		return fmt.Errorf("incorrect secret: %w", err)
34
 		return fmt.Errorf("incorrect secret: %w", err)
35
 	}
35
 	}
36
 
36
 
37
-	if err := conf.Concurrency.Set(strconv.FormatUint(s.Concurrency, 10)); err != nil { // nolint: gomnd
37
+	if err := conf.Concurrency.Set(strconv.FormatUint(s.Concurrency, 10)); err != nil { //nolint: gomnd
38
 		return fmt.Errorf("incorrect concurrency: %w", err)
38
 		return fmt.Errorf("incorrect concurrency: %w", err)
39
 	}
39
 	}
40
 
40
 
42
 		return fmt.Errorf("incorrect prefer-ip: %w", err)
42
 		return fmt.Errorf("incorrect prefer-ip: %w", err)
43
 	}
43
 	}
44
 
44
 
45
-	if err := conf.DomainFrontingPort.Set(strconv.FormatUint(s.DomainFrontingPort, 10)); err != nil { // nolint: gomnd
45
+	if err := conf.DomainFrontingPort.Set(strconv.FormatUint(s.DomainFrontingPort, 10)); err != nil { //nolint: gomnd
46
 		return fmt.Errorf("incorrect domain-fronting-port: %w", err)
46
 		return fmt.Errorf("incorrect domain-fronting-port: %w", err)
47
 	}
47
 	}
48
 
48
 

+ 2
- 2
internal/config/type_concurrency.go Просмотреть файл

10
 }
10
 }
11
 
11
 
12
 func (t *TypeConcurrency) Set(value string) error {
12
 func (t *TypeConcurrency) Set(value string) error {
13
-	concurrencyValue, err := strconv.ParseUint(value, 10, 16) // nolint: gomnd
13
+	concurrencyValue, err := strconv.ParseUint(value, 10, 16) //nolint: gomnd
14
 	if err != nil {
14
 	if err != nil {
15
 		return fmt.Errorf("value is not uint (%s): %w", value, err)
15
 		return fmt.Errorf("value is not uint (%s): %w", value, err)
16
 	}
16
 	}
41
 }
41
 }
42
 
42
 
43
 func (t TypeConcurrency) String() string {
43
 func (t TypeConcurrency) String() string {
44
-	return strconv.FormatUint(uint64(t.Value), 10) // nolint: gomnd
44
+	return strconv.FormatUint(uint64(t.Value), 10) //nolint: gomnd
45
 }
45
 }

+ 2
- 2
internal/config/type_error_rate.go Просмотреть файл

12
 }
12
 }
13
 
13
 
14
 func (t *TypeErrorRate) Set(value string) error {
14
 func (t *TypeErrorRate) Set(value string) error {
15
-	parsedValue, err := strconv.ParseFloat(value, 64) // nolint: gomnd
15
+	parsedValue, err := strconv.ParseFloat(value, 64) //nolint: gomnd
16
 	if err != nil {
16
 	if err != nil {
17
 		return fmt.Errorf("value is not a float (%s): %w", value, err)
17
 		return fmt.Errorf("value is not a float (%s): %w", value, err)
18
 	}
18
 	}
43
 }
43
 }
44
 
44
 
45
 func (t TypeErrorRate) String() string {
45
 func (t TypeErrorRate) String() string {
46
-	return strconv.FormatFloat(t.Value, 'f', -1, 64) // nolint: gomnd
46
+	return strconv.FormatFloat(t.Value, 'f', -1, 64) //nolint: gomnd
47
 }
47
 }

+ 1
- 1
internal/config/type_hostport.go Просмотреть файл

18
 		return fmt.Errorf("incorrect host:port value (%v): %w", value, err)
18
 		return fmt.Errorf("incorrect host:port value (%v): %w", value, err)
19
 	}
19
 	}
20
 
20
 
21
-	portValue, err := strconv.ParseUint(port, 10, 16) // nolint: gomnd
21
+	portValue, err := strconv.ParseUint(port, 10, 16) //nolint: gomnd
22
 	if err != nil {
22
 	if err != nil {
23
 		return fmt.Errorf("incorrect port number (%v): %w", value, err)
23
 		return fmt.Errorf("incorrect port number (%v): %w", value, err)
24
 	}
24
 	}

+ 1
- 1
internal/config/type_port.go Просмотреть файл

10
 }
10
 }
11
 
11
 
12
 func (t *TypePort) Set(value string) error {
12
 func (t *TypePort) Set(value string) error {
13
-	portValue, err := strconv.ParseUint(value, 10, 16) // nolint: gomnd
13
+	portValue, err := strconv.ParseUint(value, 10, 16) //nolint: gomnd
14
 	if err != nil {
14
 	if err != nil {
15
 		return fmt.Errorf("incorrect port number (%v): %w", value, err)
15
 		return fmt.Errorf("incorrect port number (%v): %w", value, err)
16
 	}
16
 	}

+ 1
- 1
internal/testlib/capture_output.go Просмотреть файл

27
 	closeChan := make(chan bool)
27
 	closeChan := make(chan bool)
28
 
28
 
29
 	go func() {
29
 	go func() {
30
-		io.Copy(buf, reader) // nolint: errcheck
30
+		io.Copy(buf, reader) //nolint: errcheck
31
 		close(closeChan)
31
 		close(closeChan)
32
 	}()
32
 	}()
33
 
33
 

+ 3
- 3
internal/testlib/mtglib_network_mock.go Просмотреть файл

15
 func (m *MtglibNetworkMock) Dial(network, address string) (essentials.Conn, error) {
15
 func (m *MtglibNetworkMock) Dial(network, address string) (essentials.Conn, error) {
16
 	args := m.Called(network, address)
16
 	args := m.Called(network, address)
17
 
17
 
18
-	return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
18
+	return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
19
 }
19
 }
20
 
20
 
21
 func (m *MtglibNetworkMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
21
 func (m *MtglibNetworkMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
22
 	args := m.Called(ctx, network, address)
22
 	args := m.Called(ctx, network, address)
23
 
23
 
24
-	return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
24
+	return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
25
 }
25
 }
26
 
26
 
27
 func (m *MtglibNetworkMock) MakeHTTPClient(dialFunc func(ctx context.Context,
27
 func (m *MtglibNetworkMock) MakeHTTPClient(dialFunc func(ctx context.Context,
28
 	network, address string) (essentials.Conn, error),
28
 	network, address string) (essentials.Conn, error),
29
 ) *http.Client {
29
 ) *http.Client {
30
-	return m.Called(dialFunc).Get(0).(*http.Client) // nolint: forcetypeassert
30
+	return m.Called(dialFunc).Get(0).(*http.Client) //nolint: forcetypeassert
31
 }
31
 }

+ 8
- 8
internal/testlib/net_conn_mock.go Просмотреть файл

24
 }
24
 }
25
 
25
 
26
 func (n *EssentialsConnMock) Close() error {
26
 func (n *EssentialsConnMock) Close() error {
27
-	return n.Called().Error(0) // nolint: wrapcheck
27
+	return n.Called().Error(0) //nolint: wrapcheck
28
 }
28
 }
29
 
29
 
30
 func (n *EssentialsConnMock) CloseRead() error {
30
 func (n *EssentialsConnMock) CloseRead() error {
31
-	return n.Called().Error(0) // nolint: wrapcheck
31
+	return n.Called().Error(0) //nolint: wrapcheck
32
 }
32
 }
33
 
33
 
34
 func (n *EssentialsConnMock) CloseWrite() error {
34
 func (n *EssentialsConnMock) CloseWrite() error {
35
-	return n.Called().Error(0) // nolint: wrapcheck
35
+	return n.Called().Error(0) //nolint: wrapcheck
36
 }
36
 }
37
 
37
 
38
 func (n *EssentialsConnMock) LocalAddr() net.Addr {
38
 func (n *EssentialsConnMock) LocalAddr() net.Addr {
39
-	return n.Called().Get(0).(net.Addr) // nolint: forcetypeassert
39
+	return n.Called().Get(0).(net.Addr) //nolint: forcetypeassert
40
 }
40
 }
41
 
41
 
42
 func (n *EssentialsConnMock) RemoteAddr() net.Addr {
42
 func (n *EssentialsConnMock) RemoteAddr() net.Addr {
43
-	return n.Called().Get(0).(net.Addr) // nolint: forcetypeassert
43
+	return n.Called().Get(0).(net.Addr) //nolint: forcetypeassert
44
 }
44
 }
45
 
45
 
46
 func (n *EssentialsConnMock) SetDeadline(t time.Time) error {
46
 func (n *EssentialsConnMock) SetDeadline(t time.Time) error {
47
-	return n.Called(t).Error(0) // nolint: wrapcheck
47
+	return n.Called(t).Error(0) //nolint: wrapcheck
48
 }
48
 }
49
 
49
 
50
 func (n *EssentialsConnMock) SetReadDeadline(t time.Time) error {
50
 func (n *EssentialsConnMock) SetReadDeadline(t time.Time) error {
51
-	return n.Called(t).Error(0) // nolint: wrapcheck
51
+	return n.Called(t).Error(0) //nolint: wrapcheck
52
 }
52
 }
53
 
53
 
54
 func (n *EssentialsConnMock) SetWriteDeadline(t time.Time) error {
54
 func (n *EssentialsConnMock) SetWriteDeadline(t time.Time) error {
55
-	return n.Called(t).Error(0) // nolint: wrapcheck
55
+	return n.Called(t).Error(0) //nolint: wrapcheck
56
 }
56
 }

+ 1
- 1
internal/utils/net_listener.go Просмотреть файл

14
 func (l Listener) Accept() (net.Conn, error) {
14
 func (l Listener) Accept() (net.Conn, error) {
15
 	conn, err := l.Listener.Accept()
15
 	conn, err := l.Listener.Accept()
16
 	if err != nil {
16
 	if err != nil {
17
-		return nil, err // nolint: wrapcheck
17
+		return nil, err //nolint: wrapcheck
18
 	}
18
 	}
19
 
19
 
20
 	if err := network.SetClientSocketOptions(conn, 0); err != nil {
20
 	if err := network.SetClientSocketOptions(conn, 0); err != nil {

+ 8
- 0
ipblocklist/files/doc.go Просмотреть файл

1
+// files defines a set of abstraction for 'files': an openable entities that
2
+// could be read after.
3
+//
4
+// This is not a file on a filesystem of your local machine, it also can
5
+// include "in memory" files or even remote ones, like HTTP endpoints. If you
6
+// make a GET request to HTTP endpoint, then a body is readable and you can
7
+// consider it as an openable file.
8
+package files

+ 1
- 1
ipblocklist/files/http.go Просмотреть файл

22
 	response, err := h.http.Do(request)
22
 	response, err := h.http.Do(request)
23
 	if err != nil {
23
 	if err != nil {
24
 		if response != nil {
24
 		if response != nil {
25
-			io.Copy(io.Discard, response.Body) // nolint: errcheck
25
+			io.Copy(io.Discard, response.Body) //nolint: errcheck
26
 			response.Body.Close()
26
 			response.Body.Close()
27
 		}
27
 		}
28
 
28
 

+ 1
- 1
ipblocklist/files/http_test.go Просмотреть файл

22
 }
22
 }
23
 
23
 
24
 func (suite *HTTPTestSuite) makeFile(path string) (files.File, error) {
24
 func (suite *HTTPTestSuite) makeFile(path string) (files.File, error) {
25
-	return files.NewHTTP(suite.httpClient, suite.httpServer.URL+"/"+path) // nolint: wrapcheck
25
+	return files.NewHTTP(suite.httpClient, suite.httpServer.URL+"/"+path) //nolint: wrapcheck
26
 }
26
 }
27
 
27
 
28
 func (suite *HTTPTestSuite) SetupSuite() {
28
 func (suite *HTTPTestSuite) SetupSuite() {

+ 1
- 1
ipblocklist/files/local.go Просмотреть файл

12
 }
12
 }
13
 
13
 
14
 func (l localFile) Open(ctx context.Context) (io.ReadCloser, error) {
14
 func (l localFile) Open(ctx context.Context) (io.ReadCloser, error) {
15
-	return os.Open(l.path) // nolint: wrapcheck
15
+	return os.Open(l.path) //nolint: wrapcheck
16
 }
16
 }
17
 
17
 
18
 func (l localFile) String() string {
18
 func (l localFile) String() string {

+ 2
- 2
ipblocklist/firehol.go Просмотреть файл

19
 var (
19
 var (
20
 	fireholRegexpComment = regexp.MustCompile(`\s*#.*?$`)
20
 	fireholRegexpComment = regexp.MustCompile(`\s*#.*?$`)
21
 
21
 
22
-	fireholIPv4DefaultCIDR = net.CIDRMask(32, 32)   // nolint: gomnd
23
-	fireholIPv6DefaultCIDR = net.CIDRMask(128, 128) // nolint: gomnd
22
+	fireholIPv4DefaultCIDR = net.CIDRMask(32, 32)   //nolint: gomnd
23
+	fireholIPv6DefaultCIDR = net.CIDRMask(128, 128) //nolint: gomnd
24
 )
24
 )
25
 
25
 
26
 // FireholUpdateCallback defines a signature of the callback that has to be
26
 // FireholUpdateCallback defines a signature of the callback that has to be

+ 1
- 1
ipblocklist/firehol_test.go Просмотреть файл

37
 
37
 
38
 		defer filefp.Close()
38
 		defer filefp.Close()
39
 
39
 
40
-		io.Copy(w, filefp) // nolint: errcheck
40
+		io.Copy(w, filefp) //nolint: errcheck
41
 	})
41
 	})
42
 
42
 
43
 	suite.httpServer = httptest.NewServer(mux)
43
 	suite.httpServer = httptest.NewServer(mux)

+ 1
- 1
logger/zerolog_test.go Просмотреть файл

116
 	suite.NotContains("lalala", log12Output)
116
 	suite.NotContains("lalala", log12Output)
117
 }
117
 }
118
 
118
 
119
-func TestZeroLogger(t *testing.T) { // nolint: paralleltest
119
+func TestZeroLogger(t *testing.T) { //nolint: paralleltest
120
 	suite.Run(t, &ZeroLoggerTestSuite{})
120
 	suite.Run(t, &ZeroLoggerTestSuite{})
121
 }
121
 }

+ 3
- 3
mtglib/conns.go Просмотреть файл

24
 		c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), true))
24
 		c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), true))
25
 	}
25
 	}
26
 
26
 
27
-	return n, err // nolint: wrapcheck
27
+	return n, err //nolint: wrapcheck
28
 }
28
 }
29
 
29
 
30
 func (c connTraffic) Write(b []byte) (int, error) {
30
 func (c connTraffic) Write(b []byte) (int, error) {
34
 		c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), false))
34
 		c.stream.Send(c.ctx, NewEventTraffic(c.streamID, uint(n), false))
35
 	}
35
 	}
36
 
36
 
37
-	return n, err // nolint: wrapcheck
37
+	return n, err //nolint: wrapcheck
38
 }
38
 }
39
 
39
 
40
 type connRewind struct {
40
 type connRewind struct {
49
 	c.mutex.RLock()
49
 	c.mutex.RLock()
50
 	defer c.mutex.RUnlock()
50
 	defer c.mutex.RUnlock()
51
 
51
 
52
-	return c.active.Read(p) // nolint: wrapcheck
52
+	return c.active.Read(p) //nolint: wrapcheck
53
 }
53
 }
54
 
54
 
55
 func (c *connRewind) Rewind() {
55
 func (c *connRewind) Rewind() {

+ 3
- 3
mtglib/conns_internal_test.go Просмотреть файл

22
 func (c *ConnRewindBaseConn) Read(p []byte) (int, error) {
22
 func (c *ConnRewindBaseConn) Read(p []byte) (int, error) {
23
 	c.Called(p)
23
 	c.Called(p)
24
 
24
 
25
-	return c.readBuffer.Read(p) // nolint: wrapcheck
25
+	return c.readBuffer.Read(p) //nolint: wrapcheck
26
 }
26
 }
27
 
27
 
28
 type ConnTrafficTestSuite struct {
28
 type ConnTrafficTestSuite struct {
69
 	suite.Equal(10, n)
69
 	suite.Equal(10, n)
70
 }
70
 }
71
 
71
 
72
-func (suite *ConnTrafficTestSuite) TestReadErr() { // nolint: dupl
72
+func (suite *ConnTrafficTestSuite) TestReadErr() { //nolint: dupl
73
 	suite.eventStreamMock.
73
 	suite.eventStreamMock.
74
 		On("Send", mock.Anything, mock.Anything).
74
 		On("Send", mock.Anything, mock.Anything).
75
 		Once().
75
 		Once().
125
 	suite.Equal(10, n)
125
 	suite.Equal(10, n)
126
 }
126
 }
127
 
127
 
128
-func (suite *ConnTrafficTestSuite) TestWriteErr() { // nolint: dupl
128
+func (suite *ConnTrafficTestSuite) TestWriteErr() { //nolint: dupl
129
 	suite.eventStreamMock.
129
 	suite.eventStreamMock.
130
 		On("Send", mock.Anything, mock.Anything).
130
 		On("Send", mock.Anything, mock.Anything).
131
 		Once().
131
 		Once().

+ 3
- 3
mtglib/init.go Просмотреть файл

110
 // This knowledge is encapsulated into instances of such interface.
110
 // This knowledge is encapsulated into instances of such interface.
111
 //
111
 //
112
 // mtglib uses Network for:
112
 // mtglib uses Network for:
113
-//     1. Dialing to Telegram
114
-//     2. Dialing to front domain
115
-//     3. Doing HTTP requests (for example, for FireHOL ipblocklist).
113
+//  1. Dialing to Telegram
114
+//  2. Dialing to front domain
115
+//  3. Doing HTTP requests (for example, for FireHOL ipblocklist).
116
 type Network interface {
116
 type Network interface {
117
 	// Dial establishes context-free TCP connections.
117
 	// Dial establishes context-free TCP connections.
118
 	Dial(network, address string) (essentials.Conn, error)
118
 	Dial(network, address string) (essentials.Conn, error)

+ 3
- 3
mtglib/internal/faketls/client_hello.go Просмотреть файл

56
 	if len(handshake)-4 != int(handshakeLength) {
56
 	if len(handshake)-4 != int(handshakeLength) {
57
 		return hello,
57
 		return hello,
58
 			fmt.Errorf("incorrect handshake size. manifested=%d, real=%d",
58
 			fmt.Errorf("incorrect handshake size. manifested=%d, real=%d",
59
-				handshakeLength, len(handshake)-4) // nolint: gomnd
59
+				handshakeLength, len(handshake)-4) //nolint: gomnd
60
 	}
60
 	}
61
 
61
 
62
 	copy(hello.Random[:], handshake[ClientHelloRandomOffset:])
62
 	copy(hello.Random[:], handshake[ClientHelloRandomOffset:])
72
 	// mac is calculated for the whole record, not only
72
 	// mac is calculated for the whole record, not only
73
 	// for the payload part
73
 	// for the payload part
74
 	mac := hmac.New(sha256.New, secret)
74
 	mac := hmac.New(sha256.New, secret)
75
-	rec.Dump(mac) // nolint: errcheck
75
+	rec.Dump(mac) //nolint: errcheck
76
 
76
 
77
 	computedRandom := mac.Sum(nil)
77
 	computedRandom := mac.Sum(nil)
78
 
78
 
100
 }
100
 }
101
 
101
 
102
 func parseCipherSuite(hello *ClientHello, handshake []byte) {
102
 func parseCipherSuite(hello *ClientHello, handshake []byte) {
103
-	cipherSuiteOffset := ClientHelloSessionIDOffset + len(hello.SessionID) + 3 // nolint: gomnd
103
+	cipherSuiteOffset := ClientHelloSessionIDOffset + len(hello.SessionID) + 3 //nolint: gomnd
104
 	hello.CipherSuite = binary.BigEndian.Uint16(handshake[cipherSuiteOffset : cipherSuiteOffset+2])
104
 	hello.CipherSuite = binary.BigEndian.Uint16(handshake[cipherSuiteOffset : cipherSuiteOffset+2])
105
 }
105
 }
106
 
106
 

+ 6
- 6
mtglib/internal/faketls/conn.go Просмотреть файл

25
 
25
 
26
 	for {
26
 	for {
27
 		if err := rec.Read(c.Conn); err != nil {
27
 		if err := rec.Read(c.Conn); err != nil {
28
-			return 0, err // nolint: wrapcheck
28
+			return 0, err //nolint: wrapcheck
29
 		}
29
 		}
30
 
30
 
31
-		switch rec.Type { // nolint: exhaustive
31
+		switch rec.Type { //nolint: exhaustive
32
 		case record.TypeApplicationData:
32
 		case record.TypeApplicationData:
33
-			rec.Payload.WriteTo(&c.readBuffer) // nolint: errcheck
33
+			rec.Payload.WriteTo(&c.readBuffer) //nolint: errcheck
34
 
34
 
35
-			return c.readBuffer.Read(p) // nolint: wrapcheck
35
+			return c.readBuffer.Read(p) //nolint: wrapcheck
36
 		case record.TypeChangeCipherSpec:
36
 		case record.TypeChangeCipherSpec:
37
 		default:
37
 		default:
38
 			return 0, fmt.Errorf("unsupported record type %v", rec.Type)
38
 			return 0, fmt.Errorf("unsupported record type %v", rec.Type)
60
 
60
 
61
 		rec.Payload.Reset()
61
 		rec.Payload.Reset()
62
 		rec.Payload.Write(p[:chunkSize])
62
 		rec.Payload.Write(p[:chunkSize])
63
-		rec.Dump(sendBuffer) // nolint: errcheck
63
+		rec.Dump(sendBuffer) //nolint: errcheck
64
 
64
 
65
 		p = p[chunkSize:]
65
 		p = p[chunkSize:]
66
 	}
66
 	}
67
 
67
 
68
 	if _, err := c.Conn.Write(sendBuffer.Bytes()); err != nil {
68
 	if _, err := c.Conn.Write(sendBuffer.Bytes()); err != nil {
69
-		return 0, err // nolint: wrapcheck
69
+		return 0, err //nolint: wrapcheck
70
 	}
70
 	}
71
 
71
 
72
 	return lenP, nil
72
 	return lenP, nil

+ 7
- 7
mtglib/internal/faketls/conn_test.go Просмотреть файл

24
 func (m *ConnMock) Read(p []byte) (int, error) {
24
 func (m *ConnMock) Read(p []byte) (int, error) {
25
 	m.Called(p)
25
 	m.Called(p)
26
 
26
 
27
-	return m.readBuffer.Read(p) // nolint: wrapcheck
27
+	return m.readBuffer.Read(p) //nolint: wrapcheck
28
 }
28
 }
29
 
29
 
30
 func (m *ConnMock) Write(p []byte) (int, error) {
30
 func (m *ConnMock) Write(p []byte) (int, error) {
31
 	m.Called(p)
31
 	m.Called(p)
32
 
32
 
33
-	return m.writeBuffer.Write(p) // nolint: wrapcheck
33
+	return m.writeBuffer.Write(p) //nolint: wrapcheck
34
 }
34
 }
35
 
35
 
36
 type ConnTestSuite struct {
36
 type ConnTestSuite struct {
61
 	rec.Version = record.Version12
61
 	rec.Version = record.Version12
62
 
62
 
63
 	rec.Payload.WriteByte(0x01)
63
 	rec.Payload.WriteByte(0x01)
64
-	rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
64
+	rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
65
 	rec.Reset()
65
 	rec.Reset()
66
 
66
 
67
 	rec.Type = record.TypeApplicationData
67
 	rec.Type = record.TypeApplicationData
68
 	rec.Version = record.Version12
68
 	rec.Version = record.Version12
69
 
69
 
70
 	rec.Payload.Write([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
70
 	rec.Payload.Write([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
71
-	rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
71
+	rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
72
 
72
 
73
 	resultBuffer := &bytes.Buffer{}
73
 	resultBuffer := &bytes.Buffer{}
74
 	buf := make([]byte, 2)
74
 	buf := make([]byte, 2)
95
 	rec.Version = record.Version12
95
 	rec.Version = record.Version12
96
 
96
 
97
 	rec.Payload.WriteByte(0x01)
97
 	rec.Payload.WriteByte(0x01)
98
-	rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
98
+	rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
99
 	rec.Reset()
99
 	rec.Reset()
100
 
100
 
101
 	rec.Type = record.TypeHandshake
101
 	rec.Type = record.TypeHandshake
102
 	rec.Version = record.Version12
102
 	rec.Version = record.Version12
103
 
103
 
104
 	rec.Payload.Write([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
104
 	rec.Payload.Write([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
105
-	rec.Dump(&suite.connMock.readBuffer) // nolint: errcheck
105
+	rec.Dump(&suite.connMock.readBuffer) //nolint: errcheck
106
 
106
 
107
 	buf := make([]byte, 2)
107
 	buf := make([]byte, 2)
108
 
108
 
141
 
141
 
142
 		suite.Equal(record.TypeApplicationData, rec.Type)
142
 		suite.Equal(record.TypeApplicationData, rec.Type)
143
 		suite.Equal(record.Version12, rec.Version)
143
 		suite.Equal(record.Version12, rec.Version)
144
-		rec.Payload.WriteTo(buf) // nolint: errcheck
144
+		rec.Payload.WriteTo(buf) //nolint: errcheck
145
 	}
145
 	}
146
 
146
 
147
 	suite.Equal(dataToRec, buf.Bytes())
147
 	suite.Equal(dataToRec, buf.Bytes())

+ 1
- 1
mtglib/internal/faketls/pools.go Просмотреть файл

12
 }
12
 }
13
 
13
 
14
 func acquireBytesBuffer() *bytes.Buffer {
14
 func acquireBytesBuffer() *bytes.Buffer {
15
-	return bytesBufferPool.Get().(*bytes.Buffer) // nolint: forcetypeassert
15
+	return bytesBufferPool.Get().(*bytes.Buffer) //nolint: forcetypeassert
16
 }
16
 }
17
 
17
 
18
 func releaseBytesBuffer(b *bytes.Buffer) {
18
 func releaseBytesBuffer(b *bytes.Buffer) {

+ 1
- 1
mtglib/internal/faketls/record/pools.go Просмотреть файл

11
 }
11
 }
12
 
12
 
13
 func AcquireRecord() *Record {
13
 func AcquireRecord() *Record {
14
-	return recordPool.Get().(*Record) // nolint: forcetypeassert
14
+	return recordPool.Get().(*Record) //nolint: forcetypeassert
15
 }
15
 }
16
 
16
 
17
 func ReleaseRecord(r *Record) {
17
 func ReleaseRecord(r *Record) {

+ 7
- 7
mtglib/internal/faketls/welcome.go Просмотреть файл

23
 	rec.Version = record.Version12
23
 	rec.Version = record.Version12
24
 
24
 
25
 	generateServerHello(&rec.Payload, clientHello)
25
 	generateServerHello(&rec.Payload, clientHello)
26
-	rec.Dump(buf) // nolint: errcheck
26
+	rec.Dump(buf) //nolint: errcheck
27
 	rec.Reset()
27
 	rec.Reset()
28
 
28
 
29
 	rec.Type = record.TypeChangeCipherSpec
29
 	rec.Type = record.TypeChangeCipherSpec
30
 	rec.Version = record.Version12
30
 	rec.Version = record.Version12
31
 	rec.Payload.WriteByte(ChangeCipherValue)
31
 	rec.Payload.WriteByte(ChangeCipherValue)
32
 
32
 
33
-	rec.Dump(buf) // nolint: errcheck
33
+	rec.Dump(buf) //nolint: errcheck
34
 	rec.Reset()
34
 	rec.Reset()
35
 
35
 
36
 	rec.Type = record.TypeApplicationData
36
 	rec.Type = record.TypeApplicationData
37
 	rec.Version = record.Version12
37
 	rec.Version = record.Version12
38
 
38
 
39
-	if _, err := io.CopyN(&rec.Payload, rand.Reader, int64(1024+mrand.Intn(3092))); err != nil { // nolint: gomnd
39
+	if _, err := io.CopyN(&rec.Payload, rand.Reader, int64(1024+mrand.Intn(3092))); err != nil { //nolint: gomnd
40
 		panic(err)
40
 		panic(err)
41
 	}
41
 	}
42
 
42
 
43
-	rec.Dump(buf) // nolint: errcheck
43
+	rec.Dump(buf) //nolint: errcheck
44
 
44
 
45
 	packet := buf.Bytes()
45
 	packet := buf.Bytes()
46
 	mac := hmac.New(sha256.New, secret)
46
 	mac := hmac.New(sha256.New, secret)
51
 	copy(packet[WelcomePacketRandomOffset:], mac.Sum(nil))
51
 	copy(packet[WelcomePacketRandomOffset:], mac.Sum(nil))
52
 
52
 
53
 	if _, err := writer.Write(packet); err != nil {
53
 	if _, err := writer.Write(packet); err != nil {
54
-		return err // nolint: wrapcheck
54
+		return err //nolint: wrapcheck
55
 	}
55
 	}
56
 
56
 
57
 	return nil
57
 	return nil
87
 	binary.BigEndian.PutUint32(header[:], uint32(bodyBuf.Len()))
87
 	binary.BigEndian.PutUint32(header[:], uint32(bodyBuf.Len()))
88
 	header[0] = HandshakeTypeServer
88
 	header[0] = HandshakeTypeServer
89
 
89
 
90
-	writer.Write(header[:]) // nolint: errcheck
91
-	bodyBuf.WriteTo(writer) // nolint: errcheck
90
+	writer.Write(header[:]) //nolint: errcheck
91
+	bodyBuf.WriteTo(writer) //nolint: errcheck
92
 }
92
 }

+ 1
- 1
mtglib/internal/obfuscated2/client_handshake_test.go Просмотреть файл

22
 
22
 
23
 func (suite *ClientHandshakeTestSuite) TestCannotRead() {
23
 func (suite *ClientHandshakeTestSuite) TestCannotRead() {
24
 	buf := bytes.NewBuffer([]byte{1, 2, 3})
24
 	buf := bytes.NewBuffer([]byte{1, 2, 3})
25
-	_, _, _, err := obfuscated2.ClientHandshake([]byte{1, 2, 3}, buf) // nolint: dogsled
25
+	_, _, _, err := obfuscated2.ClientHandshake([]byte{1, 2, 3}, buf) //nolint: dogsled
26
 
26
 
27
 	suite.Error(err)
27
 	suite.Error(err)
28
 }
28
 }

+ 2
- 2
mtglib/internal/obfuscated2/conn.go Просмотреть файл

16
 func (c Conn) Read(p []byte) (int, error) {
16
 func (c Conn) Read(p []byte) (int, error) {
17
 	n, err := c.Conn.Read(p)
17
 	n, err := c.Conn.Read(p)
18
 	if err != nil {
18
 	if err != nil {
19
-		return n, err // nolint: wrapcheck
19
+		return n, err //nolint: wrapcheck
20
 	}
20
 	}
21
 
21
 
22
 	c.Decryptor.XORKeyStream(p, p[:n])
22
 	c.Decryptor.XORKeyStream(p, p[:n])
33
 	payload := buf.Bytes()
33
 	payload := buf.Bytes()
34
 	c.Encryptor.XORKeyStream(payload, payload)
34
 	c.Encryptor.XORKeyStream(payload, payload)
35
 
35
 
36
-	return c.Conn.Write(payload) // nolint: wrapcheck
36
+	return c.Conn.Write(payload) //nolint: wrapcheck
37
 }
37
 }

+ 8
- 8
mtglib/internal/obfuscated2/handshake_frame.go Просмотреть файл

23
 
23
 
24
 // A structure of obfuscated2 handshake frame is following:
24
 // A structure of obfuscated2 handshake frame is following:
25
 //
25
 //
26
-//    [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd].
26
+//	[frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd].
27
 //
27
 //
28
-//    - 8 bytes of noise
29
-//    - 32 bytes of AES Key
30
-//    - 16 bytes of AES IV
31
-//    - 4 bytes of 'connection type' - this has some setting like a connection type
32
-//    - 2 bytes of 'DC'. DC is little endian int16
33
-//    - 2 bytes of noise
28
+//	- 8 bytes of noise
29
+//	- 32 bytes of AES Key
30
+//	- 16 bytes of AES IV
31
+//	- 4 bytes of 'connection type' - this has some setting like a connection type
32
+//	- 2 bytes of 'DC'. DC is little endian int16
33
+//	- 2 bytes of noise
34
 type handshakeFrame struct {
34
 type handshakeFrame struct {
35
 	data [handshakeFrameLen]byte
35
 	data [handshakeFrameLen]byte
36
 }
36
 }
37
 
37
 
38
 func (h *handshakeFrame) dc() int {
38
 func (h *handshakeFrame) dc() int {
39
-	idx := int16(h.data[handshakeFrameOffsetDC]) | int16(h.data[handshakeFrameOffsetDC+1])<<8 // nolint: gomnd, lll // little endian for int16 is here
39
+	idx := int16(h.data[handshakeFrameOffsetDC]) | int16(h.data[handshakeFrameOffsetDC+1])<<8 //nolint: gomnd, lll // little endian for int16 is here
40
 
40
 
41
 	switch {
41
 	switch {
42
 	case idx > 0:
42
 	case idx > 0:

+ 1
- 1
mtglib/internal/obfuscated2/handshake_frame_internal_test.go Просмотреть файл

57
 		suite.T().Run(strconv.Itoa(int(incoming)), func(t *testing.T) {
57
 		suite.T().Run(strconv.Itoa(int(incoming)), func(t *testing.T) {
58
 			frame := handshakeFrame{}
58
 			frame := handshakeFrame{}
59
 
59
 
60
-			rand.Read(frame.data[:]) // nolint: errcheck
60
+			rand.Read(frame.data[:]) //nolint: errcheck
61
 
61
 
62
 			frame.data[handshakeFrameOffsetDC] = byte(incoming)
62
 			frame.data[handshakeFrameOffsetDC] = byte(incoming)
63
 			frame.data[handshakeFrameOffsetDC+1] = byte(incoming >> 8)
63
 			frame.data[handshakeFrameOffsetDC+1] = byte(incoming >> 8)

+ 2
- 2
mtglib/internal/obfuscated2/pools.go Просмотреть файл

21
 )
21
 )
22
 
22
 
23
 func acquireSha256Hasher() hash.Hash {
23
 func acquireSha256Hasher() hash.Hash {
24
-	return sha256HasherPool.Get().(hash.Hash) // nolint: forcetypeassert
24
+	return sha256HasherPool.Get().(hash.Hash) //nolint: forcetypeassert
25
 }
25
 }
26
 
26
 
27
 func releaseSha256Hasher(h hash.Hash) {
27
 func releaseSha256Hasher(h hash.Hash) {
30
 }
30
 }
31
 
31
 
32
 func acquireBytesBuffer() *bytes.Buffer {
32
 func acquireBytesBuffer() *bytes.Buffer {
33
-	return bytesBufferPool.Get().(*bytes.Buffer) // nolint: forcetypeassert
33
+	return bytesBufferPool.Get().(*bytes.Buffer) //nolint: forcetypeassert
34
 }
34
 }
35
 
35
 
36
 func releaseBytesBuffer(buf *bytes.Buffer) {
36
 func releaseBytesBuffer(buf *bytes.Buffer) {

+ 2
- 2
mtglib/internal/obfuscated2/server_handshake.go Просмотреть файл

47
 			panic(err)
47
 			panic(err)
48
 		}
48
 		}
49
 
49
 
50
-		if frame.data[0] == 0xef { // nolint: gomnd // taken from tg sources
50
+		if frame.data[0] == 0xef { //nolint: gomnd // taken from tg sources
51
 			continue
51
 			continue
52
 		}
52
 		}
53
 
53
 
54
 		switch binary.LittleEndian.Uint32(frame.data[:4]) {
54
 		switch binary.LittleEndian.Uint32(frame.data[:4]) {
55
-		case 0x44414548, 0x54534f50, 0x20544547, 0x4954504f, 0xeeeeeeee: // nolint: gomnd // taken from tg sources
55
+		case 0x44414548, 0x54534f50, 0x20544547, 0x4954504f, 0xeeeeeeee: //nolint: gomnd // taken from tg sources
56
 			continue
56
 			continue
57
 		}
57
 		}
58
 
58
 

+ 2
- 2
mtglib/internal/obfuscated2/server_handshake_fuzz_test.go Просмотреть файл

19
 			Once().
19
 			Once().
20
 			Run(func(args mock.Arguments) {
20
 			Run(func(args mock.Arguments) {
21
 				message := make([]byte, len(data))
21
 				message := make([]byte, len(data))
22
-				handshakeData.decryptor.XORKeyStream(message, args.Get(0).([]byte)) // nolint: forcetypeassert
22
+				handshakeData.decryptor.XORKeyStream(message, args.Get(0).([]byte)) //nolint: forcetypeassert
23
 				assert.Equal(t, message, data)
23
 				assert.Equal(t, message, data)
24
 			})
24
 			})
25
 
25
 
45
 			Run(func(args mock.Arguments) {
45
 			Run(func(args mock.Arguments) {
46
 				message := make([]byte, len(data))
46
 				message := make([]byte, len(data))
47
 				handshakeData.encryptor.XORKeyStream(message, data)
47
 				handshakeData.encryptor.XORKeyStream(message, data)
48
-				copy(args.Get(0).([]byte), message) // nolint: forcetypeassert
48
+				copy(args.Get(0).([]byte), message) //nolint: forcetypeassert
49
 			})
49
 			})
50
 
50
 
51
 		n, err := handshakeData.proxyConn.Read(buffer)
51
 		n, err := handshakeData.proxyConn.Read(buffer)

+ 2
- 2
mtglib/internal/obfuscated2/server_handshake_test.go Просмотреть файл

30
 		Once().
30
 		Once().
31
 		Run(func(args mock.Arguments) {
31
 		Run(func(args mock.Arguments) {
32
 			message := make([]byte, len(messageToTelegram))
32
 			message := make([]byte, len(messageToTelegram))
33
-			suite.data.decryptor.XORKeyStream(message, args.Get(0).([]byte)) // nolint: forcetypeassert
33
+			suite.data.decryptor.XORKeyStream(message, args.Get(0).([]byte)) //nolint: forcetypeassert
34
 			suite.Equal(messageToTelegram, message)
34
 			suite.Equal(messageToTelegram, message)
35
 		})
35
 		})
36
 
36
 
50
 		Run(func(args mock.Arguments) {
50
 		Run(func(args mock.Arguments) {
51
 			message := make([]byte, len(messageFromTelegram))
51
 			message := make([]byte, len(messageFromTelegram))
52
 			suite.data.encryptor.XORKeyStream(message, messageFromTelegram)
52
 			suite.data.encryptor.XORKeyStream(message, messageFromTelegram)
53
-			copy(args.Get(0).([]byte), message) // nolint: forcetypeassert
53
+			copy(args.Get(0).([]byte), message) //nolint: forcetypeassert
54
 		})
54
 		})
55
 
55
 
56
 	n, err := suite.data.proxyConn.Read(buffer)
56
 	n, err := suite.data.proxyConn.Read(buffer)

+ 1
- 1
mtglib/internal/relay/pools.go Просмотреть файл

11
 }
11
 }
12
 
12
 
13
 func acquireCopyBuffer() *[]byte {
13
 func acquireCopyBuffer() *[]byte {
14
-	return copyBufferPool.Get().(*[]byte) // nolint: forcetypeassert
14
+	return copyBufferPool.Get().(*[]byte) //nolint: forcetypeassert
15
 }
15
 }
16
 
16
 
17
 func releaseCopyBuffer(buf *[]byte) {
17
 func releaseCopyBuffer(buf *[]byte) {

+ 2
- 2
mtglib/internal/relay/relay.go Просмотреть файл

35
 }
35
 }
36
 
36
 
37
 func pump(log Logger, src, dst essentials.Conn, direction string) {
37
 func pump(log Logger, src, dst essentials.Conn, direction string) {
38
-	defer src.CloseRead()  // nolint: errcheck
39
-	defer dst.CloseWrite() // nolint: errcheck
38
+	defer src.CloseRead()  //nolint: errcheck
39
+	defer dst.CloseWrite() //nolint: errcheck
40
 
40
 
41
 	copyBuffer := acquireCopyBuffer()
41
 	copyBuffer := acquireCopyBuffer()
42
 	defer releaseCopyBuffer(copyBuffer)
42
 	defer releaseCopyBuffer(copyBuffer)

+ 3
- 3
mtglib/proxy.go Просмотреть файл

106
 			}
106
 			}
107
 		}
107
 		}
108
 
108
 
109
-		ipAddr := conn.RemoteAddr().(*net.TCPAddr).IP // nolint: forcetypeassert
109
+		ipAddr := conn.RemoteAddr().(*net.TCPAddr).IP //nolint: forcetypeassert
110
 		logger := p.logger.BindStr("ip", ipAddr.String())
110
 		logger := p.logger.BindStr("ip", ipAddr.String())
111
 
111
 
112
 		if !p.allowlist.Contains(ipAddr) {
112
 		if !p.allowlist.Contains(ipAddr) {
253
 
253
 
254
 	p.eventStream.Send(ctx,
254
 	p.eventStream.Send(ctx,
255
 		NewEventConnectedToDC(ctx.streamID,
255
 		NewEventConnectedToDC(ctx.streamID,
256
-			conn.RemoteAddr().(*net.TCPAddr).IP, // nolint: forcetypeassert
256
+			conn.RemoteAddr().(*net.TCPAddr).IP, //nolint: forcetypeassert
257
 			ctx.dc),
257
 			ctx.dc),
258
 	)
258
 	)
259
 
259
 
316
 
316
 
317
 	pool, err := ants.NewPoolWithFunc(opts.getConcurrency(),
317
 	pool, err := ants.NewPoolWithFunc(opts.getConcurrency(),
318
 		func(arg interface{}) {
318
 		func(arg interface{}) {
319
-			proxy.ServeConn(arg.(essentials.Conn)) // nolint: forcetypeassert
319
+			proxy.ServeConn(arg.(essentials.Conn)) //nolint: forcetypeassert
320
 		},
320
 		},
321
 		ants.WithLogger(opts.getLogger("ants")),
321
 		ants.WithLogger(opts.getLogger("ants")),
322
 		ants.WithNonblocking(true))
322
 		ants.WithNonblocking(true))

+ 4
- 4
mtglib/proxy_test.go Просмотреть файл

86
 
86
 
87
 	suite.listener = listener
87
 	suite.listener = listener
88
 
88
 
89
-	go suite.p.Serve(suite.listener) // nolint: errcheck
89
+	go suite.p.Serve(suite.listener) //nolint: errcheck
90
 }
90
 }
91
 
91
 
92
 func (suite *ProxyTestSuite) TearDownSuite() {
92
 func (suite *ProxyTestSuite) TearDownSuite() {
179
 
179
 
180
 	addr := fmt.Sprintf("https://%s/headers", suite.ProxyAddress())
180
 	addr := fmt.Sprintf("https://%s/headers", suite.ProxyAddress())
181
 
181
 
182
-	resp, err := client.Get(addr) // nolint: noctx
182
+	resp, err := client.Get(addr) //nolint: noctx
183
 	suite.NoError(err)
183
 	suite.NoError(err)
184
 
184
 
185
 	defer resp.Body.Close()
185
 	defer resp.Body.Close()
191
 
191
 
192
 	jsonStruct := struct {
192
 	jsonStruct := struct {
193
 		Headers struct {
193
 		Headers struct {
194
-			TraceID string `json:"X-Amzn-Trace-Id"` // nolint: tagliatelle
194
+			TraceID string `json:"X-Amzn-Trace-Id"` //nolint: tagliatelle
195
 		} `json:"headers"`
195
 		} `json:"headers"`
196
 	}{}
196
 	}{}
197
 
197
 
221
 		_, err := tg.NewClient(tgClient).HelpGetConfig(ctx)
221
 		_, err := tg.NewClient(tgClient).HelpGetConfig(ctx)
222
 		suite.NoError(err)
222
 		suite.NoError(err)
223
 
223
 
224
-		return err // nolint: wrapcheck
224
+		return err //nolint: wrapcheck
225
 	}))
225
 	}))
226
 }
226
 }
227
 
227
 

+ 1
- 1
mtglib/secret.go Просмотреть файл

74
 		return fmt.Errorf("incorrect secret format: %w", err)
74
 		return fmt.Errorf("incorrect secret format: %w", err)
75
 	}
75
 	}
76
 
76
 
77
-	if len(decoded) < 2 { // nolint: gomnd // we need at least 1 byte here
77
+	if len(decoded) < 2 { //nolint: gomnd // we need at least 1 byte here
78
 		return fmt.Errorf("secret is truncated, length=%d", len(decoded))
78
 		return fmt.Errorf("secret is truncated, length=%d", len(decoded))
79
 	}
79
 	}
80
 
80
 

+ 2
- 2
mtglib/stream_context.go Просмотреть файл

29
 }
29
 }
30
 
30
 
31
 func (s *streamContext) Err() error {
31
 func (s *streamContext) Err() error {
32
-	return s.ctx.Err() // nolint: wrapcheck
32
+	return s.ctx.Err() //nolint: wrapcheck
33
 }
33
 }
34
 
34
 
35
 func (s *streamContext) Value(key interface{}) interface{} {
35
 func (s *streamContext) Value(key interface{}) interface{} {
49
 }
49
 }
50
 
50
 
51
 func (s *streamContext) ClientIP() net.IP {
51
 func (s *streamContext) ClientIP() net.IP {
52
-	return s.clientConn.RemoteAddr().(*net.TCPAddr).IP // nolint: forcetypeassert
52
+	return s.clientConn.RemoteAddr().(*net.TCPAddr).IP //nolint: forcetypeassert
53
 }
53
 }
54
 
54
 
55
 func newStreamContext(ctx context.Context, logger Logger, clientConn essentials.Conn) *streamContext {
55
 func newStreamContext(ctx context.Context, logger Logger, clientConn essentials.Conn) *streamContext {

+ 1
- 1
mtglib/stream_context_internal_test.go Просмотреть файл

24
 
24
 
25
 func (suite *StreamContextTestSuite) SetupTest() {
25
 func (suite *StreamContextTestSuite) SetupTest() {
26
 	ctx, cancel := context.WithCancel(context.Background())
26
 	ctx, cancel := context.WithCancel(context.Background())
27
-	ctx = context.WithValue(ctx, "key", "value") // nolint: golint, revive, staticcheck
27
+	ctx = context.WithValue(ctx, "key", "value") //nolint: golint, staticcheck
28
 
28
 
29
 	suite.ctxCancel = cancel
29
 	suite.ctxCancel = cancel
30
 	suite.connMock = &testlib.EssentialsConnMock{}
30
 	suite.connMock = &testlib.EssentialsConnMock{}

+ 5
- 5
network/circuit_breaker.go Просмотреть файл

59
 			conn.Close()
59
 			conn.Close()
60
 		}
60
 		}
61
 
61
 
62
-		return nil, ctx.Err() // nolint: wrapcheck
62
+		return nil, ctx.Err() //nolint: wrapcheck
63
 	case c.stateMutexChan <- true:
63
 	case c.stateMutexChan <- true:
64
 		defer func() {
64
 		defer func() {
65
 			<-c.stateMutexChan
65
 			<-c.stateMutexChan
78
 		c.switchState(circuitBreakerStateOpened)
78
 		c.switchState(circuitBreakerStateOpened)
79
 	}
79
 	}
80
 
80
 
81
-	return conn, err // nolint: wrapcheck
81
+	return conn, err //nolint: wrapcheck
82
 }
82
 }
83
 
83
 
84
 func (c *circuitBreakerDialer) doHalfOpened(ctx context.Context,
84
 func (c *circuitBreakerDialer) doHalfOpened(ctx context.Context,
96
 			conn.Close()
96
 			conn.Close()
97
 		}
97
 		}
98
 
98
 
99
-		return nil, ctx.Err() // nolint: wrapcheck
99
+		return nil, ctx.Err() //nolint: wrapcheck
100
 	case c.stateMutexChan <- true:
100
 	case c.stateMutexChan <- true:
101
 		defer func() {
101
 		defer func() {
102
 			<-c.stateMutexChan
102
 			<-c.stateMutexChan
104
 	}
104
 	}
105
 
105
 
106
 	if c.state != circuitBreakerStateHalfOpened {
106
 	if c.state != circuitBreakerStateHalfOpened {
107
-		return conn, err // nolint: wrapcheck
107
+		return conn, err //nolint: wrapcheck
108
 	}
108
 	}
109
 
109
 
110
 	if err == nil {
110
 	if err == nil {
113
 		c.switchState(circuitBreakerStateOpened)
113
 		c.switchState(circuitBreakerStateOpened)
114
 	}
114
 	}
115
 
115
 
116
-	return conn, err // nolint: wrapcheck
116
+	return conn, err //nolint: wrapcheck
117
 }
117
 }
118
 
118
 
119
 func (c *circuitBreakerDialer) switchState(state uint32) {
119
 func (c *circuitBreakerDialer) switchState(state uint32) {

+ 4
- 4
network/circuit_breaker_internal_test.go Просмотреть файл

110
 		Port: 80,
110
 		Port: 80,
111
 	})
111
 	})
112
 
112
 
113
-	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
114
-	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
115
-	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
116
-	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") // nolint: errcheck
113
+	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
114
+	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
115
+	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
116
+	suite.d.DialContext(suite.ctx, "tcp", "127.0.0.1") //nolint: errcheck
117
 
117
 
118
 	time.Sleep(500 * time.Millisecond)
118
 	time.Sleep(500 * time.Millisecond)
119
 
119
 

+ 2
- 2
network/default.go Просмотреть файл

19
 
19
 
20
 func (d *defaultDialer) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
20
 func (d *defaultDialer) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
21
 	switch network {
21
 	switch network {
22
-	case "tcp", "tcp4", "tcp6": // nolint: goconst
22
+	case "tcp", "tcp4", "tcp6": //nolint: goconst
23
 	default:
23
 	default:
24
 		return nil, fmt.Errorf("unsupported network %s", network)
24
 		return nil, fmt.Errorf("unsupported network %s", network)
25
 	}
25
 	}
36
 		return nil, fmt.Errorf("cannot set socket options: %w", err)
36
 		return nil, fmt.Errorf("cannot set socket options: %w", err)
37
 	}
37
 	}
38
 
38
 
39
-	return conn.(essentials.Conn), nil // nolint: forcetypeassert
39
+	return conn.(essentials.Conn), nil //nolint: forcetypeassert
40
 }
40
 }
41
 
41
 
42
 // NewDefaultDialer build a new dialer which dials bypassing proxies
42
 // NewDefaultDialer build a new dialer which dials bypassing proxies

+ 1
- 1
network/default_test.go Просмотреть файл

57
 func (suite *DefaultDialerTestSuite) TestHTTPRequest() {
57
 func (suite *DefaultDialerTestSuite) TestHTTPRequest() {
58
 	httpClient := suite.MakeHTTPClient(suite.d)
58
 	httpClient := suite.MakeHTTPClient(suite.d)
59
 
59
 
60
-	resp, err := httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
60
+	resp, err := httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
61
 	if err == nil {
61
 	if err == nil {
62
 		defer resp.Body.Close()
62
 		defer resp.Body.Close()
63
 	}
63
 	}

+ 2
- 4
network/dns_resolver.go Просмотреть файл

85
 	return ips
85
 	return ips
86
 }
86
 }
87
 
87
 
88
-func newDNSResolver(hostname string, httpClient *http.Client) (ret *dnsResolver) {
88
+func newDNSResolver(hostname string, httpClient *http.Client) *dnsResolver {
89
 	if net.ParseIP(hostname).To4() == nil {
89
 	if net.ParseIP(hostname).To4() == nil {
90
 		// the hostname is an IPv6 address
90
 		// the hostname is an IPv6 address
91
 		hostname = fmt.Sprintf("[%s]", hostname)
91
 		hostname = fmt.Sprintf("[%s]", hostname)
92
 	}
92
 	}
93
 
93
 
94
-	ret = &dnsResolver{
94
+	return &dnsResolver{
95
 		resolver: doh.Resolver{
95
 		resolver: doh.Resolver{
96
 			Host:       hostname,
96
 			Host:       hostname,
97
 			Class:      doh.IN,
97
 			Class:      doh.IN,
99
 		},
99
 		},
100
 		cache: map[string]dnsResolverCacheEntry{},
100
 		cache: map[string]dnsResolverCacheEntry{},
101
 	}
101
 	}
102
-
103
-	return
104
 }
102
 }

+ 2
- 2
network/init_internal_test.go Просмотреть файл

14
 func (d *DialerMock) Dial(network, address string) (essentials.Conn, error) {
14
 func (d *DialerMock) Dial(network, address string) (essentials.Conn, error) {
15
 	args := d.Called(network, address)
15
 	args := d.Called(network, address)
16
 
16
 
17
-	return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
17
+	return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
18
 }
18
 }
19
 
19
 
20
 func (d *DialerMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
20
 func (d *DialerMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
21
 	args := d.Called(ctx, network, address)
21
 	args := d.Called(ctx, network, address)
22
 
22
 
23
-	return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
23
+	return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
24
 }
24
 }

+ 4
- 4
network/init_test.go Просмотреть файл

22
 func (d *DialerMock) Dial(network, address string) (essentials.Conn, error) {
22
 func (d *DialerMock) Dial(network, address string) (essentials.Conn, error) {
23
 	args := d.Called(network, address)
23
 	args := d.Called(network, address)
24
 
24
 
25
-	return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
25
+	return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
26
 }
26
 }
27
 
27
 
28
 func (d *DialerMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
28
 func (d *DialerMock) DialContext(ctx context.Context, network, address string) (essentials.Conn, error) {
29
 	args := d.Called(ctx, network, address)
29
 	args := d.Called(ctx, network, address)
30
 
30
 
31
-	return args.Get(0).(essentials.Conn), args.Error(1) // nolint: wrapcheck, forcetypeassert
31
+	return args.Get(0).(essentials.Conn), args.Error(1) //nolint: wrapcheck, forcetypeassert
32
 }
32
 }
33
 
33
 
34
 type HTTPServerTestSuite struct {
34
 type HTTPServerTestSuite struct {
55
 	return &http.Client{
55
 	return &http.Client{
56
 		Transport: &http.Transport{
56
 		Transport: &http.Transport{
57
 			DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
57
 			DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
58
-				return dialer.DialContext(ctx, network, address) // nolint: wrapcheck
58
+				return dialer.DialContext(ctx, network, address) //nolint: wrapcheck
59
 			},
59
 			},
60
 		},
60
 		},
61
 	}
61
 	}
74
 		},
74
 		},
75
 	})
75
 	})
76
 
76
 
77
-	go suite.socks5Server.Serve(suite.socks5Listener) // nolint: errcheck
77
+	go suite.socks5Server.Serve(suite.socks5Listener) //nolint: errcheck
78
 }
78
 }
79
 
79
 
80
 func (suite *Socks5ServerTestSuite) TearDownSuite() {
80
 func (suite *Socks5ServerTestSuite) TearDownSuite() {

+ 1
- 1
network/load_balanced_socks5_test.go Просмотреть файл

73
 }
73
 }
74
 
74
 
75
 func (suite *LoadBalancedSocks5TestSuite) TestDialOk() {
75
 func (suite *LoadBalancedSocks5TestSuite) TestDialOk() {
76
-	resp, err := suite.httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
76
+	resp, err := suite.httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
77
 	if err == nil {
77
 	if err == nil {
78
 		defer resp.Body.Close()
78
 		defer resp.Body.Close()
79
 	}
79
 	}

+ 1
- 1
network/network.go Просмотреть файл

21
 func (n networkHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
21
 func (n networkHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
22
 	req.Header.Set("User-Agent", n.userAgent)
22
 	req.Header.Set("User-Agent", n.userAgent)
23
 
23
 
24
-	return n.next.RoundTrip(req) // nolint: wrapcheck
24
+	return n.next.RoundTrip(req) //nolint: wrapcheck
25
 }
25
 }
26
 
26
 
27
 type network struct {
27
 type network struct {

+ 4
- 4
network/network_test.go Просмотреть файл

31
 
31
 
32
 	client := ntw.MakeHTTPClient(nil)
32
 	client := ntw.MakeHTTPClient(nil)
33
 
33
 
34
-	resp, err := client.Get(suite.httpServer.URL + "/headers") // nolint: noctx
34
+	resp, err := client.Get(suite.httpServer.URL + "/headers") //nolint: noctx
35
 	suite.NoError(err)
35
 	suite.NoError(err)
36
 
36
 
37
 	defer resp.Body.Close()
37
 	defer resp.Body.Close()
42
 
42
 
43
 	jsonStruct := struct {
43
 	jsonStruct := struct {
44
 		Headers struct {
44
 		Headers struct {
45
-			UserAgent []string `json:"User-Agent"` // nolint: tagliatelle
45
+			UserAgent []string `json:"User-Agent"` //nolint: tagliatelle
46
 		} `json:"headers"`
46
 		} `json:"headers"`
47
 	}{}
47
 	}{}
48
 
48
 
56
 
56
 
57
 	client := ntw.MakeHTTPClient(nil)
57
 	client := ntw.MakeHTTPClient(nil)
58
 
58
 
59
-	resp, err := client.Get("https://httpbin.org/headers") // nolint: noctx
59
+	resp, err := client.Get("https://httpbin.org/headers") //nolint: noctx
60
 	suite.NoError(err)
60
 	suite.NoError(err)
61
 
61
 
62
 	defer resp.Body.Close()
62
 	defer resp.Body.Close()
67
 
67
 
68
 	jsonStruct := struct {
68
 	jsonStruct := struct {
69
 		Headers struct {
69
 		Headers struct {
70
-			UserAgent string `json:"User-Agent"` // nolint: tagliatelle
70
+			UserAgent string `json:"User-Agent"` //nolint: tagliatelle
71
 		} `json:"headers"`
71
 		} `json:"headers"`
72
 	}{}
72
 	}{}
73
 
73
 

+ 1
- 1
network/proxy_dialer.go Просмотреть файл

16
 	)
16
 	)
17
 
17
 
18
 	if param := params.Get("open_threshold"); param != "" {
18
 	if param := params.Get("open_threshold"); param != "" {
19
-		if intNum, err := strconv.ParseUint(param, 10, 32); err == nil { // nolint: gomnd
19
+		if intNum, err := strconv.ParseUint(param, 10, 32); err == nil { //nolint: gomnd
20
 			openThreshold = uint32(intNum)
20
 			openThreshold = uint32(intNum)
21
 		}
21
 		}
22
 	}
22
 	}

+ 5
- 5
network/proxy_dialer_internal_test.go Просмотреть файл

21
 }
21
 }
22
 
22
 
23
 func (suite *ProxyDialerTestSuite) TestSetupDefaults() {
23
 func (suite *ProxyDialerTestSuite) TestSetupDefaults() {
24
-	d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
24
+	d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
25
 	suite.EqualValues(ProxyDialerOpenThreshold, d.openThreshold)
25
 	suite.EqualValues(ProxyDialerOpenThreshold, d.openThreshold)
26
 	suite.EqualValues(ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
26
 	suite.EqualValues(ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
27
 	suite.EqualValues(ProxyDialerResetFailuresTimeout, d.resetFailuresTimeout)
27
 	suite.EqualValues(ProxyDialerResetFailuresTimeout, d.resetFailuresTimeout)
34
 	query.Set("half_open_timeout", "2s")
34
 	query.Set("half_open_timeout", "2s")
35
 	suite.u.RawQuery = query.Encode()
35
 	suite.u.RawQuery = query.Encode()
36
 
36
 
37
-	d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
37
+	d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
38
 	suite.EqualValues(30, d.openThreshold)
38
 	suite.EqualValues(30, d.openThreshold)
39
 	suite.EqualValues(2*time.Second, d.halfOpenTimeout)
39
 	suite.EqualValues(2*time.Second, d.halfOpenTimeout)
40
 	suite.EqualValues(time.Second, d.resetFailuresTimeout)
40
 	suite.EqualValues(time.Second, d.resetFailuresTimeout)
50
 			query.Set("open_threshold", param)
50
 			query.Set("open_threshold", param)
51
 			suite.u.RawQuery = query.Encode()
51
 			suite.u.RawQuery = query.Encode()
52
 
52
 
53
-			d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
53
+			d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
54
 			assert.EqualValues(t, ProxyDialerOpenThreshold, d.openThreshold)
54
 			assert.EqualValues(t, ProxyDialerOpenThreshold, d.openThreshold)
55
 		})
55
 		})
56
 	}
56
 	}
66
 			query.Set("half_open_timeout", param)
66
 			query.Set("half_open_timeout", param)
67
 			suite.u.RawQuery = query.Encode()
67
 			suite.u.RawQuery = query.Encode()
68
 
68
 
69
-			d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
69
+			d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
70
 			assert.EqualValues(t, ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
70
 			assert.EqualValues(t, ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
71
 		})
71
 		})
72
 	}
72
 	}
82
 			query.Set("reset_failures_timeout", param)
82
 			query.Set("reset_failures_timeout", param)
83
 			suite.u.RawQuery = query.Encode()
83
 			suite.u.RawQuery = query.Encode()
84
 
84
 
85
-			d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) // nolint: forcetypeassert
85
+			d := newProxyDialer(&DialerMock{}, suite.u).(*circuitBreakerDialer) //nolint: forcetypeassert
86
 			assert.EqualValues(t, ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
86
 			assert.EqualValues(t, ProxyDialerHalfOpenTimeout, d.halfOpenTimeout)
87
 		})
87
 		})
88
 	}
88
 	}

+ 2
- 2
network/sockopts.go Просмотреть файл

10
 //
10
 //
11
 // bufferSize setting is deprecated and ignored.
11
 // bufferSize setting is deprecated and ignored.
12
 func SetClientSocketOptions(conn net.Conn, bufferSize int) error {
12
 func SetClientSocketOptions(conn net.Conn, bufferSize int) error {
13
-	return setCommonSocketOptions(conn.(*net.TCPConn)) // nolint: forcetypeassert
13
+	return setCommonSocketOptions(conn.(*net.TCPConn)) //nolint: forcetypeassert
14
 }
14
 }
15
 
15
 
16
 // SetServerSocketOptions tunes a TCP socket that represents a connection to
16
 // SetServerSocketOptions tunes a TCP socket that represents a connection to
17
 // remote server like Telegram or fronting domain (but not end user).
17
 // remote server like Telegram or fronting domain (but not end user).
18
 func SetServerSocketOptions(conn net.Conn, bufferSize int) error {
18
 func SetServerSocketOptions(conn net.Conn, bufferSize int) error {
19
-	return setCommonSocketOptions(conn.(*net.TCPConn)) // nolint: forcetypeassert
19
+	return setCommonSocketOptions(conn.(*net.TCPConn)) //nolint: forcetypeassert
20
 }
20
 }
21
 
21
 
22
 func setCommonSocketOptions(conn *net.TCPConn) error {
22
 func setCommonSocketOptions(conn *net.TCPConn) error {

+ 3
- 3
network/sockopts_unix.go Просмотреть файл

13
 func setSocketReuseAddrPort(conn syscall.RawConn) error {
13
 func setSocketReuseAddrPort(conn syscall.RawConn) error {
14
 	var err error
14
 	var err error
15
 
15
 
16
-	conn.Control(func(fd uintptr) { // nolint: errcheck
17
-		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
16
+	conn.Control(func(fd uintptr) { //nolint: errcheck
17
+		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) //nolint: nosnakecase
18
 		if err != nil {
18
 		if err != nil {
19
 			err = fmt.Errorf("cannot set SO_REUSEADDR: %w", err)
19
 			err = fmt.Errorf("cannot set SO_REUSEADDR: %w", err)
20
 
20
 
21
 			return
21
 			return
22
 		}
22
 		}
23
 
23
 
24
-		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
24
+		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) //nolint: nosnakecase
25
 		if err != nil {
25
 		if err != nil {
26
 			err = fmt.Errorf("cannot set SO_REUSEPORT: %w", err)
26
 			err = fmt.Errorf("cannot set SO_REUSEPORT: %w", err)
27
 		}
27
 		}

+ 1
- 1
network/socks5.go Просмотреть файл

139
 // NewSocks5Dialer build a new dialer from a given one (so, in theory you can
139
 // NewSocks5Dialer build a new dialer from a given one (so, in theory you can
140
 // chain here). Proxy parameters are passed with URI in a form of:
140
 // chain here). Proxy parameters are passed with URI in a form of:
141
 //
141
 //
142
-//     socks5://[user:[password]]@host:port
142
+//	socks5://[user:[password]]@host:port
143
 func NewSocks5Dialer(baseDialer Dialer, proxyURL *url.URL) (Dialer, error) {
143
 func NewSocks5Dialer(baseDialer Dialer, proxyURL *url.URL) (Dialer, error) {
144
 	if _, _, err := net.SplitHostPort(proxyURL.Host); err != nil {
144
 	if _, _, err := net.SplitHostPort(proxyURL.Host); err != nil {
145
 		return nil, fmt.Errorf("incorrect url %s", proxyURL.Redacted())
145
 		return nil, fmt.Errorf("incorrect url %s", proxyURL.Redacted())

+ 2
- 2
network/socks5_test.go Просмотреть файл

33
 	dialer, _ := network.NewSocks5Dialer(suite.d, proxyURL)
33
 	dialer, _ := network.NewSocks5Dialer(suite.d, proxyURL)
34
 	httpClient := suite.MakeHTTPClient(dialer)
34
 	httpClient := suite.MakeHTTPClient(dialer)
35
 
35
 
36
-	resp, err := httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
36
+	resp, err := httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
37
 	if err == nil {
37
 	if err == nil {
38
 		defer resp.Body.Close()
38
 		defer resp.Body.Close()
39
 	}
39
 	}
46
 	dialer, _ := network.NewSocks5Dialer(suite.d, proxyURL)
46
 	dialer, _ := network.NewSocks5Dialer(suite.d, proxyURL)
47
 	httpClient := suite.MakeHTTPClient(dialer)
47
 	httpClient := suite.MakeHTTPClient(dialer)
48
 
48
 
49
-	resp, err := httpClient.Get(suite.MakeURL("/get")) // nolint: noctx
49
+	resp, err := httpClient.Get(suite.MakeURL("/get")) //nolint: noctx
50
 	if err == nil {
50
 	if err == nil {
51
 		defer resp.Body.Close()
51
 		defer resp.Body.Close()
52
 	}
52
 	}

+ 1
- 1
stats/pools.go Просмотреть файл

11
 }
11
 }
12
 
12
 
13
 func acquireStreamInfo() *streamInfo {
13
 func acquireStreamInfo() *streamInfo {
14
-	return streamInfoPool.Get().(*streamInfo) // nolint: forcetypeassert
14
+	return streamInfoPool.Get().(*streamInfo) //nolint: forcetypeassert
15
 }
15
 }
16
 
16
 
17
 func releaseStreamInfo(info *streamInfo) {
17
 func releaseStreamInfo(info *streamInfo) {

+ 3
- 3
stats/prometheus.go Просмотреть файл

171
 
171
 
172
 // Serve starts an HTTP server on a given listener.
172
 // Serve starts an HTTP server on a given listener.
173
 func (p *PrometheusFactory) Serve(listener net.Listener) error {
173
 func (p *PrometheusFactory) Serve(listener net.Listener) error {
174
-	return p.httpServer.Serve(listener) // nolint: wrapcheck
174
+	return p.httpServer.Serve(listener) //nolint: wrapcheck
175
 }
175
 }
176
 
176
 
177
 // Close stops a factory. Please pay attention that underlying listener
177
 // Close stops a factory. Please pay attention that underlying listener
178
 // is not closed.
178
 // is not closed.
179
 func (p *PrometheusFactory) Close() error {
179
 func (p *PrometheusFactory) Close() error {
180
-	return p.httpServer.Shutdown(context.Background()) // nolint: wrapcheck
180
+	return p.httpServer.Shutdown(context.Background()) //nolint: wrapcheck
181
 }
181
 }
182
 
182
 
183
 // NewPrometheus builds an events.ObserverFactory which can serve HTTP
183
 // NewPrometheus builds an events.ObserverFactory which can serve HTTP
184
 // endpoint with Prometheus scrape data.
184
 // endpoint with Prometheus scrape data.
185
-func NewPrometheus(metricPrefix, httpPath string) *PrometheusFactory { // nolint: funlen
185
+func NewPrometheus(metricPrefix, httpPath string) *PrometheusFactory { //nolint: funlen
186
 	registry := prometheus.NewPedanticRegistry()
186
 	registry := prometheus.NewPedanticRegistry()
187
 	httpHandler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{
187
 	httpHandler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{
188
 		EnableOpenMetrics: true,
188
 		EnableOpenMetrics: true,

+ 4
- 4
stats/prometheus_test.go Просмотреть файл

25
 func (suite *PrometheusTestSuite) Get() (string, error) {
25
 func (suite *PrometheusTestSuite) Get() (string, error) {
26
 	addr := fmt.Sprintf("http://%s/", suite.httpListener.Addr().String())
26
 	addr := fmt.Sprintf("http://%s/", suite.httpListener.Addr().String())
27
 
27
 
28
-	resp, err := http.Get(addr) // nolint: noctx
28
+	resp, err := http.Get(addr) //nolint: noctx
29
 	if err != nil {
29
 	if err != nil {
30
-		return "", err // nolint: wrapcheck
30
+		return "", err //nolint: wrapcheck
31
 	}
31
 	}
32
 
32
 
33
 	defer resp.Body.Close()
33
 	defer resp.Body.Close()
34
 
34
 
35
 	data, err := io.ReadAll(resp.Body)
35
 	data, err := io.ReadAll(resp.Body)
36
 	if err != nil {
36
 	if err != nil {
37
-		return "", err // nolint: wrapcheck
37
+		return "", err //nolint: wrapcheck
38
 	}
38
 	}
39
 
39
 
40
 	return string(data), nil
40
 	return string(data), nil
45
 	suite.factory = stats.NewPrometheus("mtg", "/")
45
 	suite.factory = stats.NewPrometheus("mtg", "/")
46
 	suite.prometheus = suite.factory.Make()
46
 	suite.prometheus = suite.factory.Make()
47
 
47
 
48
-	go suite.factory.Serve(suite.httpListener) // nolint: errcheck
48
+	go suite.factory.Serve(suite.httpListener) //nolint: errcheck
49
 }
49
 }
50
 
50
 
51
 func (suite *PrometheusTestSuite) TearDownTest() {
51
 func (suite *PrometheusTestSuite) TearDownTest() {

+ 1
- 1
stats/statsd.go Просмотреть файл

160
 
160
 
161
 // Close stops sending requests to statsd.
161
 // Close stops sending requests to statsd.
162
 func (s StatsdFactory) Close() error {
162
 func (s StatsdFactory) Close() error {
163
-	return s.client.Close() // nolint: wrapcheck
163
+	return s.client.Close() //nolint: wrapcheck
164
 }
164
 }
165
 
165
 
166
 // Make build a new observer.
166
 // Make build a new observer.

+ 1
- 1
stats/statsd_test.go Просмотреть файл

30
 
30
 
31
 func (s *statsdFakeServer) Close() error {
31
 func (s *statsdFakeServer) Close() error {
32
 	if s.conn != nil {
32
 	if s.conn != nil {
33
-		return s.conn.Close() // nolint: wrapcheck
33
+		return s.conn.Close() //nolint: wrapcheck
34
 	}
34
 	}
35
 
35
 
36
 	return nil
36
 	return nil

Загрузка…
Отмена
Сохранить