Skip to content

Commit

Permalink
feat: Added instructions for binding locally. (#215)
Browse files Browse the repository at this point in the history
Added the ability to specify a hostname when executing locally.

The default example in the README now includes a flag to only bind
to the loopback device on a machine so firewall alerts shouldn't
trigger by default (and users won't expose functions to the LAN).

Existing use of the Start function including previous versions and
within the FF Buildpacks for GCF should continue to function.

See FF buildpack template for more details about how it invokes:
https://github.com/GoogleCloudPlatform/buildpacks/blob/main/cmd/go/functions_framework/template_v0.go
  • Loading branch information
josephlewis42 authored Sep 26, 2023
1 parent 77b9da8 commit 8e6bded
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,16 @@ handling logic.
if envPort := os.Getenv("PORT"); envPort != "" {
port = envPort
}
if err := funcframework.Start(port); err != nil {
log.Fatalf("funcframework.Start: %v\n", err)
// By default, listen on all interfaces. If testing locally, run with
// LOCAL_ONLY=true to avoid triggering firewall warnings and
// exposing the server outside of your own machine.
hostname := ""
if localOnly := os.Getenv("LOCAL_ONLY"); localOnly == "true" {
hostname = "127.0.0.1"
}
if err := funcframework.StartHostPort(hostname, port); err != nil {
log.Fatalf("funcframework.StartHostPort: %v\n", err)
}
}
```
Expand All @@ -113,8 +121,7 @@ handling logic.
1. Start the local development server:
```sh
export FUNCTION_TARGET=HelloWorld
go run cmd/main.go
FUNCTION_TARGET=HelloWorld LOCAL_ONLY=true go run cmd/main.go
# Output: Serving function: HelloWorld
```
Expand Down
7 changes: 6 additions & 1 deletion funcframework/framework.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,16 @@ func RegisterCloudEventFunctionContext(ctx context.Context, path string, fn func

// Start serves an HTTP server with registered function(s).
func Start(port string) error {
return StartHostPort("", port)
}

// StartHostPort serves an HTTP server with registered function(s) on the given host and port.
func StartHostPort(hostname, port string) error {
server, err := initServer()
if err != nil {
return err
}
return http.ListenAndServe(":"+port, server)
return http.ListenAndServe(fmt.Sprintf("%s:%s", hostname, port), server)
}

func initServer() (*http.ServeMux, error) {
Expand Down

0 comments on commit 8e6bded

Please sign in to comment.