File: client.go

package info (click to toggle)
golang-github-ibm-sarama 1.45.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 2,964 kB
  • sloc: makefile: 35; sh: 19
file content (95 lines) | stat: -rw-r--r-- 2,136 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package toxiproxy

import (
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"time"
)

type Client struct {
	httpClient *http.Client
	endpoint   string
}

func NewClient(endpoint string) *Client {
	return &Client{
		httpClient: &http.Client{
			Transport: &http.Transport{
				Proxy: http.ProxyFromEnvironment,
				DialContext: (&net.Dialer{
					Timeout:   30 * time.Second,
					KeepAlive: 30 * time.Second,
				}).DialContext,
				ForceAttemptHTTP2:     true,
				MaxIdleConns:          -1,
				DisableKeepAlives:     true,
				IdleConnTimeout:       90 * time.Second,
				TLSHandshakeTimeout:   10 * time.Second,
				ExpectContinueTimeout: 1 * time.Second,
			},
		},
		endpoint: endpoint,
	}
}

func (c *Client) CreateProxy(
	name string,
	listenAddr string,
	targetAddr string,
) (*Proxy, error) {
	proxy := &Proxy{
		Name:       name,
		ListenAddr: listenAddr,
		TargetAddr: targetAddr,
		Enabled:    true,
		client:     c,
	}
	return proxy.Save()
}

func (c *Client) Proxy(name string) (*Proxy, error) {
	req, err := http.NewRequest("GET", c.endpoint+"/proxies/"+name, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to make proxy request: %w", err)
	}
	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("failed to http get proxy: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		body, _ := io.ReadAll(resp.Body)
		return nil, fmt.Errorf("error getting proxy %s: %s %s", name, resp.Status, body)
	}

	var p Proxy
	if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
		return nil, fmt.Errorf("error decoding json for proxy %s: %w", name, err)
	}
	p.client = c

	return &p, nil
}

func (c *Client) ResetState() error {
	req, err := http.NewRequest("POST", c.endpoint+"/reset", http.NoBody)
	if err != nil {
		return fmt.Errorf("failed to make reset request: %w", err)
	}
	resp, err := c.httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("failed to http post reset: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != 204 {
		body, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("error resetting proxies: %s %s", resp.Status, body)
	}

	return nil
}