Documentation ¶
Index ¶
- func ProxyHandler(target *url.URL, config *tls.Config) *httputil.ReverseProxy
- func ProxyHandlerRemote(target *url.URL, config *tls.Config) *httputil.ReverseProxy
- func RedirectHandler(target *url.URL, redirectStatus int) http.Handler
- func RegisterOnInterrupt(cb func())
- func ShutdownOnInterrupt(su *Supervisor, shutdownTimeout time.Duration) func()
- func WriteStartupLogOnServe(w io.Writer) func(TaskHost)
- type Configurator
- type Supervisor
- func (su *Supervisor) Configure(configurators ...Configurator) *Supervisor
- func (su *Supervisor) DeferFlow()
- func (su *Supervisor) ListenAndServe() error
- func (su *Supervisor) ListenAndServeAutoTLS(domain string, email string, cacheDir string) error
- func (su *Supervisor) ListenAndServeTLS(certFileOrContents string, keyFileOrContents string) error
- func (su *Supervisor) NoRedirect()
- func (su *Supervisor) RegisterOnError(cb func(error))
- func (su *Supervisor) RegisterOnServe(cb func(TaskHost))
- func (su *Supervisor) RegisterOnShutdown(cb func())
- func (su *Supervisor) RestoreFlow()
- func (su *Supervisor) Serve(l net.Listener) error
- func (su *Supervisor) Shutdown(ctx context.Context) error
- type TaskHost
- type TnterruptListener
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ProxyHandler ¶
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 ¶
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 ¶
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 ¶
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 // 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 ¶
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 ¶
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) 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 "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 ¶
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.
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: 3 * 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.
Callbacks will run as separate go routines.
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 ¶
HostURL returns the listening full url (scheme+host) based on the supervisor's server's address.
func (TaskHost) Shutdown ¶
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 ¶
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.