-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathschema_registry.go
98 lines (82 loc) · 2.41 KB
/
schema_registry.go
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
96
97
98
package proxy
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/sirupsen/logrus"
)
type SchemaRegistryProxy struct {
url string
username string
password string
port int
proxyPort int
httpServer *http.Server
}
func validateSchemaRegistryCreds(username, password string) error {
if username == "" || password == "" {
return fmt.Errorf("schema Registry proxy requires both username and password")
}
return nil
}
func NewSchemaRegistryProxy(url, username, password string, port, proxyPort int) (*SchemaRegistryProxy, error) {
if err := validateSchemaRegistryCreds(username, password); err != nil {
return nil, err
}
return &SchemaRegistryProxy{
url: url,
username: username,
password: password,
port: port,
proxyPort: proxyPort,
}, nil
}
func (s *SchemaRegistryProxy) createProxyHandler(proxy *httputil.ReverseProxy, remote *url.URL) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logrus.WithFields(logrus.Fields{
"method": r.Method,
"path": r.URL.Path,
}).Debug("Schema Registry proxy request")
r.Host = remote.Host
r.SetBasicAuth(s.username, s.password)
proxy.ServeHTTP(w, r)
})
}
func (s *SchemaRegistryProxy) Start() error {
remote, err := url.Parse(fmt.Sprintf("https://%s:%d", s.url, s.port))
if err != nil {
return fmt.Errorf("invalid Schema Registry URL: %w", err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
logrus.WithError(err).Error("Schema Registry proxy error")
w.WriteHeader(http.StatusBadGateway)
}
// Setup proxy handler with logging and auth
handler := s.createProxyHandler(proxy, remote)
s.httpServer = &http.Server{
Addr: fmt.Sprintf(":%d", s.proxyPort),
Handler: handler,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
logrus.WithFields(logrus.Fields{
"listen_port": s.proxyPort,
"target_url": remote.String(),
}).Info("Starting Schema Registry proxy")
if err := s.httpServer.ListenAndServe(); err != nil && !errors.Is(http.ErrServerClosed, err) {
return fmt.Errorf("schema Registry proxy server error: %w", err)
}
return nil
}
func (s *SchemaRegistryProxy) Stop(ctx context.Context) error {
if s.httpServer != nil {
return s.httpServer.Shutdown(ctx)
}
return nil
}