host

package
v7.4.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2017 License: BSD-3-Clause Imports: 22 Imported by: 18

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

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 RegisterOnInterruptHook

func RegisterOnInterruptHook(cb func())

RegisterOnInterruptHook 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 registerd on Interrupt.

func WriteStartupLogOnServe

func WriteStartupLogOnServe(logger *zap.SugaredLogger, banner string) 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
	// 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, sirisConfig *configuration.Configuration) *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 redirects 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 (*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() 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.

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) ListenPacket

func (su *Supervisor) ListenPacket() (*net.UDPConn, error)

ListenPacket creates udp connection for QUIC if it is enabled,

func (*Supervisor) RegisterOnErrorHook

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

RegisterOnErrorHook registers a function to call when errors occured by the underline http server.

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

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

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

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

go su.ListenAndServe()
time.Sleep(1 * time.Second)
ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
defer cancel()
su.Shutdown(ctx)
time.Sleep(1 * time.Second)
Output:

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

func (*Supervisor) RegisterOnServeHook

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

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

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

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

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

h.RegisterOnServeHook(WriteStartupLogOnServe(func() *zap.SugaredLogger { log, _ := zap.NewDevelopment(); return log.Sugar() }(), banner+"V"+Version))

h.RegisterOnServeHook(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) RegisterOnShutdownHook

func (su *Supervisor) RegisterOnShutdownHook(cb func())

RegisterOnShutdownHook 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