httpserver

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: BSD-3-Clause Imports: 30 Imported by: 0

Documentation

Overview

Package httpserver can host an HTTP server in the CLI app.

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultReadyFunc = ComposeReadyFuncs(
		ReportListening(),
		ReloadServer(),
	)

	DefaultShutdownFunc = ComposeReadyFuncs(
		ReportShutdown(),
	)
)

DefaultReadyFunc provides the default behavior when the server starts DefaultShutdownFunc provides the default behavior when the server shuts down

View Source
var (
	// ErrNotListening is reported when the server is not listening
	ErrNotListening = errors.New("server is not listening")
)
View Source
var HandlerRegistry = &provider.Registry{
	Name: "handlers",
	Providers: provider.Details{
		"ping": {
			Factory:  provider.FactoryOf(newPingHandlerWithOpts),
			HelpText: "Responds simply Generates a ping",
		},
		"file": {
			Factory:  provider.FactoryOf(newFileServerHandlerWithOpts),
			HelpText: "Serve a particular directory as static files",
			Defaults: map[string]any{
				"directory":              ".",
				"hide_directory_listing": "false",
			},
		},
		"reload": {
			Value: HandlerSpec(func(ctx context.Context, _ httpclient.VirtualPath) (http.Handler, error) {
				return NewReloadHandler(FromContext(ctx)), nil
			}),
			HelpText: "Reloads the server",
		},
		"redirect": {
			Factory:  provider.FactoryOf(newRedirectServerHandlerWithOpts),
			HelpText: "Redirect to the given path and provide a status code",
			Defaults: map[string]any{
				"to":   "/",
				"code": strconv.Itoa(http.StatusTemporaryRedirect),
			},
		},
		"echo": {
			Factory:  provider.FactoryOf(newEchoHandlerWithOpts),
			HelpText: "Reflects out the request and connection information",
			Defaults: map[string]any{
				"failsafe": "false",
			},
			Aliases: []string{"reflect"},
		},
	},
}

HandlerRegistry provides the default handler registry.

Functions

func NewEchoHandler added in v0.5.4

func NewEchoHandler(failsafe bool) http.Handler

NewEchoHandler provides a handler which echoes the request back in the response. An option failsafe indicates whether the response will always be 200 OK even if the request is malformed.

func NewHeaderMiddleware

func NewHeaderMiddleware(name, value string) func(http.Handler) http.Handler

NewHeaderMiddleware provides handler middleware which simply adds the given header

func NewPingHandler

func NewPingHandler() http.Handler

NewPingHandler provides a handler which simply replies with a message

func NewRecoveryMiddleware added in v0.11.0

func NewRecoveryMiddleware(next http.Handler) http.Handler

NewRecoveryMiddleware is middleware that recovers from panics, logs the panic and backtrace, and writes out a HTTP 500 (Internal Server Error) status if appropriate.

func NewReloadHandler added in v0.7.4

func NewReloadHandler(s *Server) http.Handler

NewReloadHandler provides a handler which triggers the server to reload all handlers

func NewRequestLoggerMiddleware added in v0.10.0

func NewRequestLoggerMiddleware(format string, out io.Writer) func(http.Handler) http.Handler

NewRequestLoggerMiddleware provides handler middleware to write to access log

func SourceAnnotation

func SourceAnnotation() (string, string)

SourceAnnotation gets the name and value of the annotation added to the Data of all flags that are initialized from this package

Types

type Action added in v0.12.0

type Action = cli.Action

Action provides a context action that affects the server

func ContextValue

func ContextValue(s *Server) Action

func FlagsAndArgs

func FlagsAndArgs() Action

FlagsAndArgs adds numerous flags that can be used to configure the server in the context. The default flags list contains all of the flag actions in this package except for SetHandler and its variants.

func HandleSpec added in v0.7.1

func HandleSpec(vpath httpclient.VirtualPath, spec HandlerSpec) Action

HandleSpec registers the given handler spec with the context server

func ListHandlers

func ListHandlers() Action

ListHandlers provides an action which lists the handlers for the handler flag. When used in the Uses pipeline, also sets reasonable defaults for a flag. This handler is not included in FlagsAndArgs

func RunServer

func RunServer(actionopt ...cli.Action) Action

RunServer locates the server in context and runs it until interrupt signal is detected. Optional actions run just before the server starts up, typically used to provide context-bound modifications to the server just in time.

func SetAccessLog

func SetAccessLog(v ...string) Action

func SetAddr

func SetAddr(s ...string) Action

SetAddr sets the server address, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.

func SetFileServerHandler

func SetFileServerHandler(v ...httpclient.VirtualPath) Action

SetFileServerHandler adds the specified file server handler to the mux. This can be called multiple times. This handler is not included in FlagsAndArgs

func SetHandler

