ngrok

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2023 License: MIT Imports: 22 Imported by: 49

README

Go Reference Go

ngrok-go

ngrok is a globally distributed reverse proxy commonly used for quickly getting a public URL to a service running inside a private network, such as on your local laptop. The ngrok agent is usually deployed inside a private network and is used to communicate with the ngrok cloud service.

This is the ngrok agent in library form, suitable for integrating directly into Go applications. This allows you to quickly build ngrok into your application with no separate process to manage.

See examples/http/main.go for example usage, or the tests in online_test.go.

For working with the ngrok API, check out the ngrok Go API Client Library.

Installation

The best way to install the ngrok agent SDK is through go get.

go get golang.ngrok.com/ngrok

Documentation

A full API reference is included in the ngrok go sdk documentation on pkg.go.dev. Check out the ngrok Documentation for more information about what you can do with ngrok.

Quickstart

For more examples of using ngrok-go, check out the /examples folder.

The following example uses ngrok to start an http endpoint with a random url that will route traffic to the handler. The ngrok URL provided when running this example is accessible by anyone with an internet connection.

The ngrok authtoken is pulled from the NGROK_AUTHTOKEN environment variable. You can find your authtoken by logging into the ngrok dashboard.

You can run this example with the following command:

NGROK_AUTHTOKEN=xxxx_xxxx go run examples/http/main.go
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"golang.ngrok.com/ngrok"
	"golang.ngrok.com/ngrok/config"
)

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	tun, err := ngrok.Listen(ctx,
		config.HTTPEndpoint(),
		ngrok.WithAuthtokenFromEnv(),
	)
	if err != nil {
		return err
	}

	log.Println("tunnel created:", tun.URL())

	return http.Serve(tun, http.HandlerFunc(handler))
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello from ngrok-go!")
}

Support

The best place to get support using ngrok-go is through the ngrok Slack Community. If you find bugs or would like to contribute code, please follow the instructions in the contributing guide.

License

ngrok-go is licensed under the terms of the MIT license.

See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConnectOption

type ConnectOption func(*connectConfig)

ConnectOptions are passed to Connect to customize session connection and establishment.

func WithAuthtoken

func WithAuthtoken(token string) ConnectOption

WithAuthtoken configures the sesssion to authenticate with the provided authtoken. You can find your existing authtoken or create a new one in the ngrok dashboard.

See the authtoken parameter in the ngrok docs for additional details.

func WithAuthtokenFromEnv

func WithAuthtokenFromEnv() ConnectOption

WithAuthtokenFromEnv is a shortcut for calling WithAuthtoken with the value of the NGROK_AUTHTOKEN environment variable.

func WithCA

func WithCA(pool *x509.CertPool) ConnectOption

WithCA configures the CAs used to validate the TLS certificate returned by the ngrok service while establishing the session. Use this option only if you are connecting through a man-in-the-middle or deep packet inspection proxy.

See the root_cas parameter in the ngrok docs for additional details.

func WithConnectHandler

func WithConnectHandler(handler SessionConnectHandler) ConnectOption

WithConnectHandler configures a function which is called each time the ngrok Session successfully connects to the ngrok service. Use this option to receive events when ngrok successfully reconnects a Session that was disconnected because of a network failure.

func WithDialer

func WithDialer(dialer Dialer) ConnectOption

WithDialer configures the session to use the provided Dialer when establishing a connection to the ngrok service. This option will cause WithProxyURL to be ignored.

func WithDisconnectHandler

func WithDisconnectHandler(handler SessionDisconnectHandler) ConnectOption

WithDisconnectHandler configures a function which is called each time the ngrok Session disconnects from the ngrok service. Use this option to detect when the ngrok session has gone temporarily offline.

func WithHeartbeatHandler

func WithHeartbeatHandler(handler SessionHeartbeatHandler) ConnectOption

WithHeartbeatHandler configures a function which is called each time the Session successfully heartbeats the ngrok service. The callback receives the latency of the round trip time from initiating the heartbeat to receiving an acknowledgement back from the ngrok service.

func WithHeartbeatInterval

func WithHeartbeatInterval(interval time.Duration) ConnectOption

WithHeartbeatInterval configures how often the session will send heartbeat messages to the ngrok service to check session liveness.

See the heartbeat_interval parameter in the ngrok docs for additional details.

func WithHeartbeatTolerance

func WithHeartbeatTolerance(tolerance time.Duration) ConnectOption

WithHeartbeatTolerance configures the duration to wait for a response to a heartbeat before assuming the session connection is dead and attempting to reconnect.

See the heartbeat_tolerance parameter in the ngrok docs for additional details.

func WithLogger

func WithLogger(logger log.Logger) ConnectOption

WithLogger configures a logger to recieve log messages from the Session. The log subpackage contains adapters for both logrus and zap.

func WithMetadata

func WithMetadata(meta string) ConnectOption

WithMetdata configures the opaque, machine-readable metadata string for this session. Metadata is made available to you in the ngrok dashboard and the Agents API resource. It is a useful way to allow you to uniquely identify sessions. We suggest encoding the value in a structured format like JSON.

See the metdata parameter in the ngrok docs for additional details.

func WithProxyURL

func WithProxyURL(url *url.URL) ConnectOption

