faas/gateway/handlers/forwarding_proxy.go
John McCabe 89878f0c8a Migrate from alexellis org to openfaas
Note, not all `alexellis/github` references should be changed, there are
a number of repos which are not part of the openfaas org, this commit
excludes those.

Signed-off-by: John McCabe <john@johnmccabe.net>
2017-10-04 09:18:06 +01:00

50 lines
1.3 KiB
Go

package handlers
import (
"log"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"time"
"github.com/openfaas/faas/gateway/metrics"
"github.com/openfaas/faas/gateway/types"
"github.com/prometheus/client_golang/prometheus"
)
// 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()
log.Printf("> Forwarding [%s] to %s", r.Method, r.URL.String())
start := time.Now()
writeAdapter := types.NewWriteAdapter(w)
proxy.ServeHTTP(writeAdapter, r)
seconds := time.Since(start).Seconds()
log.Printf("< [%s] - %d took %f seconds\n", r.URL.String(), writeAdapter.GetHeaderCode(), seconds)
forward := "/function/"
if startsWith(uri, forward) {
log.Printf("function=%s", uri[len(forward):])
service := uri[len(forward):]
metrics.GatewayFunctionsHistogram.
WithLabelValues(service).
Observe(seconds)
code := strconv.Itoa(writeAdapter.GetHeaderCode())
metrics.GatewayFunctionInvocation.With(prometheus.Labels{"function_name": service, "code": code}).Inc()
}
}
}
func startsWith(value, token string) bool {
return len(value) > len(token) && strings.Index(value, token) == 0
}