func SetHandler(v ...httpclient.VirtualPath) Action

SetHandler adds the specified handler to the mux. This can be called multiple times. SetHandler only works if a Registry named "handlers" is present in the context to convert the handler spec to the correct implementation. Consider adding HandlerRegistry to the Uses pipeline.. This handler is not included in FlagsAndArgs

func SetHideDirectoryListings added in v0.7.3

func SetHideDirectoryListings() Action

SetHideDirectoryListings causes directories not to be listed

func SetHostname

func SetHostname(s ...string) Action

SetHostname sets the server address, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.

func SetIdleTimeout

func SetIdleTimeout(d ...time.Duration) Action

SetIdleTimeout sets the maximum amount of time to wait for the next request when keep-alives are enabled, which either uses the specified value or reads from the corresponding flag/arg to get the value to set. If zero is set, then the value of read time is used, unless both are zero in which case there is no timeout.

func SetMaxHeaderBytes

func SetMaxHeaderBytes(v ...int) Action

SetMaxHeaderBytes sets the maximum header size in bytes

func SetOpenInBrowser

func SetOpenInBrowser() Action

SetOpenInBrowser causes the default Web browser to open when the server is ready

func SetPort

func SetPort(s ...int) Action

SetPort sets the server port, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.

func SetReadHeaderTimeout

func SetReadHeaderTimeout(d ...time.Duration) Action

SetReadHeaderTimeout sets the amount of time allowed to read request headers, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.

func SetReadTimeout

func SetReadTimeout(d ...time.Duration) Action

SetReadTimeout sets the maximum duration for reading the entire request, including the body, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.

func SetServerHeader added in v0.7.0

func SetServerHeader(v ...string) Action

func SetShutdownTimeout

func SetShutdownTimeout(d ...time.Duration) Action

SetShutdownTimeout sets the maximum duration to wait for shutting down the server.

func SetStaticDirectory

func SetStaticDirectory(f ...*cli.File) Action

SetStaticDirectory sets the static directory to host

func SetTLSCertFile

func SetTLSCertFile(v ...*cli.File) Action

func SetTLSKeyFile

func SetTLSKeyFile(v ...*cli.File) Action

func SetWriteTimeout

func SetWriteTimeout(d ...time.Duration) Action

SetWriteTimeout sets the maximum duration before timing out writes of the response, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.

type Expander added in v0.12.1

type Expander = expander.Interface

Expander converts the given string key into its variable expansion

func ExpandRequest

func ExpandRequest(r *http.Request, ww wrapResponseWriter) Expander

ExpandRequest provides an expander that provides variables from a request in the context of a server.

type HandlerSpec

type HandlerSpec func(context.Context, httpclient.VirtualPath) (http.Handler, error)

HandlerSpec creates a handler from a virtual path. The virtual path defines how the handler works. Typically, the physical path identifies a useful feature or the location of a file, and the options may be used for any purpose of customization.

func FileServerHandlerSpec

func FileServerHandlerSpec() HandlerSpec

FileServerHandlerSpec creates a file server. The physical path in the virtual path specifies the base directory for the file server. An option named hide_directory_listing controls whether the directory listing response is served. The handler also consults the server for whether directory listings can be served.

func RegistryHandlerSpec

func RegistryHandlerSpec(name string) HandlerSpec

RegistryHandlerSpec creates a handler by looking it up as a provider in the registry that is named. The physical path in the virtual path specifies the name of the provider which is used. The virtual path's options are propagated to the registry factory function.

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

MiddlewareFunc defines a function that creates a middleware wrapper around another handler

type Option

type Option interface {
	cli.Action
	// contains filtered or unexported methods
}

Option is an option to configure the server Option can be used as an Action, typically within the Uses or Before pipeline.

func AddReadyFunc

func AddReadyFunc(ready ReadyFunc) Option

AddReadyFunc appends a callback for when the server is ready

func AddShutdownFunc

func AddShutdownFunc(shutdown ReadyFunc) Option

AddShutdownFunc adds a callback for when the server is shutting down

func Handle

func Handle(path string, h http.Handler) Option

Handle registers the given handler with the context server

func HandleFunc added in v0.7.0

func HandleFunc(path string, h http.HandlerFunc) Option

HandleFunc registers the given handler with the context server

func WithAccessLog added in v0.7.0

func WithAccessLog(s string) Option

WithAccessLog sets the format string for the access log

func WithAction added in v0.7.3

func WithAction(a cli.Action) Option

WithAction sets the action

func WithAddr

func WithAddr(addr string) Option

WithAddr sets the corresponding server field

func WithDefaultAction added in v0.7.3

func WithDefaultAction() Option

WithDefaultAction sets the action to the default

func WithDefaultServerFactory added in v0.12.0

func WithDefaultServerFactory() Option

