Fix 'kubectl proxy' to allow the /metrics page to be proxied, without breaking the previous proxy behavior
This commit is contained in:
@@ -28,17 +28,18 @@ import (
|
||||
|
||||
// ProxyServer is a http.Handler which proxies Kubernetes APIs to remote API server.
|
||||
type ProxyServer struct {
|
||||
mux *http.ServeMux
|
||||
httputil.ReverseProxy
|
||||
}
|
||||
|
||||
// NewProxyServer creates and installs a new ProxyServer.
|
||||
// It automatically registers the created ProxyServer to http.DefaultServeMux.
|
||||
func NewProxyServer(filebase string, apiProxyPrefix string, staticPrefix string, cfg *client.Config) (*ProxyServer, error) {
|
||||
prefix := cfg.Prefix
|
||||
if prefix == "" {
|
||||
prefix = "/api"
|
||||
host := cfg.Host
|
||||
if !strings.HasSuffix(host, "/") {
|
||||
host = host + "/"
|
||||
}
|
||||
target, err := url.Parse(singleJoiningSlash(cfg.Host, prefix))
|
||||
target, err := url.Parse(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -46,15 +47,22 @@ func NewProxyServer(filebase string, apiProxyPrefix string, staticPrefix string,
|
||||
if proxy.Transport, err = client.TransportFor(cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
http.Handle(apiProxyPrefix, http.StripPrefix(apiProxyPrefix, proxy))
|
||||
http.Handle(staticPrefix, newFileHandler(staticPrefix, filebase))
|
||||
if strings.HasPrefix(apiProxyPrefix, "/api") {
|
||||
proxy.mux.Handle(apiProxyPrefix, proxy)
|
||||
} else {
|
||||
proxy.mux.Handle(apiProxyPrefix, http.StripPrefix(apiProxyPrefix, proxy))
|
||||
}
|
||||
proxy.mux.Handle(staticPrefix, newFileHandler(staticPrefix, filebase))
|
||||
return proxy, nil
|
||||
}
|
||||
|
||||
// Serve starts the server (http.DefaultServeMux) on given port, loops forever.
|
||||
func (s *ProxyServer) Serve(port int) error {
|
||||
addr := fmt.Sprintf(":%d", port)
|
||||
return http.ListenAndServe(addr, nil)
|
||||
server := http.Server{
|
||||
Addr: fmt.Sprintf(":%d", port),
|
||||
Handler: s.mux,
|
||||
}
|
||||
return server.ListenAndServe()
|
||||
}
|
||||
|
||||
func newProxyServer(target *url.URL) *ProxyServer {
|
||||
@@ -63,7 +71,10 @@ func newProxyServer(target *url.URL) *ProxyServer {
|
||||
req.URL.Host = target.Host
|
||||
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
|
||||
}
|
||||
return &ProxyServer{ReverseProxy: httputil.ReverseProxy{Director: director}}
|
||||
return &ProxyServer{
|
||||
ReverseProxy: httputil.ReverseProxy{Director: director},
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
}
|
||||
|
||||
func newFileHandler(prefix, base string) http.Handler {
|
||||
|
Reference in New Issue
Block a user