WithProxyURL configures the session to connect to ngrok through an outbound HTTP or SOCKS5 proxy. This parameter is ignored if you override the dialer with WithDialer.

See the proxy url paramter in the ngrok docs for additional details.

func WithRegion

func WithRegion(region string) ConnectOption

WithRegion configures the session to connect to a specific ngrok region. If unspecified, ngrok will connect to the fastest region, which is usually what you want. The full list of ngrok regions can be found in the ngrok documentation.

See the region parameter in the ngrok docs for additional details.

func WithServer

func WithServer(addr string) ConnectOption

WithServer configures the network address to dial to connect to the ngrok service. Use this option only if you are connecting to a custom agent ingress.

See the server_addr parameter in the ngrok docs for additional details.

func WithStopHandler

func WithStopHandler(handler ServerCommandHandler) ConnectOption

WithStopHandler configures a function which is called when the ngrok service requests that this Session stops. Your application may choose to interpret this callback as a request to terminate the Session or the entire process.

Errors returned by this function will be visible to the ngrok dashboard or API as the response to the Stop operation.

Do not block inside this callback. It will cause the Dashboard or API stop operation to hang. Do not call Session.Close or os.Exit inside this callback, it will also cause the operation to hang.

Instead, either return an error or if you intend to Stop, spawn a goroutine to asynchronously call Session.Close or os.Exit.

type Dialer

type Dialer interface {
	// Connect to an address on the named network.
	// See the documentation for net.Dial.
	Dial(network, address string) (net.Conn, error)
	// Connect to an address on the named network with the provided
	// context.
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

Dialer is the interface a custom connection dialer must implement for use with the WithDialer option.

type ServerCommandHandler

type ServerCommandHandler func(ctx context.Context, sess Session) error

ServerCommandHandler is the callback type for WithStopHandler

type Session

type Session interface {
	// Listen creates a new Tunnel which will listen for new inbound
	// connections. The returned Tunnel object is a net.Listener.
	Listen(ctx context.Context, cfg config.Tunnel) (Tunnel, error)

	// Close ends the ngrok session. All Tunnel objects created by Listen
	// on this session will be closed.
	Close() error
}

Session encapsulates an established session with the ngrok service. Sessions recover from network failures by automatically reconnecting.

func Connect

func Connect(ctx context.Context, opts ...ConnectOption) (Session, error)

Connect begins a new ngrok Session by connecting to the ngrok service. Connect blocks until the session is successfully established or fails with an error. Customize session connection behavior with ConnectOption arguments.

type SessionConnectHandler

type SessionConnectHandler func(ctx context.Context, sess Session)

SessionConnectHandler is the callback type for WithConnectHandler

type SessionDisconnectHandler

type SessionDisconnectHandler func(ctx context.Context, sess Session, err error)

SessionDisconnectHandler is the callback type for WithDisconnectHandler

type SessionHeartbeatHandler

type SessionHeartbeatHandler func(ctx context.Context, sess Session, latency time.Duration)

SessionHearbeatHandler is the callback type for [WithHearbeatHandler]

type Tunnel

type Tunnel interface {
	// Every Tunnel is a net.Listener. It can be plugged into any existing
	// code that expects a net.Listener seamlessly without any changes.
	net.Listener

	// Close is a convenience method for calling Tunnel.CloseWithContext
	// with a context that has a timeout of 5 seconds. This also allows the
	// Tunnel to satisfy the io.Closer interface.
	Close() error
	// CloseWithContext closes the Tunnel. Closing a tunnel is an operation
	// that involves sending a "close" message over the parent session.
	// Since this is a network operation, it is most correct to provide a
	// context with a timeout.
	CloseWithContext(context.Context) error
	// ForwardsTo returns a human-readable string presented in the ngrok
	// dashboard and the Tunnels API. Use config.WithForwardsTo when
	// calling Session.Listen to set this value explicitly.
	ForwardsTo() string
	// ID returns a tunnel's unique ID.
	ID() string
	// Labels returns the labels set by config.WithLabel if this is a
	// labeled tunnel. Non-labeled tunnels will return an empty map.
	Labels() map[string]string
	// Metadata returns the arbitraray metadata string for this tunnel.
	Metadata() string
	// Proto returns the protocol of the tunnel's endpoint.
	// Labeled tunnels will return the empty string.
	Proto() string
	// Session returns the tunnel's parent Session object that it
	// was started on.
	Session() Session
	// URL returns the tunnel endpoint's URL.
	// Labeled tunnels will return the empty string.
	URL() string
}

Tunnel is a net.Listener created by a call to Listen or Session.Listen. A Tunnel allows your application to receive net.Conn connections from endpoints created on the ngrok service.

func Listen

func Listen(ctx context.Context, tunnelConfig config.Tunnel, connectOpts ...ConnectOption) (Tunnel, error)

Listen creates a new Tunnel after connecting a new Session. This is a shortcut for calling Connect then Session.Listen.

Access to the underlying Session that was started automatically can be accessed via Tunnel.Session.

If an error is encoutered during Session.Listen, the Session object that was created will be closed automatically.

Directories

Path Synopsis
examples module
internal
muxado
muxado implements a general purpose stream-multiplexing protocol.
muxado implements a general purpose stream-multiplexing protocol.
pb
log
log15 Module
logrus Module
slog Module
zap Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL