-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
queue_proxy.go
93 lines (76 loc) · 2.1 KB
/
queue_proxy.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
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package handlers
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"github.com/gorilla/mux"
ftypes "github.com/openfaas/faas-provider/types"
"github.com/openfaas/faas/gateway/metrics"
"github.com/openfaas/faas/gateway/pkg/middleware"
"github.com/openfaas/faas/gateway/scaling"
)
// MakeQueuedProxy accepts work onto a queue
func MakeQueuedProxy(metrics metrics.MetricOptions, queuer ftypes.RequestQueuer, pathTransformer middleware.URLPathTransformer, defaultNS string, functionQuery scaling.FunctionQuery) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var body []byte
if r.Body != nil {
defer r.Body.Close()
var err error
body, err = io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
callbackURL, err := getCallbackURLHeader(r.Header)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
vars := mux.Vars(r)
name := vars["name"]
req := &ftypes.QueueRequest{
Function: name,
Body: body,
Method: r.Method,
QueryString: r.URL.RawQuery,
Path: pathTransformer.Transform(r),
Header: r.Header,
Host: r.Host,
CallbackURL: callbackURL,
}
if err = queuer.Queue(req); err != nil {
log.Printf("Error queuing request: %v", err)
http.Error(w, fmt.Sprintf("Error queuing request: %s", err.Error()),
http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}
}
func getCallbackURLHeader(header http.Header) (*url.URL, error) {
value := header.Get("X-Callback-Url")
var callbackURL *url.URL
if len(value) > 0 {
urlVal, err := url.Parse(value)
if err != nil {
return callbackURL, err
}
callbackURL = urlVal
}
return callbackURL, nil
}
func getNameParts(name string) (fn, ns string) {
fn = name
ns = ""
if index := strings.LastIndex(name, "."); index > 0 {
fn = name[:index]
ns = name[index+1:]
}
return fn, ns
}