WithDefaultServerFactory sets up the default server factory and built-in server middleware (connection settings and handler setup). This option is applied automatically by New.

func WithHandler

func WithHandler(handler http.Handler) Option

WithHandler sets the handler which will run on the server

func WithHandlerFactory

func WithHandlerFactory(f func(*Server) (http.Handler, error)) Option

WithHandlerFactory sets how to create the handler which will run on the server

func WithHideDirectoryListings added in v0.7.3

func WithHideDirectoryListings(v bool) Option

WithHideDirectoryListings disables directory listings

func WithHostname

func WithHostname(v string) Option

WithHostname sets the server hostname

func WithIdleTimeout added in v0.7.0

func WithIdleTimeout(d time.Duration) Option

WithIdleTimeout sets the amount of time to allow for idling

func WithMaxHeaderBytes added in v0.7.0

func WithMaxHeaderBytes(n int) Option

WithMaxHeaderBytes sets the amount max header bytes

func WithMiddleware

func WithMiddleware(m MiddlewareFunc) Option

WithMiddleware adds handler middleware

func WithPort

func WithPort(v int) Option

WithPort sets the server port

func WithReadHeaderTimeout added in v0.7.0

func WithReadHeaderTimeout(d time.Duration) Option

WithReadHeaderTimeout sets the amount of time to allow for reading headers

func WithReadTimeout added in v0.7.0

func WithReadTimeout(d time.Duration) Option

WithReadTimeout sets the amount of time to allow for reading requests

func WithReadyFunc

func WithReadyFunc(ready ReadyFunc) Option

WithReadyFunc sets a callback for when the server is listening

func WithServer added in v0.12.0

func WithServer(srv *http.Server) Option

WithServer sets the http.Server to use directly, bypassing the default factory. The connection settings and handler which have been configured with the other options are still applied to it.

func WithServerFactory added in v0.12.0

func WithServerFactory(fn func(context.Context) (*http.Server, error)) Option

WithServerFactory provides a factory for obtaining the http.Server.

func WithServerHeader added in v0.7.0

func WithServerHeader(s string) Option

WithServerHeader sets the contents of the server header

func WithShutdownFunc

func WithShutdownFunc(shutdown ReadyFunc) Option

WithShutdownFunc sets a callback for when the server is shutting down

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout sets the amount of time to allow the server to shutdown

func WithStaticDirectory added in v0.7.0

func WithStaticDirectory(path string) Option

WithStaticDirectory hosts a static directory

func WithTLSCertFile added in v0.7.0

func WithTLSCertFile(filename string) Option

WithTLSCertFile sets the file to use for the TLS cert

func WithTLSKeyFile added in v0.7.0

func WithTLSKeyFile(filename string) Option

WithTLSKeyFile sets the file to use for the TLS key

func WithWriteTimeout added in v0.7.0

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout sets the amount of time to allow for writing responses

type Options added in v0.7.4

type Options struct {
	Addr                  *string        `toml:"addr"                    json:"addr,omitempty"`
	Hostname              *string        `toml:"hostname"                json:"hostname,omitempty"`
	Port                  *int           `toml:"port"                    json:"port,omitempty"`
	TLSCertFile           *string        `toml:"tls-cert-file"           json:"tlsCertFile,omitempty"`
	TLSKeyFile            *string        `toml:"tls-key-file"            json:"tlsKeyFile,omitempty"`
	ServerHeader          *string        `toml:"server-header"           json:"serverHeader,omitempty"`
	AccessLog             *string        `toml:"access-log"              json:"accessLog,omitempty"`
	StaticDirectory       *string        `toml:"static-directory"        json:"staticDirectory,omitempty"`
	HideDirectoryListings *bool          `toml:"hide-directory-listings" json:"hideDirectoryListings,omitempty"`
	ShutdownTimeout       *time.Duration `toml:"shutdown-timeout"        json:"shutdownTimeout,omitempty"`
	ReadTimeout           *time.Duration `toml:"read-timeout"            json:"readTimeout,omitempty"`
	ReadHeaderTimeout     *time.Duration `toml:"read-header-timeout"     json:"readHeaderTimeout,omitempty"`
	WriteTimeout          *time.Duration `toml:"write-timeout"           json:"writeTimeout,omitempty"`
	IdleTimeout           *time.Duration `toml:"idle-timeout"            json:"idleTimeout,omitempty"`
	MaxHeaderBytes        *int           `toml:"max-header-bytes"        json:"maxHeaderBytes,omitempty"`
}

Options contains settings for the server which have data representations. Each non-nil field is applied when Options is used as an Option.

func (*Options) Execute added in v0.7.4

func (o *Options) Execute(ctx context.Context) error

type ReadyFunc

type ReadyFunc func(context.Context)

ReadyFunc provides a function for when the server has started or stopped

func ComposeReadyFuncs

