If you’d prefer to skip the boilerplate setup, you can clone the complete example from the ngrok-samples collection.
In that case, you’ll just need to reserve a domain and add your auth token as described below to get started.
What you’ll need
- An ngrok account.
- Your ngrok auth token.
- Go installed on your machine. You can check this by running
go version
in your terminal.
1. Start your app or service
Start up the app or service you’d like to put online. This is the app that your agent endpoint will forward online traffic to. If you don’t have an app to work with, you can create a minimal Go app using the following code to set up a basic HTTP server at port8080
.
service.go
2. Install the Go SDK
Open a new terminal, then run the following commands to create a new Go module and install the SDK:3. Create a .env file
Create a.env
file and add your ngrok auth token and reserved domain to it.
This file needs to be in the same directory where you initialized your Go module in the previous step.
Run the following command to create the .env
file:
.env
godotenv
package to access your environment variables from your code:
If you don’t want to use a
.env
file, you can instead export your auth token as an environment variable in your terminal session, or call ngrok.WithAuthToken("your-token")
in your code.You can set your reserved domain directly in your endpoint file below using ngrok.WithURL()
.4. Create your endpoint
Create your agent endpoint, which will forward public traffic to your app. Create a new file namedendpoint.go
in the same directory as your .env
file and add the following code.
This example:
- Starts an agent endpoint that forwards from your reserved domain to your service running on port
8080
. - Secures the endpoint with a Traffic Policy that requires authentication via Google OAuth.
This example uses ngrok’s default Google OAuth application.
To use your own, see the OAuth Traffic Policy Action documentation.
endpoint.go
5. Test your endpoint
Test your endpoint by running the following terminal command:What’s next?
In this guide, you learned how to use the Go SDK to an create agent endpoint that forwards traffic to your localhost. You saw one way to implement a traffic policy directly in your codebase, including an action that adds authentication to your app with no configuration required. What else can you do with these features?- Dig deeper into traffic policies, which enable you to grant conditional access, send custom headers, rewrite URLs, and more with your endpoints.
- Learn more about the Agent SDKs to understand how the Go SDK works under the hood.
- Check out the ngrok Go SDK repo for more code examples.
- If your use case calls for a centrally managed, always-on endpoint instead of one that’s only available when an agent is running, you should proceed to getting started with Cloud Endpoints.