host

package
v12.2.10 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2024 License: BSD-3-Clause Imports: 20 Imported by: 15

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ProxyHandler

func ProxyHandler(target *url.URL, config *tls.Config) *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.

Look `ProxyHandlerRemote` too.

func ProxyHandlerRemote added in v12.2.0

func ProxyHandlerRemote(target *url.URL, config *tls.Config) *httputil.ReverseProxy

ProxyHandlerRemote returns a new ReverseProxy that rewrites URLs to the scheme, host, and path provided in target. Case 1: req.Host == target.Host behavior same as ProxyHandler Case 2: req.Host != target.Host the target request will be forwarded to the target's url insecureSkipVerify indicates enable ssl certificate verification or not.

Look `ProxyHandler` too.

func RedirectHandler added in v12.2.0

func RedirectHandler(target *url.URL, redirectStatus int) http.Handler

RedirectHandler returns a simple redirect handler. See `NewProxy` or `ProxyHandler` for more features.

func RegisterOnInterrupt

func RegisterOnInterrupt(cb func())

RegisterOnInterrupt registers a global function to call when CTRL+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.

func NonBlocking added in v12.2.10

func NonBlocking() Configurator

NonBlocking sets the server to non-blocking mode. Use its `Wait` method to wait for server to be up and running.

type Supervisor

type Supervisor struct {
	Server *http.Server
	// FriendlyAddr can be set to customize the "Now Listening on: {FriendlyAddr}".
	FriendlyAddr string // e.g mydomain.com instead of :443 when AutoTLS is used, see `WriteStartupLogOnServe` task.

	// IgnoreErrors should contains the errors that should be ignored
	// on both serve functions return statements and error handlers.
	//
	// Note that this will match the string value instead of the equality of the type's variables.
	//
	// Defaults to empty.
	IgnoredErrors []string

	// Fallback should return a http.Server, which may already running
	// to handle the HTTP/1.1 clients when TLS/AutoTLS.
	// On manual TLS the accepted "challengeHandler" just returns the passed handler,
	// otherwise it binds to the acme challenge wrapper.
	// Example:
	//      Fallback = func(h func(fallback http.Handler) http.Handler) *http.Server {
	//          s := &http.Server{
	//             Handler: h(myServerHandler),
	//             ...otherOptions
	//          }
	//          go s.ListenAndServe()
	//          return s
	//      }
	Fallback func(challegeHandler func(fallback http.Handler) http.Handler) *http.Server

	// See `iris.Configuration.SocketSharding`.
	SocketSharding bool
	// If more than zero then tcp keep alive listener is attached instead of the simple TCP listener.
	// See `iris.Configuration.KeepAlive`
	KeepAlive time.Duration
	// 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, config *tls.Config) *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 NewProxyRemote added in v12.2.0

func NewProxyRemote(hostAddr string, target *url.URL, config *tls.Config) *Supervisor

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

Usage: target, _ := url.Parse("https://anotherdomain.com/abc") proxy := NewProxyRemote("mydomain.com", target, false) 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) 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 "kataras2006@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(certFileOrContents string, keyFileOrContents 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) NoRedirect added in v12.2.0

func (su *Supervisor) NoRedirect()

NoRedirect should be called before `ListenAndServeTLS` when secondary http1 to http2 server is not required. This method will disable the automatic registration of secondary http.Server which would redirect "http://" requests to their "https://" equivalent.

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)
if err := su.Shutdown(context.TODO()); err != nil {
	panic(err)
}
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.

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.

Callbacks will run as separate go routines.

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.

func (*Supervisor) Wait added in v12.2.10

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

Wait blocks until server is up and running or a serve failure.

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.

type TnterruptListener added in v12.2.0

type TnterruptListener interface {
	Register(cb func())
	FireNow()
}
var Interrupt TnterruptListener = 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.

type Waiter added in v12.2.10

type Waiter struct {
	// contains filtered or unexported fields
}

Waiter is a helper for waiting for a server to be up and running.

func NewWaiter added in v12.2.10

func NewWaiter(defaultMaxRetries int, addressFunc func() string) *Waiter

NewWaiter returns a new Waiter.

func (*Waiter) Fail added in v12.2.10

func (w *Waiter) Fail(err error)

Fail is called by the server's Run method when the server failed to start.

func (*Waiter) Wait added in v12.2.10

func (w *Waiter) Wait(ctx context.Context) error

Wait blocks the main goroutine until the application is up and running.

Jump to

Keyboard shortcuts

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