func ComposeReadyFuncs(v ...ReadyFunc) ReadyFunc

ComposeReadyFuncs provides a ReadyFunc that combines a sequence

func OpenInBrowser

func OpenInBrowser(path ...string) ReadyFunc

OpenInBrowser is a function to open the server in the browser. This function is passed as a value to WithReadyFunc

func ReloadServer added in v0.7.1

func ReloadServer() ReadyFunc

ReloadServer provides a function which reloads reloadable handlers. This is included in the default ready function for the server. To defer loading to the first time a handler is invoked, you should remove this ready func from the server. If the server does not support reloading, this operation fails silently

func ReportListening

func ReportListening() ReadyFunc

ReportListening is a ready func that prints a message to stderr that the server is listening

func ReportShutdown added in v0.9.0

func ReportShutdown() ReadyFunc

ReportShutdown is a ready func that prints a goodbye message to stderr

type ReloadableHandler added in v0.7.1

type ReloadableHandler interface {
	http.Handler

	Invalidate()
}

ReloadableHandler provides a handler whose internal state can be invalidated so that the next time it serves, it recomputes it

func NewReloadableHandler added in v0.7.1

func NewReloadableHandler(fn func(context.Context) (http.Handler, error)) ReloadableHandler

NewReloadableHandler provides a handler which is reloadable. When the server starts or when the server is restarted, the function is invoked to generate the actual handler that is called. If an error is returned, the server will respond with 503 Service Unavailable.

type Server

type Server struct {
	cli.Action
	// contains filtered or unexported fields
}

Server provides an HTTP server (which encapsulates an http.Server) that can be initialized and hosted within a CLI app. The server is used within the Uses pipeline where it registers itself as a context service. The action RunServer is used to actually run the server.

The simplest action to use is RunServer(), which runs the server:

&cli.App{
   Name: "goserv",
   Uses: &httpserver.New(httpserver.WithHandler(...)),
   Action: httpserver.RunServer(),
}

This simple app has numerous flags to configure connection handling and to dynamically construct the server's router. Many dynamic server routing actions depend upon the server having a handler which is also a mux that contains a method Handle(string, http.Handler) to register additional handlers. (This is the same API provided by the built-in Go mux, http.ServeMux). There are other APIs provided by convention, documented in their respective contexts.

The server is configured exclusively with Options, either passed to New or applied later using Apply. The underlying http.Server is created on demand the first time it is needed, which is available from NewServer. How it gets created can be customized with WithServer or WithServerFactory.

The cmd/weave package provides weave, which is a command line utility that hosts a server for files and some built-in handlers, which is similar to what the default server does.

If you only want to add the Server to the context (typically in advanced scenarios where you are deeply customizing the behavior), you only use the action httpserver.ContextValue() with the server you want to add instead of add the server to the pipeline directly.

func FromContext

func FromContext(ctx context.Context) *Server

FromContext obtains the server from the context.

func New

func New(options ...Option) *Server

New creates a new HTTP server with the given handler creation callback.

func NewDefault added in v0.11.0

func NewDefault() *Server

func (*Server) Addr added in v0.12.0

func (s *Server) Addr() string

Addr specifies the address that the server will listen on

func (*Server) Apply added in v0.7.0

func (s *Server) Apply(opts ...Option)

func (*Server) Handle

func (s *Server) Handle(path string, h http.Handler) (err error)

func (*Server) HideDirectoryListing

func (s *Server) HideDirectoryListing() bool

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ctx context.Context) error

ListenAndServe creates the server if necessary and starts listening

func (*Server) NewServer added in v0.12.0

func (s *Server) NewServer(ctx context.Context) (*http.Server, error)

NewServer creates (or returns the cached) http.Server for the server

func (*Server) OpenInBrowser

func (s *Server) OpenInBrowser(path ...string) error

OpenInBrowser opens in the browser. The request path can also be specified

func (*Server) Pipeline added in v0.7.3

func (s *Server) Pipeline() cli.Action

func (*Server) ReloadAll added in v0.7.1

func (s *Server) ReloadAll()

ReloadAll causes the server to reload all reloadable handlers. To support reloading, the built-in mux must be used. In particular, you can't specify a handler or handler factory directly.

func (*Server) ReportListening

func (s *Server) ReportListening() error

func (*Server) Shutdown added in v0.12.0

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server

func (*Server) ShutdownTimeout

func (s *Server) ShutdownTimeout() time.Duration

ShutdownTimeout specifies how long to wait for the server to shutdown when a signal is received

func (*Server) TLSCertFile

func (s *Server) TLSCertFile() string

TLSCertFile specifies the certificate file to use in TLS

func (*Server) TLSKeyFile

func (s *Server) TLSKeyFile() string

TLSKeyFile specifies the certificate file to use in TLS

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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