| 1 |
/* |
| 2 |
Copyright 2023 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package proxy |
| 18 |
|
| 19 |
import ( |
| 20 |
"net/http" |
| 21 |
|
| 22 |
"k8s.io/klog/v2" |
| 23 |
) |
| 24 |
|
| 25 |
// translatingHandler wraps the delegate handler, implementing the |
| 26 |
// http.Handler interface. The delegate handles all requests unless |
| 27 |
// the request satisfies the passed "shouldTranslate" function |
| 28 |
// (currently only for WebSocket/V5 request), in which case the translator |
| 29 |
// handles the request. |
| 30 |
type translatingHandler struct { |
| 31 |
delegate http.Handler |
| 32 |
translator http.Handler |
| 33 |
shouldTranslate func(*http.Request) bool |
| 34 |
} |
| 35 |
|
| 36 |
func NewTranslatingHandler(delegate http.Handler, translator http.Handler, shouldTranslate func(*http.Request) bool) http.Handler { |
| 37 |
return &translatingHandler{ |
| 38 |
delegate: delegate, |
| 39 |
translator: translator, |
| 40 |
shouldTranslate: shouldTranslate, |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
func (t *translatingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 45 |
if t.shouldTranslate(req) { |
| 46 |
klog.V(4).Infof("request handled by translator proxy") |
| 47 |
t.translator.ServeHTTP(w, req) |
| 48 |
return |
| 49 |
} |
| 50 |
t.delegate.ServeHTTP(w, req) |
| 51 |
} |