> ## Documentation Index
> Fetch the complete documentation index at: https://ngrok.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK Quickstart

> Learn how to get started with the ngrok Go SDK to create secure tunnels from your Go applications to the internet.

export const YouTubeEmbed = ({className, title, videoId, ...props}) => {
  return <div className={`relative aspect-video mb-3 ${className}`} {...props}>
      <iframe src={`https://www.youtube.com/embed/${videoId}`} allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen className="absolute inset-0 w-full h-full" title={title} />
    </div>;
};

<Prompt description="Give this to your AI coding agent to complete the full quickstart automatically." actions={["copy", "cursor"]}>
  Complete the ngrok Go SDK quickstart:

  1. Create `service.go` — a Go HTTP server on port 8080 that responds "Hello from Go HTTP Server!"
  2. Create a new Go module: `mkdir ngrok-go-demo && cd ngrok-go-demo && go mod init ngrok-go-demo`
  3. Install dependencies: `go get golang.ngrok.com/ngrok/v2 github.com/joho/godotenv`
  4. Create a `.env` file with NGROK\_AUTHTOKEN and NGROK\_DOMAIN — ask me for these values
  5. Create `endpoint.go` using `agent.Forward()` to tunnel port 8080 to my reserved domain with a Google OAuth traffic policy
  6. Run `go run service.go` in one terminal and `go run endpoint.go` in another
  7. Confirm the tunnel URL is printed and that visiting it requires a Google login

  Ask me for my auth token and reserved domain before starting.
</Prompt>

[The ngrok Go SDK](https://pkg.go.dev/golang.ngrok.com/ngrok/v2) is an open-source, idiomatic Go package that enables you to quickly and efficiently serve Go applications on the internet without the need to configure low-level network primitives like IPs, certificates, load balancers, or ports.
You can think of it as the [ngrok Agent CLI](/getting-started/) packaged as a Go library.

This quickstart uses the ngrok Go SDK to create an Agent Endpoint that forwards traffic from the internet to a Go app running on your local device, then secure it by requiring visitors to log in with a Google account to access it.

<Info>
  If you'd prefer to skip the boilerplate setup, you can clone the complete example from the [ngrok-samples collection](https://github.com/ngrok-samples/go-quickstart).
  In that case, you'll just need to reserve a domain and add your auth token as described below to get started.
</Info>

<YouTubeEmbed videoId="YtFlIKfADO4" title="Watch the video to learn how to add an API gateway to your Go apps" />

## What you'll need

* An [ngrok account](https://dashboard.ngrok.com/signup).
* Your [ngrok auth token](https://dashboard.ngrok.com/get-started/your-authtoken).
* [Go installed](https://go.dev/doc/install) 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 port `8080`.

```go title="service.go" theme={null}
package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello from Go HTTP Server!")
}

func main() {
	http.HandleFunc("/", handler)

	fmt.Println("Starting server at http://localhost:8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Server failed:", err)
	}
}
```

Navigate to the directory where this file is located and run the following command to start the server:

```bash theme={null}
go run 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:

```bash theme={null}
mkdir ngrok-go-demo
cd ngrok-go-demo
go mod init ngrok-go-demo
go get golang.ngrok.com/ngrok/v2
```

## 3. Create a .env file

Create a `.env` file and add [your ngrok auth token](https://dashboard.ngrok.com/get-started/your-authtoken) 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:

```bash theme={null}
touch .env
```

Add your ngrok auth token and reserved domain to this file:

```txt title=".env" theme={null}
NGROK_AUTHTOKEN=your_actual_auth_token_here
NGROK_DOMAIN=your_actual_domain_here
```

Finally, you'll need to install [the `godotenv` package](https://github.com/joho/godotenv?tab=readme-ov-file#godotenv--) to access your environment variables from your code:

```bash theme={null}
go get github.com/joho/godotenv
```

<Tip>
  If you don't want to use a `.env` file, you can instead [export your auth token as an environment variable](https://support.apple.com/en-il/guide/terminal/apd382cc5fa-4f58-4449-b20a-41c53c006f8f/mac) in your terminal session, or [call `ngrok.WithAuthToken("your-token")`](https://pkg.go.dev/golang.ngrok.com/ngrok/v2#WithAuthtoken) in your code.

  You can set your reserved domain directly in your endpoint file below using `ngrok.WithURL()`.
</Tip>

## 4. Create your endpoint

Create your Agent Endpoint, which will forward public traffic to your app.

Create a new file named `endpoint.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.

<Note>
  This example uses ngrok's default Google OAuth application.
  To use your own, see [the OAuth Traffic Policy Action documentation](/traffic-policy/actions/oauth/#google-example).
</Note>

```go title="endpoint.go" theme={null}
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
	"golang.ngrok.com/ngrok/v2"
)

func main() {
	if err := godotenv.Load(".env"); err != nil {
		log.Fatal("Error loading .env file", err)
	}
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

const trafficPolicy = `
on_http_request:
  - actions:
      - type: oauth
        config:
          provider: google
`
const address = "http://localhost:8080"

func run(ctx context.Context) error {
	agent, err := ngrok.NewAgent(ngrok.WithAuthtoken(os.Getenv("NGROK_AUTHTOKEN")))
	if err != nil {
	    return err
	}

	ln, err := agent.Forward(ctx,
		ngrok.WithUpstream(address),
		ngrok.WithURL(os.Getenv("NGROK_DOMAIN")),
		ngrok.WithTrafficPolicy(trafficPolicy),
	)

	if err != nil {
		fmt.Println("Error", err)
		return err
	}

	fmt.Println("Endpoint online: forwarding from", ln.URL(), "to", address)

	// Explicitly stop forwarding; otherwise it runs indefinitely
	<-ln.Done()
	return nil
}
```

## 5. Test your endpoint

Test your endpoint by running the following terminal command:

```bash theme={null}
go run endpoint.go
```

This should print your reserved domain URL to the terminal.
When you visit the URL, you should be prompted to log in with Google.
After logging in, you'll see your app or service.

If you used the example app in this quickstart, you'll see **"Hello from Go HTTP Server!"** displayed in your browser.

## 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](/traffic-policy/), which enable you to [grant conditional access](/traffic-policy/examples/add-authentication/#conditional-access-using-oauth-variables), [send custom headers](/traffic-policy/actions/add-headers/#examples), [rewrite URLs](/traffic-policy/actions/url-rewrite/#examples), and more with your endpoints.
* Learn more about the [Agent SDKs](/agent-sdks/) to understand how the Go SDK works under the hood.
* Check out [the ngrok Go SDK repo](https://github.com/ngrok/ngrok-go?tab=readme-ov-file#ngrok-go) 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](/getting-started/cloud-endpoints-quickstart/).
