{"id":19865639,"url":"https://github.com/openfaas/go-sdk","last_synced_at":"2026-03-03T13:04:08.568Z","repository":{"id":65447689,"uuid":"592385898","full_name":"openfaas/go-sdk","owner":"openfaas","description":"An SDK for use within OpenFaaS functions","archived":false,"fork":false,"pushed_at":"2025-01-27T15:59:21.000Z","size":119,"stargazers_count":4,"open_issues_count":2,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-06T23:07:26.228Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openfaas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-23T16:12:23.000Z","updated_at":"2025-01-27T15:59:10.000Z","dependencies_parsed_at":"2024-11-12T19:31:45.317Z","dependency_job_id":null,"html_url":"https://github.com/openfaas/go-sdk","commit_stats":{"total_commits":27,"total_committers":3,"mean_commits":9.0,"dds":0.5555555555555556,"last_synced_commit":"faf4f56574d591c2bac6019bc7e8661e6df9f058"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fgo-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fgo-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fgo-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fgo-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openfaas","download_url":"https://codeload.github.com/openfaas/go-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251992925,"owners_count":21677022,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-12T15:23:32.673Z","updated_at":"2026-03-03T13:04:08.561Z","avatar_url":"https://github.com/openfaas.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"## go-sdk\n\nA lightweight Go SDK for use within OpenFaaS functions and to control the OpenFaaS gateway.\n\nFor use within any Go code (not just OpenFaaS Functions):\n\n* Client - A client for the OpenFaaS REST API\n\nFor use within functions:\n\n* ReadSecret() - Read a named secret from within an OpenFaaS Function\n* ReadSecrets() - Read all available secrets returning a queryable map\n\nAuthentication helpers (See: [Authentication with IAM](#authentication-with-iam)):\n\n* ServiceAccountTokenSource - An implementation of the TokenSource interface to get an ID token by reading a Kubernetes projected service account token from `/var/secrets/tokens/openfaas-token` or the path set by the `token_mount_path` environment\nvariable.\n\n## Usage\n\n```go\nimport \"github.com/openfaas/go-sdk\"\n```\n\nConstruct a new OpenFaaS client and use it to access the OpenFaaS gateway API.\n\n```go\ngatewayURL, _ := url.Parse(\"http://127.0.0.1:8080\")\nauth := \u0026sdk.BasicAuth{\n    Username: username,\n    Password: password,\n}\n\nclient := sdk.NewClient(gatewayURL, auth, http.DefaultClient)\n\nnamespace, err := client.GetNamespaces(context.Background())\n```\n\n### Authentication with IAM\n\nTo authenticate with an OpenFaaS deployment that has [Identity and Access Management (IAM)](https://docs.openfaas.com/openfaas-pro/iam/overview/) enabled, the client needs to exchange an ID token for an OpenFaaS ID token.\n\nTo get a token that can be exchanged for an OpenFaaS token you need to implement the `TokenSource` interface.\n\nThis is an example of a token source that gets a service account token mounted into a pod with [ServiceAccount token volume projection](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#serviceaccount-token-volume-projection).\n\n```go\ntype ServiceAccountTokenSource struct{}\n\nfunc (ts *ServiceAccountTokenSource) Token() (string, error) {\n\ttokenMountPath := getEnv(\"token_mount_path\", \"/var/secrets/tokens\")\n\tif len(tokenMountPath) == 0 {\n\t\treturn \"\", fmt.Errorf(\"invalid token_mount_path specified for reading the service account token\")\n\t}\n\n\tidTokenPath := path.Join(tokenMountPath, \"openfaas-token\")\n\tidToken, err := os.ReadFile(idTokenPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to load service account token: %s\", err)\n\t}\n\n\treturn string(idToken), nil\n}\n```\n\nThe service account token returned by the `TokenSource` is automatically exchanged for an OpenFaaS token that is then used in the Authorization header for all requests made to the API.\n\nIf the OpenFaaS token is expired the `TokenSource` is asked for a token and the token exchange will run again.\n\n```go\ngatewayURL, _ := url.Parse(\"https://gw.openfaas.example.com\")\n\nauth := \u0026sdk.TokenAuth{\n    TokenURL \"https://gw.openfaas.example.com/oauth/token\",\n    TokenSource: \u0026ServiceAccountTokenSource{}\n}\n\nclient := sdk.NewClient(gatewayURL, auth, http.DefaultClient)\n```\n\n### Authentication with Federated Gateway\n\n```go\nfunc Test_ClientCredentials(t *testing.T) {\n\tclientID := \"\"\n\tclientSecret := \"\"\n\ttokenURL := \"https://keycloak.example.com/realms/openfaas/protocol/openid-connect/token\"\n\tscope := \"email\"\n\tgrantType := \"client_credentials\"\n\n\taudience = \"\" // Optional\n\n\tauth := NewClientCredentialsTokenSource(clientID, clientSecret, tokenURL, scope, grantType, audience)\n\n\ttoken, err := auth.Token()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif token == \"\" {\n\t\tt.Fatal(\"token is empty\")\n\t}\n\n\tu, _ := url.Parse(\"https://fed-gw.example.com\")\n\n\tclient := NewClient(u, \u0026ClientCredentialsAuth{tokenSource: auth}, http.DefaultClient)\n\n\tfns, err := client.GetFunctions(context.Background(), \"openfaas-fn\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(fns) == 0 {\n\t\tt.Fatal(\"no functions found\")\n\t}\n}\n```\n\n## Deploy Function\n```go\n\nstatus, err := client.Deploy(context.Background(), types.FunctionDeployment{\n\tService:    \"env-store-test\",\n\tImage:      \"ghcr.io/openfaas/alpine:latest\",\n\tNamespace:  \"openfaas-fn\",\n\tEnvProcess: \"env\",\n})\n\n// non 200 status value will have some error\nif err != nil {\n\tlog.Printf(\"Deploy Failed: %s\", err)\n}\n```\n\n## Delete Function\n```go\n\nerr := client.DeleteFunction(context.Background(),\"env-store-test\", \"openfaas-fn\")\nif err != nil {\n\tlog.Printf(\"Deletion Failed: %s\", err)\n}\n```\n\nPlease refer [examples](https://github.com/openfaas/go-sdk/tree/master/examples) folder for code examples of each operation\n\n## Invoke functions\n\n```go\nbody := strings.NewReader(\"OpenFaaS\")\nreq, err := http.NewRequestWithContext(context.TODO(), http.MethodPost, \"/\", body)\nif err != nil {\n\tpanic(err)\n}\n\nreq.Header.Set(\"Content-Type\", \"text/plain\")\n\nasync := false\nauthenticate := false\n\n// Make a POST request to a figlet function in the openfaas-fn namespace\nres, err := client.InvokeFunction(context.Background(), \"figlet\", \"openfaas-fn\", async, authenticate, req)\nif err != nil {\n\tlog.Printf(\"Failed to invoke function: %s\", err)\n\treturn\n}\n\nif res.Body != nil {\n\tdefer res.Body.Close()\n}\n\n// Read the response body\nbody, err := io.ReadAll(res.Body)\nif err != nil {\n\tlog.Printf(\"Error reading response body: %s\", err)\n\treturn\n}\n\n// Print the response\nfmt.Printf(\"Response status code: %s\\n\", res.Status)\nfmt.Printf(\"Response body: %s\\n\", string(body))\n```\n\n### Authenticate function invocations\n\nThe SDK supports invoking functions if you are using OpenFaaS IAM with [built-in authentication for functions](https://www.openfaas.com/blog/built-in-function-authentication/).\n\nSet the `auth` argument to `true` when calling `InvokeFunction` to authenticate the request with an OpenFaaS function access token.\n\nThe `Client` needs a `TokenSource` to get an ID token that can be exchanged for a function access token to make authenticated function invocations. By default the `TokenAuth` provider that was set when constructing a new `Client` is used.\n\nIt is also possible to provide a custom `TokenSource` for the function token exchange:\n\n```go\nts := sdk.NewClientCredentialsTokenSource(clientID, clientSecret, tokenURL, scope, grantType, audience)\n\nclient := sdk.NewClientWithOpts(gatewayURL, http.DefaultClient, sdk.WithFunctionTokenSource(ts))\n```\n\nOptionally a `TokenCache` can be configured to cache function access tokens and prevent the client from having to do a token exchange each time a function is invoked.\n\n```go\nctx, cancel := context.WithCancel(context.Background())\ndefer cancel()\n\nfnTokenCache := sdk.NewMemoryTokenCache()\n// Start garbage collection to remove expired tokens from the cache.\ngo fnTokenCache.StartGC(ctx, time.Second*10)\n\nclient := sdk.NewClientWithOpts(\n    gatewayUrl,\n    httpClient,\n    sdk.WithAuthentication(auth),\n    sdk.WithFunctionTokenCache(fnTokenCache),\n)\n```\n\n## Build functions\n\nUse the OpenFaaS [OpenFaaS Function Builder API](https://docs.openfaas.com/openfaas-pro/builder/) to build functions from code.\n\nThe Function Builder API provides a simple REST API to create your functions from source code. The API accepts a tar archive with the function build context and build configuration. The SDk provides methods to create this tar archive and invoke the build API.\n\nIf your functions are using a language template you will need to make sure the required templates are available on the file system. How this is done is up to your implementation. Templates can be pulled from a git repository, copied from an S3 bucket, downloaded with an http call or fetched with the faas-cli.\n\n```go\nimage := \"ttl.sh/openfaas/hello-world\"\nfunctionName := \"hello-world\"\nhandler := \"./hello-world\"\nlang := \"node22\"\n\n// Get the HMAC secret used for payload authentication with the builder API.\npayloadSecret, err := os.ReadFile(\"payload.txt\")\nif err != nil {\n\tlog.Fatal(err)\n}\npayloadSecret = bytes.TrimSpace(payloadSecret)\n\n// Initialize a new builder client.\nbuilderURL, _ := url.Parse(\"http://pro-builder.openfaas.svc.cluster.local\")\nb := builder.NewFunctionBuilder(builderURL, http.DefaultClient, builder.WithHmacAuth(string(payloadSecret)))\n\n// Create the function build context using the provided function handler and language template.\nbuildContext, err := builder.CreateBuildContext(functionName, handler, lang, []string{})\nif err != nil {\n\tlog.Fatalf(\"failed to create build context: %s\", err)\n}\n\n// Create a temporary file for the build tar.\ntarFile, err := os.CreateTemp(os.TempDir(), \"build-context-*.tar\")\nif err != nil {\n\tlog.Fatalf(\"failed to temporary file: %s\", err)\n}\ntarFile.Close()\n\ntarPath := tarFile.Name()\ndefer os.Remove(tarPath)\n\n// Configuration for the build.\n// Set the image name plus optional build arguments and target platforms for multi-arch images.\nbuildConfig := builder.BuildConfig{\n\tImage:     image,\n\tPlatforms: []string{\"linux/arm64\"},\n\tBuildArgs: map[string]string{},\n}\n\n// Prepare a tar archive that contains the build config and build context.\n// The function build context is a normal docker build context. Any valid folder with a Dockerfile will work.\nif err := builder.MakeTar(tarPath, buildContext, \u0026buildConfig); err != nil {\n\tlog.Fatal(err)\n}\n\n// Invoke the function builder with the tar archive containing the build config and context\n// to build and push the function image.\nresult, err := b.Build(tarPath)\nif err != nil {\n\tlog.Fatal(err)\n}\n\n// Print build logs\nfor _, logMsg := range result.Log {\n\tfmt.Printf(\"%s\\n\", logMsg)\n}\n```\n\nTake a look at the [function builder examples](https://github.com/openfaas/function-builder-examples) for a complete example.\n\n### Stream build logs\n\n```go\n// Invoke the function builder with the tar archive containing the build config and context\n// to build and push the function image.\nstream, err := b.BuildWithStream(tarPath)\nif err != nil {\n\tlog.Fatal(err)\n}\ndefer stream.Close()\n\nfor event, err := range stream.Results() {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif event.Log != nil {\n\t\tfor _, logMsg := range event.Log {\n\t\t\tfmt.Printf(\"%s\\n\", logMsg)\n\t\t}\n\t}\n\n\tif event.Status == builder.BuildSuccess || event.Status == builder.BuildFailed {\n\t\tfmt.Printf(\"Status: %s\\n\", event.Status)\n\t\tfmt.Printf(\"Image: %s\\n\", event.Image)\n\n\t\tif len(event.Error) \u003e 0 {\n\t\t\tfmt.Printf(\"Error: %s\\n\", event.Error)\n\t\t}\n\t}\n}\n```\n\nWhen you use the `BuildWithStream` method, the SDK invokes the Function Builder API and requests that the build progress be streamed in the response. If the invocation is successful, the method returns a `*builder.BuildResultStream`. This stream allows you to iterate over the build progress and has two key methods:\n\n- `Results()`: This method returns a single-use iterator.\n\n\tYou can use a range expression to loop over this iterator and receive intermediate build results. Each iteration produces a `builder.BuildResult` and an `error`.\n\n\tWhile the build is in progress, `result.Status` will always be `in_progress`, and `result.Log` will contain the container build logs.\n\n\tWhen the build completes successfully, `result.Status` will be `success`, and `result.Image` will contain the reference for the published image. If an error occurs during the build process, the status will be `failed`, and `result.Error` should contain the error that caused the build to fail.\n\n\tThe iterator produces an `error` only when something goes wrong while reading or parsing a build result from the HTTP response.\n\n- `Close()`: This method stops the stream and ensures the underlying connection is closed.\n\n\tThe stream is automatically closed when you iterate through all results or when the iteration terminates (e.g., with `break` or `return`). However, it's a good practice to call `defer stream.Close()` immediately after a successful call to `BuildWithStream` to prevent any resource leaks.\n\n## License\n\nLicense: MIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenfaas%2Fgo-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenfaas%2Fgo-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenfaas%2Fgo-sdk/lists"}