host

package
v10.7.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2018 License: BSD-3-Clause Imports: 19 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var Interrupt = new(interruptListener)

Interrupt watches the os.Signals for interruption signals and fires the callbacks when those happens. A call of its `FireNow` manually will fire and reset the registered interrupt handlers.

Functions

func ProxyHandler

func ProxyHandler(target *url.URL) *httputil.ReverseProxy

ProxyHandler returns a new ReverseProxy that rewrites URLs to the scheme, host, and base path provided in target. If the target's path is "/base" and the incoming request was for "/dir", the target request will be for /base/dir.

Relative to httputil.NewSingleHostReverseProxy with some additions.

func RegisterOnInterrupt

func RegisterOnInterrupt(cb func())

RegisterOnInterrupt registers a global function to call when CTRL+C/CMD+C pressed or a unix kill command received.

func ShutdownOnInterrupt

func ShutdownOnInterrupt(su *Supervisor, shutdownTimeout time.Duration) func()

ShutdownOnInterrupt terminates the supervisor and its underline server when CMD+C/CTRL+C pressed. This function should be registered on Interrupt.

func WriteStartupLogOnServe

func WriteStartupLogOnServe(w io.Writer) func(TaskHost)

WriteStartupLogOnServe is a task which accepts a logger(io.Writer) and logs the listening address by a generated message based on the host supervisor's server and writes it to the "w". This function should be registered on Serve.

Types

type Configurator

type Configurator func(su *Supervisor)

Configurator provides an easy way to modify the Supervisor.

Look the `Configure` func for more.

type Supervisor

type Supervisor struct {
	Server *http.Server

	// IgnoreErrors should contains the errors that should be ignored
	// on both serve functions return statements and error handlers.
	//
	// i.e: http.ErrServerClosed.Error().
	//
	// Note that this will match the string value instead of the equality of the type's variables.
	//
	// Defaults to empty.
	IgnoredErrors []string
	// contains filtered or unexported fields
}

Supervisor is the wrapper and the manager for a compatible server and it's relative actions, called Tasks.

Interfaces are separated to return relative functionality to them.

func New

func New(srv *http.Server) *Supervisor

New returns a new host supervisor based on a native net/http "srv".

It contains all native net/http's Server methods. Plus you can add tasks on specific events. It has its own flow, which means that you can prevent to return and exit and restore the flow too.

func NewProxy

func NewProxy(hostAddr string, target *url.URL) *Supervisor

NewProxy returns a new host (server supervisor) which proxies all requests to the target. It uses the httputil.NewSingleHostReverseProxy.

Usage: target, _ := url.Parse("https://mydomain.com") proxy := NewProxy("mydomain.com:80", target) proxy.ListenAndServe() // use of `proxy.Shutdown` to close the proxy server.

func NewRedirection

func NewRedirection(hostAddr string, target *url.URL, redirectStatus int) *Supervisor

NewRedirection returns a new host (server supervisor) which redirects all requests to the target. Usage: target, _ := url.Parse("https://mydomain.com") r := NewRedirection(":80", target, 307) r.ListenAndServe() // use of `r.Shutdown` to close this server.

func (*Supervisor) Configure

func (su *Supervisor) Configure(configurators ...Configurator) *Supervisor

Configure accepts one or more `Configurator`. With this function you can use simple functions that are spread across your app to modify the supervisor, these Configurators can be used on any Supervisor instance.

Look `Configurator` too.

Returns itself.

func (*Supervisor) DeferFlow

func (su *Supervisor) DeferFlow()

DeferFlow defers the flow of the exeuction, i.e: when server should return error and exit from app, a DeferFlow call inside a Task can wait for a `RestoreFlow` to exit or not exit if host's server is "fixed".

See `RestoreFlow` too.

func (*Supervisor) ListenAndServe

func (su *Supervisor) ListenAndServe() error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

func (*Supervisor) ListenAndServeAutoTLS

func (su *Supervisor) ListenAndServeAutoTLS(domain string, email string, cacheDir string) error

ListenAndServeAutoTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Server's certificates are auto generated from LETSENCRYPT using the golang/x/net/autocert package.

The whitelisted domains are separated by whitespace in "domain" argument, i.e "iris-go.com". If empty, all hosts are currently allowed. This is not recommended, as it opens a potential attack where clients connect to a server by IP address and pretend to be asking for an incorrect host name. Manager will attempt to obtain a certificate for that host, incorrectly, eventually reaching the CA's rate limit for certificate requests and making it impossible to obtain actual certificates.

