mirror of
https://github.com/openfaas/faas.git
synced 2025-06-21 10:26:32 +00:00
Remove Golang reverseproxy and use http Client
Signed-off-by: Alex Ellis <alexellis2@gmail.com>
This commit is contained in:
@ -1,9 +1,9 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@ -14,36 +14,66 @@ import (
|
||||
)
|
||||
|
||||
// MakeForwardingProxyHandler create a handler which forwards HTTP requests
|
||||
func MakeForwardingProxyHandler(proxy *httputil.ReverseProxy, metrics *metrics.MetricOptions) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uri := r.URL.String()
|
||||
func MakeForwardingProxyHandler(proxy *types.HttpClientReverseProxy, metrics *metrics.MetricOptions) http.HandlerFunc {
|
||||
baseURL := proxy.BaseURL.String()
|
||||
if strings.HasSuffix(baseURL, "/") {
|
||||
baseURL = baseURL[0 : len(baseURL)-1]
|
||||
}
|
||||
|
||||
log.Printf("> Forwarding [%s] to %s", r.Method, r.URL.String())
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestURL := r.URL.String()
|
||||
|
||||
log.Printf("> Forwarding [%s] to %s", r.Method, requestURL)
|
||||
start := time.Now()
|
||||
|
||||
writeAdapter := types.NewWriteAdapter(w)
|
||||
proxy.ServeHTTP(writeAdapter, r)
|
||||
upstreamReq, _ := http.NewRequest(r.Method, baseURL+requestURL, nil)
|
||||
|
||||
upstreamReq.Header["X-Forwarded-For"] = []string{r.RequestURI}
|
||||
|
||||
if r.Body != nil {
|
||||
defer r.Body.Close()
|
||||
upstreamReq.Body = r.Body
|
||||
|
||||
}
|
||||
|
||||
res, resErr := proxy.Client.Do(upstreamReq)
|
||||
if resErr != nil {
|
||||
log.Printf("upstream client error: %s\n", resErr)
|
||||
return
|
||||
}
|
||||
|
||||
if res.Body != nil {
|
||||
defer res.Body.Close()
|
||||
}
|
||||
|
||||
for k, v := range res.Header {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
|
||||
io.CopyBuffer(w, res.Body, nil)
|
||||
|
||||
seconds := time.Since(start).Seconds()
|
||||
log.Printf("< [%s] - %d took %f seconds\n", r.URL.String(),
|
||||
writeAdapter.GetHeaderCode(), seconds)
|
||||
res.StatusCode, seconds)
|
||||
|
||||
forward := "/function/"
|
||||
if startsWith(uri, forward) {
|
||||
if startsWith(requestURL, forward) {
|
||||
// log.Printf("function=%s", uri[len(forward):])
|
||||
|
||||
service := uri[len(forward):]
|
||||
service := requestURL[len(forward):]
|
||||
|
||||
metrics.GatewayFunctionsHistogram.
|
||||
WithLabelValues(service).
|
||||
Observe(seconds)
|
||||
|
||||
code := strconv.Itoa(writeAdapter.GetHeaderCode())
|
||||
code := strconv.Itoa(res.StatusCode)
|
||||
|
||||
metrics.GatewayFunctionInvocation.
|
||||
With(prometheus.Labels{"function_name": service, "code": code}).
|
||||
Inc()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user