ngrok

package module
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2024 License: MIT Imports: 28 Imported by: 49

README

ngrok-go

Go Reference Go MIT licensed

ngrok is a simplified API-first ingress-as-a-service that adds connectivity, security, and observability to your apps.

ngrok-go is an open source and idiomatic library for embedding ngrok networking directly into Go applications. If you’ve used ngrok before, you can think of ngrok-go as the ngrok agent packaged as a Go library.

ngrok-go lets developers serve Go apps on the internet in a single line of code without setting up low-level network primitives like IPs, certificates, load balancers and even ports! Applications using ngrok-go listen on ngrok’s global ingress network but they receive the same interface any Go app would expect (net.Listener) as if it listened on a local port by calling net.Listen(). This makes it effortless to integrate ngrok-go into any application that uses Go's net or net/http packages.

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.

For additional information, be sure to also check out the ngrok-go launch announcement!

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 {
	ln, err := ngrok.Listen(ctx,
		config.HTTPEndpoint(),
		ngrok.WithAuthtokenFromEnv(),
	)
	if err != nil {
		return err
	}

	log.Println("Ingress established at:", ln.URL())

	return http.Serve(ln, 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.

Changelog

Changes to ngrok-go are tracked under CHANGELOG.md.

Join the ngrok Community

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 AgentVersionDeprecated added in v1.2.0

type AgentVersionDeprecated proto.AgentVersionDeprecated

AgentVersionDeprecated is a type wrapper for proto.AgentVersionDeprecated

func (*AgentVersionDeprecated) Error added in v1.2.0

func (avd *AgentVersionDeprecated) Error() string

type Conn added in v1.1.0

type Conn interface {
	net.Conn
	// Proto returns the tunnel protocol (http, https, tls, or tcp) for this connection.
	Proto() string
	// EdgeType returns the type of the edge (https, tls, or tcp) that matched this tunnel.
	EdgeType() EdgeType
	// PassthroughTLS returns whether this connection contains an end-to-end tls
	// connection.
	PassthroughTLS() bool
}

Conn is a connection from an ngrok Tunnel.

It implements the standard net.Conn interface and has additional methods to query ngrok-specific connection metadata.

Because the net.Listener interface requires `Accept` to return a net.Conn, you will have to type-assert it to an ngrok Conn: ``` conn, _ := tun.Accept() ngrokConn := conn.(ngrok.Conn) ```

type ConnectOption

type ConnectOption func(*connectConfig)

ConnectOption is passed to Connect to customize session connection and establishment.

func WithAdditionalServers added in v1.9.0

func WithAdditionalServers(addrs []string) ConnectOption

WithAdditionalServers configures the network address to dial to connect to the ngrok service on secondary legs. Use this option only if you are connecting to a custom agent ingress, and have enabled multi leg.

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

func WithAuthtoken

func WithAuthtoken(token string) ConnectOption

WithAuthtoken configures the session 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 WithClientInfo added in v1.1.0

func WithClientInfo(clientType, version string, comments ...string) ConnectOption

WithClientInfo configures client type and version information for applications built on this library. This is a way for consumers of this library to identify themselves to the ngrok service.

This will add a new entry to the `User-Agent` field in the "most significant" (first) position.

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 the Session successfully connects or reconnects after a disconnection due to 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.

This handler will be called every time the Session encounters an error during or after connection. It may be called multiple times in a row; it may be called before any Connect handler is called and before Connect returns.

If this function is called with a nil error, the Session has stopped and will not reconnect, usually due to [Session.Close] being called.

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 receive log messages from the Session. The log subpackage contains adapters for both logrus and zap.

func WithMetadata

func WithMetadata(meta string) ConnectOption

WithMetadata 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 metadata parameter in the ngrok docs for additional details.

func WithMultiLeg added in v1.9.0

func WithMultiLeg(enable bool) ConnectOption

WithMultiLeg as true allows connecting to the ngrok service on secondary legs.

See WithAdditionalServers if connecting to a custom agent ingress.

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 parameter 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 WithRestartCommandDisabled added in v1.1.0

func WithRestartCommandDisabled(err string) ConnectOption

WithRestartCommandDisabled specifies a user-friendly error message to be reported by the ngrok dashboard or API when a user attempts to issue a Restart command for this Session.

Set this error only if you wish to provide a more detailed reason for entirely disabling the Restart command for your application. If you wish to report an error while attempting to handle a Restart command, instead return that error from the handler function set by WithRestartHandler.

func WithRestartHandler added in v1.1.0

func WithRestartHandler(handler ServerCommandHandler) ConnectOption

WithRestartHandler configures a function which is called when the ngrok service requests that this Session restarts. Your application may choose to interpret this callback as a request to reconnect the Session or restart the entire process.

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

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

Instead, either spawn a goroutine to asynchronously restart, or return an error.

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 WithStopCommandDisabled added in v1.1.0

func WithStopCommandDisabled(err string) ConnectOption

WithStopCommandDisabled specifies a user-friendly error message to be reported by the ngrok dashboard or API when a user attempts to issue a Stop command for this Session.

Set this error only if you wish to provide a more detailed reason for entirely disabling the Stop command for your application. If you wish to report an error while attempting to handle a Stop command, instead return that error from the handler function set by WithStopHandler.

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.

func WithTLSConfig added in v1.1.0

func WithTLSConfig(tlsCustomizer func(*tls.Config)) ConnectOption

WithTLSConfig allows customization of the TLS connection made from the agent to the ngrok service. Customization is applied after the WithServer and WithCA options are applied.

func WithUpdateCommandDisabled added in v1.1.0

func WithUpdateCommandDisabled(err string) ConnectOption

WithUpdateCommandDisabled specifies a user-friendly error message to be reported by the ngrok dashboard or API when a user attempts to issue a Update command for this Session.

Set this error only if you wish to provide a more detailed reason for entirely disabling the Update command for your application. If you wish to report an error while attempting to handle a Update command, instead return that error from the handler function set by WithUpdateHandler.

func WithUpdateHandler added in v1.1.0

func WithUpdateHandler(handler ServerCommandHandler) ConnectOption

WithUpdateHandler configures a function which is called when the ngrok service requests that the application running this Session updates. Your application may use this callback to trigger a check for a newer version followed by an update and restart if one exists.

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

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

Instead, spawn a goroutine to asynchronously handle the update process or return an error if there is no newer version to update to.

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 EdgeType added in v1.1.0

type EdgeType proto.EdgeType

EdgeType is the type of the edge (https, tls, or tcp) for this tunnel.

const (
	EdgeTypeUndefined EdgeType = 0
	EdgeTypeTCP       EdgeType = 1
	EdgeTypeTLS       EdgeType = 2
	EdgeTypeHTTPS     EdgeType = 3
)

All possible edge types. Currently only https, tls, and tcp are supported.

type Error added in v1.4.0

type Error interface {
	error
	// Msg returns the error string without the error code.
	Msg() string
	// ErrorCode returns the ngrok error code, if one exists.
	ErrorCode() string
}

Error is an error enriched with a specific ErrorCode. All ngrok error codes are documented at https://ngrok.com/docs/errors.

An Error can be extracted from a generic error using errors.As.

Example:

var nerr ngrok.Error
if errors.As(err, &nerr) {
  fmt.Printf("%s: %s\n", nerr.ErrorCode(), nerr.Msg())
}

type Forwarder added in v1.5.0

type Forwarder interface {
	// Information about the tunnel being forwarded
	TunnelInfo

	// 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

	// Session returns the tunnel's parent Session object that it
	// was started on.
	Session() Session

	// Wait blocks until the forwarding task exits (usually due to tunnel
	// close), or the `context.Context` that it was started with is canceled.
	Wait() error
}

Forwarder is a tunnel that has every connection forwarded to some URL.

func ListenAndForward added in v1.5.0

func ListenAndForward(ctx context.Context, backend *url.URL, tunnelConfig config.Tunnel, connectOpts ...ConnectOption) (Forwarder, error)

ListenAndForward creates a new Forwarder after connecting a new Session, and then forwards all connections to the provided URL. This is a shortcut for calling Connect then Session.ListenAndForward.

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

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

func ListenAndHandleHTTP added in v1.5.0

func ListenAndHandleHTTP(ctx context.Context, handler *http.Handler, tunnelConfig config.Tunnel, connectOpts ...ConnectOption) (Forwarder, error)

ListenAndHandleHTTP creates a new Forwarder after connecting a new Session, and then forwards all connections to a new HTTP server and handles them with the provided HTTP handler.

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

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

func ListenAndServeHTTP added in v1.5.0

func ListenAndServeHTTP(ctx context.Context, server *http.Server, tunnelConfig config.Tunnel, connectOpts ...ConnectOption) (Forwarder, error)

ListenAndServeHTTP creates a new Forwarder after connecting a new Session, and then forwards all connections to the provided HTTP server. This is a shortcut for calling Connect then Session.ListenAndForward.

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

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

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)

	// Warnings returns a list of warnings generated for the session on connect/auth
	Warnings() []error

	// ListenAndForward creates a new Tunnel which will listen for new inbound
	// connections. Connections on this tunnel are automatically forwarded to
	// the provided URL.
	ListenAndForward(ctx context.Context, backend *url.URL, cfg config.Tunnel) (Forwarder, error)

	// ListenAndServeHTTP creates a new Tunnel to serve as a backend for an HTTP server. Connections will be
	// forwarded to the provided HTTP server.
	ListenAndServeHTTP(ctx context.Context, cfg config.Tunnel, server *http.Server) (Forwarder, error)

	// ListenAndHandleHTTP creates a new Tunnel to serve as a backend for an HTTP handler. Connections will be
	// forwarded to a new HTTP server and handled by the provided HTTP handler.
	ListenAndHandleHTTP(ctx context.Context, cfg config.Tunnel, handler *http.Handler) (Forwarder, 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, retrying transient failures if they occur.

Connect blocks until the session is successfully established or fails with an error that will not be retried. 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)

SessionHeartbeatHandler 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

	// Information associated with the tunnel
	TunnelInfo

	// 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

	// Session returns the tunnel's parent Session object that it
	// was started on.
	Session() Session
}

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 encountered during Session.Listen, the Session object that was created will be closed automatically.

type TunnelInfo added in v1.5.0

type TunnelInfo interface {
	// 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 arbitrary 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
	// URL returns the tunnel endpoint's URL.
	// Labeled tunnels will return the empty string.
	URL() string
}

TunnelInfo implementations contain metadata about a Tunnel.

Directories

Path Synopsis
examples module
internal
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