Skip to content

Commit

Permalink
Accept a http.Request as argument to InvokeFunction
Browse files Browse the repository at this point in the history
Allow the caller to construct and configure requests as required without
limitations imposed by the signature of InvokeFunction.

Signed-off-by: Han Verstraete (OpenFaaS Ltd) <[email protected]>
  • Loading branch information
welteki committed May 30, 2024
1 parent 343aee3 commit 20a2d09
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 22 deletions.
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,16 +146,19 @@ Please refer [examples](https://github.com/openfaas/go-sdk/tree/master/examples)
## Invoke functions

```go
header := http.Header{}
header.Set("Content-Type", "text/plain")

body := strings.NewReader("OpenFaaS")
req, err := http.NewRequestWithContext(context.TODO(), http.MethodPost, "/", body)
if err != nil {
panic(err)
}

req.Header.Set("Content-Type", "text/plain")

async := false
authenticate := false

// Make a POST request to a figlet function in the openfaas-fn namespace
res, err := client.InvokeFunction(context.Background(), "figlet", "openfaas-fn", http.MethodPost, header, nil, body, async, authenticate)
res, err := client.InvokeFunction(context.Background(), "figlet", "openfaas-fn", async, authenticate, req)
if err != nil {
log.Printf("Failed to invoke function: %s", err)
return
Expand Down
22 changes: 4 additions & 18 deletions functions.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
package sdk

import (
"context"
"crypto/sha256"
"fmt"
"io"
"net/http"
"net/url"
)

const DefaultNamespace = "openfaas-fn"

func (c *Client) InvokeFunction(ctx context.Context, name, namespace string, method string, header http.Header, query url.Values, body io.Reader, async bool, auth bool) (*http.Response, error) {
func (c *Client) InvokeFunction(name, namespace string, async bool, auth bool, req *http.Request) (*http.Response, error) {
fnEndpoint := "/function"
if async {
fnEndpoint = "/async-function"
Expand All @@ -21,20 +18,9 @@ func (c *Client) InvokeFunction(ctx context.Context, name, namespace string, met
namespace = DefaultNamespace
}

u, _ := url.Parse(c.GatewayURL.String())
u.Path = fmt.Sprintf("%s/%s.%s", fnEndpoint, name, namespace)
u.RawQuery = query.Encode()

req, err := http.NewRequestWithContext(ctx, method, u.String(), body)
if err != nil {
return nil, err
}

for key, values := range header {
for _, value := range values {
req.Header.Add(key, value)
}
}
req.URL.Scheme = c.GatewayURL.Scheme
req.URL.Host = c.GatewayURL.Host
req.URL.Path = fmt.Sprintf("%s/%s.%s", fnEndpoint, name, namespace)

if auth && c.FunctionTokenSource != nil {
idToken, err := c.FunctionTokenSource.Token()
Expand Down

0 comments on commit 20a2d09

Please sign in to comment.