For an "e-mail" use a non-public one, letsencrypt needs that for your own security.

The "cacheDir" is being, optionally, used to provide cache stores and retrieves previously-obtained certificates. If empty, certs will only be cached for the lifetime of the auto tls manager.

Note: The domain should be like "iris-go.com www.iris-go.com", the e-mail like "teamlint2006@hotmail.com" and the cacheDir like "letscache" The `ListenAndServeAutoTLS` will start a new server for you, which will redirect all http versions to their https, including subdomains as well.

func (*Supervisor) ListenAndServeTLS

func (su *Supervisor) ListenAndServeTLS(certFile string, keyFile string) error

ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

func (*Supervisor) RegisterOnError

func (su *Supervisor) RegisterOnError(cb func(error))

RegisterOnError registers a function to call when errors occurred by the underline http server.

Example
su := New(&http.Server{Addr: ":8273", Handler: http.DefaultServeMux})

su.RegisterOnError(func(err error) {
	fmt.Println(err.Error())
})

su.RegisterOnError(func(err error) {
	fmt.Println(err.Error())
})

su.RegisterOnError(func(err error) {
	fmt.Println(err.Error())
})

go su.ListenAndServe()
time.Sleep(1 * time.Second)
su.Shutdown(context.TODO())
time.Sleep(1 * time.Second)
Output:

http: Server closed
http: Server closed
http: Server closed

func (*Supervisor) RegisterOnServe

func (su *Supervisor) RegisterOnServe(cb func(TaskHost))

RegisterOnServe registers a function to call on Serve/ListenAndServe/ListenAndServeTLS/ListenAndServeAutoTLS.

Example
h := New(&http.Server{
	Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	}),
})

logger := log.New(os.Stdout, "Supervisor: ", 0)

mytask := myTestTask{
	restartEvery: 6 * time.Second,
	maxRestarts:  2,
	logger:       logger,
}

h.RegisterOnServe(mytask.OnServe)

ln, err := net.Listen("tcp4", ":9394")
if err != nil {
	panic(err.Error())
}

logger.Println("server started...")
h.Serve(ln)
Output:

Supervisor: server started...
Supervisor: closed 1 times
Supervisor: restart
Supervisor: closed 2 times
Supervisor: restart
Supervisor: exit

func (*Supervisor) RegisterOnShutdown

func (su *Supervisor) RegisterOnShutdown(cb func())

RegisterOnShutdown registers a function to call on Shutdown. This can be used to gracefully shutdown connections that have undergone NPN/ALPN protocol upgrade or that have been hijacked. This function should start protocol-specific graceful shutdown, but should not wait for shutdown to complete.

func (*Supervisor) RestoreFlow

func (su *Supervisor) RestoreFlow()

RestoreFlow restores the flow of the execution, if called without a `DeferFlow` call before then it does nothing. See tests to understand how that can be useful on specific cases.

See `DeferFlow` too.

func (*Supervisor) Serve

func (su *Supervisor) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call su.server.Handler to reply to them.

For HTTP/2 support, server.TLSConfig should be initialized to the provided listener's TLS Config before calling Serve. If server.TLSConfig is non-nil and doesn't include the string "h2" in Config.NextProtos, HTTP/2 support is not enabled.

Serve always returns a non-nil error. After Shutdown or Close, the returned error is http.ErrServerClosed.

func (*Supervisor) Shutdown

func (su *Supervisor) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, then the context's error is returned.

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired.

type TaskHost

type TaskHost struct {
	Supervisor *Supervisor
}

TaskHost contains all the necessary information about the host supervisor, its server and the exports the whole flow controller of it.

func (TaskHost) HostURL

func (h TaskHost) HostURL() string

HostURL returns the listening full url (scheme+host) based on the supervisor's server's address.

func (TaskHost) Hostname

func (h TaskHost) Hostname() string

Hostname returns the underline server's hostname.

func (TaskHost) Serve

func (h TaskHost) Serve() error

Serve can (re)run the server with the latest known configuration.

func (TaskHost) Shutdown

func (h TaskHost) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, then the context's error is returned.

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired.

This Shutdown calls the underline's Server's Shutdown, in order to be able to re-start the server from a task.

Jump to

Keyboard shortcuts

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