...
1
16
17 package nosnatproxy
18
19 import (
20 "fmt"
21 "io"
22 "net/http"
23 "os"
24
25 "github.com/spf13/cobra"
26 "k8s.io/component-base/logs"
27 )
28
29
30 var CmdNoSnatTestProxy = &cobra.Command{
31 Use: "no-snat-test-proxy",
32 Short: "Creates a proxy for the /checknosnat endpoint",
33 Long: `Creates the /checknosnat endpoint which proxies the request to the given target (/checknosnat?target=target_ip&ips=ip1,ip2) and returns its response, or a 500 response on error.`,
34 Args: cobra.MaximumNArgs(0),
35 Run: main,
36 }
37
38 var port string
39
40 func init() {
41 CmdNoSnatTestProxy.Flags().StringVar(&port, "port", "31235", "The port to serve /checknosnat endpoint on.")
42 }
43
44
45
46 type masqTestProxy struct {
47 Port string
48 }
49
50 func main(cmd *cobra.Command, args []string) {
51 m := &masqTestProxy{
52 Port: port,
53 }
54
55 logs.InitLogs()
56 defer logs.FlushLogs()
57
58 if err := m.Run(); err != nil {
59 fmt.Fprintf(os.Stderr, "%v\n", err)
60 os.Exit(1)
61 }
62 }
63
64 func (m *masqTestProxy) Run() error {
65
66 http.HandleFunc("/checknosnat", checknosnat)
67
68
69 return http.ListenAndServe(":"+m.Port, nil)
70 }
71
72 func checknosnatURL(pip, ips string) string {
73 return fmt.Sprintf("http://%s/checknosnat?ips=%s", pip, ips)
74 }
75
76 func checknosnat(w http.ResponseWriter, req *http.Request) {
77 url := checknosnatURL(req.URL.Query().Get("target"), req.URL.Query().Get("ips"))
78 resp, err := http.Get(url)
79 if err != nil {
80 w.WriteHeader(500)
81 fmt.Fprintf(w, "error querying %q, err: %v", url, err)
82 return
83 }
84 defer resp.Body.Close()
85
86 body, err := io.ReadAll(resp.Body)
87 if err != nil {
88 w.WriteHeader(500)
89 fmt.Fprintf(w, "error reading body of response from %q, err: %v", url, err)
90 return
91 }
92
93
94 w.WriteHeader(resp.StatusCode)
95 w.Write(body)
96 }
97
View as plain text