tunnel

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2022 License: MIT Imports: 9 Imported by: 4

README

Tunnel

build status report card godocs

Public URLs for exposing your local web server using ngrok's API.

Installation

The only requirement is the Go Programming Language.

$ go get github.com/kataras/tunnel@latest

Getting Started

First of all, navigate to https://ngrok.com/, create an account and download ngrok. Extract the downloaded zip file anywhere you like and optionally add it to your PATH or NGROK system environment variable. Test if installation successfully completed by running the following command:

$ ngrok version

Import the package:

package main

import "github.com/kataras/tunnel"

Start a new local http Server and expose it to the internet using just a single new line of code:

func main() {
    // [...http.HandleFunc]

    srv := &http.Server{Addr: ":8080"}
    // 1 LOC:
    go fmt.Printf("• Public Address: %s\n", tunnel.MustStart(tunnel.WithServers(srv)))
    //
    srv.ListenAndServe()
}

OR

config := tunnel.Configuration{
    // AuthToken: "<YOUR_AUTHTOKEN>",
    // Bin: "C:/ngrok.exe",
    // WebInterface: "http://127.0.0.1:4040",
    // Region: "eu",
    Tunnels: []tunnel.Tunnel{
        {Name: "my-app", Addr: ":8080"},
    },
}
publicAddrs := tunnel.MustStart(config)
fmt.Printf("• Public Address: %s\n", publicAddrs)

Example output:

• Public Address: https://ef02b1377b65.ngrok.io

The Web Interface is also available.

Please navigate through _examples directory for more.

License

This software is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	// DefaultWebInterface is the default web interface for ngrok.
	DefaultWebInterface = "http://127.0.0.1:4040"
	// DefaultAddr is the default local web server address will be set
	// if tunnel's Addr field is missing.
	DefaultAddr = "localhost:8080"
)

Variables

View Source
var DefaultNameGenerator = func(tunnelIndex int) string {
	return fmt.Sprintf("app-%d-%s", tunnelIndex+1, time.Now().Format(http.TimeFormat))
}

DefaultNameGenerator is a function which should set the application's name if Tunnel's Name field is missing.

This name can be used to stop a tunnel as well.

View Source
var ErrExec = errors.New(`"ngrok" executable not found, please install it from: https://ngrok.com/download`)

ErrExec returns when ngrok executable was not found in the PATH or NGROK environment variable.

Functions

func MustStart

func MustStart(c Configurator) []string

MustStart same as Start package-level function but it panics on error.

func Start

func Start(c Configurator) (publicAddrs []string, err error)

Start creates a localhost ngrok tunnel based on the given Configuration. that's why it may return a non empty list among with a non-nil error.

The ngrok instance may be running or not. Meaning that if the ngrok binary instance is not already running then this function will try to start it first.

func StopTunnel

func StopTunnel(c Configurator, tunnelName string) error

StopTunnel deletes a tunnel from a running ngrok instance. If the tunnelName is "*" then it stops all registered tunnels. The tunnelName can be also the server's original addr. Exits on first error.

Types

type Configuration

type Configuration struct {
	// Client defaults to the http.DefaultClient,
	// callers can use this field to change it.
	Client *http.Client
	// AuthToken field is optionally and can be used
	// to authenticate the ngrok access.
	// ngrok authtoken <YOUR_AUTHTOKEN>
	AuthToken string `ini:"auth_token" json:"authToken,omitempty" yaml:"AuthToken" toml:"AuthToken"`

	// Bin is the system binary path of the ngrok executable file.
	// If it's empty then it will try to find it through system env variables.
	Bin string `ini:"bin" json:"bin,omitempty" yaml:"Bin" toml:"Bin"`

	// WebUIAddr is the web interface address of an already-running ngrok instance.
	// The package will try to fetch the default web interface address(http://127.0.0.1:4040)
	// to determinate if a ngrok instance is running before try to start it manually.
	// However if a custom web interface address is used,
	// this field must be set e.g. http://127.0.0.1:5050.
	WebInterface string `ini:"web_interface" json:"webInterface,omitempty" yaml:"WebInterface" toml:"WebInterface"`

	// Region is optionally, can be used to set the region which defaults to "us".
	// Available values are:
	// "us" for United States
	// "eu" for Europe
	// "ap" for Asia/Pacific
	// "au" for Australia
	// "sa" for South America
	// "jp" forJapan
	// "in" for India
	Region string `ini:"region" json:"region,omitempty" yaml:"Region" toml:"Region"`
	// Tunnels the collection of the tunnels.
	// Most of the times you only need one.
	Tunnels []Tunnel `ini:"tunnels" json:"tunnels" yaml:"Tunnels" toml:"Tunnels"`
}

Configuration contains configuration for the optional tunneling through ngrok feature. Note that the ngrok should be already installed at the host machine.

func (Configuration) Apply

func (tc Configuration) Apply(c *Configuration)

Apply implements the Option on the Configuration structure.

func (Configuration) StartTunnel

func (tc Configuration) StartTunnel(t Tunnel, publicAddr *string) error

StartTunnel starts the ngrok, if not already running, creates and starts a localhost tunnel. It binds the "publicAddr" pointer to the value of the ngrok's output public address.

func (Configuration) StopTunnel

func (tc Configuration) StopTunnel(t Tunnel) error

StopTunnel removes and stops a tunnel from a running ngrok instance.

type Configurator

type Configurator interface {
	Apply(*Configuration)
}

Configurator is an interface with a single `Apply` method. Available Configurators: - Configuration{} - WithServers

See `Start` package-level function.

type ConfiguratorFunc

type ConfiguratorFunc func(*Configuration)

ConfiguratorFunc a function signature that completes the `Configurator` interface.

func WithServers

func WithServers(servers ...*http.Server) ConfiguratorFunc

WithServers its a helper which returns a new Configuration added one or more Tunnels based on `http.Server` instances.

func (ConfiguratorFunc) Apply

func (opt ConfiguratorFunc) Apply(tc *Configuration)

Apply should set the Configuration "tc".

type StartError

type StartError struct {
	Succeed []Tunnel
	Failed  []Tunnel
	Err     error
}

StartError is a custom error type which provides details about the started and failed to start tunnels so the caller can decide to retry the failed once or to stop the succeed ones.

Usage: publicAddr, err := tunnel.Start(Configuration{...})

if err != nil {
	  if startErr, ok := err.(tunnel.Error);ok {
     startErr.Failed tunnels...
     startErr.Succeed tunnels...
     startErr.Err error...
	  }
}

See `Start` package-level function.

func (StartError) Error

func (e StartError) Error() string

Error returns the underline error's message.

type Tunnel

type Tunnel struct {
	// Name is the only one required field,
	// it is used to create and close tunnels, e.g. "MyApp".
	// If this field is not empty then ngrok tunnels will be created
	// when the app is up and running.
	Name string `ini:"name" json:"name" yaml:"Name" toml:"Name"`
	// Addr should be set of form 'hostname:port'.
	Addr string `ini:"addr" json:"addr,omitempty" yaml:"Addr" toml:"Addr"`

	// Hostname is a static subdomain that can be used instead of random URLs
	// when paid account.
	Hostname string `ini:"hostname" json:"hostname,omitempty" yaml:"Hostname" toml:"Hostname"`
}

Tunnel is the Tunnels field of the Configuration structure.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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