{"modulePath":"github.com/Carbonfrost/joe-cli-http","version":"v0.14.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package httpserver\n\nPackage httpserver can host an HTTP server in the CLI app.\n\n## Variables\n\n```go\nvar (\n\tDefaultReadyFunc = ComposeReadyFuncs(\n\t\tReportListening(),\n\t\tReloadServer(),\n\t)\n\n\tDefaultShutdownFunc = ComposeReadyFuncs(\n\t\tReportShutdown(),\n\t)\n)\n```\nDefaultReadyFunc provides the default behavior when the server starts DefaultShutdownFunc provides the default behavior when the server shuts down\n\n```go\nvar (\n\t// ErrNotListening is reported when the server is not listening\n\tErrNotListening = errors.New(\"server is not listening\")\n)\n```\n\n```go\nvar HandlerRegistry = \u0026provider.Registry{\n\tName: \"handlers\",\n\tProviders: provider.Details{\n\t\t\"ping\": {\n\t\t\tFactory:  provider.FactoryOf(newPingHandlerWithOpts),\n\t\t\tHelpText: \"Responds simply Generates a ping\",\n\t\t},\n\t\t\"file\": {\n\t\t\tFactory:  provider.FactoryOf(newFileServerHandlerWithOpts),\n\t\t\tHelpText: \"Serve a particular directory as static files\",\n\t\t\tDefaults: map[string]any{\n\t\t\t\t\"directory\":              \".\",\n\t\t\t\t\"hide_directory_listing\": \"false\",\n\t\t\t},\n\t\t},\n\t\t\"reload\": {\n\t\t\tValue: HandlerSpec(func(ctx context.Context, _ httpclient.VirtualPath) (http.Handler, error) {\n\t\t\t\treturn NewReloadHandler(FromContext(ctx)), nil\n\t\t\t}),\n\t\t\tHelpText: \"Reloads the server\",\n\t\t},\n\t\t\"redirect\": {\n\t\t\tFactory:  provider.FactoryOf(newRedirectServerHandlerWithOpts),\n\t\t\tHelpText: \"Redirect to the given path and provide a status code\",\n\t\t\tDefaults: map[string]any{\n\t\t\t\t\"to\":   \"/\",\n\t\t\t\t\"code\": strconv.Itoa(http.StatusTemporaryRedirect),\n\t\t\t},\n\t\t},\n\t\t\"echo\": {\n\t\t\tFactory:  provider.FactoryOf(newEchoHandlerWithOpts),\n\t\t\tHelpText: \"Reflects out the request and connection information\",\n\t\t\tDefaults: map[string]any{\n\t\t\t\t\"failsafe\": \"false\",\n\t\t\t},\n\t\t\tAliases: []string{\"reflect\"},\n\t\t},\n\t},\n}\n```\nHandlerRegistry provides the default handler registry.\n\n## Functions\n\n```go\nfunc NewEchoHandler(failsafe bool) http.Handler\n```\nNewEchoHandler 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.\n\n```go\nfunc NewHeaderMiddleware(name, value string) func(http.Handler) http.Handler\n```\nNewHeaderMiddleware provides handler middleware which simply adds the given header\n\n```go\nfunc NewPingHandler() http.Handler\n```\nNewPingHandler provides a handler which simply replies with a message\n\n```go\nfunc NewRecoveryMiddleware(next http.Handler) http.Handler\n```\nNewRecoveryMiddleware is middleware that recovers from panics, logs the panic and backtrace, and writes out a HTTP 500 (Internal Server Error) status if appropriate.\n\n```go\nfunc NewReloadHandler(s *Server) http.Handler\n```\nNewReloadHandler provides a handler which triggers the server to reload all handlers\n\n```go\nfunc NewRequestLoggerMiddleware(format string, out io.Writer) func(http.Handler) http.Handler\n```\nNewRequestLoggerMiddleware provides handler middleware to write to access log\n\n```go\nfunc SourceAnnotation() (string, string)\n```\nSourceAnnotation gets the name and value of the annotation added to the Data of all flags that are initialized from this package\n\n## Types\n\n```go\ntype Action = cli.Action\n```\nAction provides a context action that affects the server\n\n```go\nfunc ContextValue(s *Server) Action\n```\nContextValue adds the server to the context\n\n```go\nfunc FlagsAndArgs() Action\n```\nFlagsAndArgs 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.\n\n```go\nfunc HandleSpec(vpath httpclient.VirtualPath, spec HandlerSpec) Action\n```\nHandleSpec registers the given handler spec with the context server\n\n```go\nfunc IDAnnotation(id ID) Action\n```\n\n```go\nfunc ListHandlers() Action\n```\nListHandlers 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](#FlagsAndArgs)\n\n```go\nfunc RunServer(actionopt ...cli.Action) Action\n```\nRunServer 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.\n\n```go\nfunc SetAccessLog(v ...string) Action\n```\nSetAccessLog sets the access log used by the server.\n\n```go\nfunc SetAddr(s ...string) Action\n```\nSetAddr sets the server address, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.\n\n```go\nfunc SetFileServerHandler(v ...httpclient.VirtualPath) Action\n```\nSetFileServerHandler adds the specified file server handler to the mux. This can be called multiple times. This handler is not included in [FlagsAndArgs](#FlagsAndArgs)\n\n```go\nfunc SetHandler(v ...httpclient.VirtualPath) Action\n```\nSetHandler 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](#HandlerRegistry) to the Uses pipeline.. This handler is not included in [FlagsAndArgs](#FlagsAndArgs)\n\n```go\nfunc SetHideDirectoryListings() Action\n```\nSetHideDirectoryListings causes directories not to be listed\n\n```go\nfunc SetHostname(s ...string) Action\n```\nSetHostname sets the server address, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.\n\n```go\nfunc SetIdleTimeout(d ...time.Duration) Action\n```\nSetIdleTimeout 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.\n\n```go\nfunc SetMaxHeaderBytes(v ...int) Action\n```\nSetMaxHeaderBytes sets the maximum header size in bytes\n\n```go\nfunc SetOpenInBrowser() Action\n```\nSetOpenInBrowser causes the default Web browser to open when the server is ready\n\n```go\nfunc SetPort(s ...int) Action\n```\nSetPort sets the server port, which either uses the specified value or reads from the corresponding flag/arg to get the value to set.\n\n```go\nfunc SetReadHeaderTimeout(d ...time.Duration) Action\n```\nSetReadHeaderTimeout 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.\n\n```go\nfunc SetReadTimeout(d ...time.Duration) Action\n```\nSetReadTimeout 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.\n\n```go\nfunc SetServerHeader(v ...string) Action\n```\nSetServerHeader sets the contents of the Server header in the response\n\n```go\nfunc SetShutdownTimeout(d ...time.Duration) Action\n```\nSetShutdownTimeout sets the maximum duration to wait for shutting down the server.\n\n```go\nfunc SetStaticDirectory(f ...*cli.File) Action\n```\nSetStaticDirectory sets the static directory to host\n\n```go\nfunc SetTLSCertFile(v ...*cli.File) Action\n```\nSetTLSCertFile applies the given TLS cert file to the server.\n\n```go\nfunc SetTLSKeyFile(v ...*cli.File) Action\n```\nSetTLSKeyFile applies the given TLS key file to the server.\n\n```go\nfunc SetWriteTimeout(d ...time.Duration) Action\n```\nSetWriteTimeout 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.\n\n```go\ntype ContextFilter int\n```\nContextFilter provides the context filters in this package\n\n```go\nconst (\n\t// Defines provides a context filter for flags and args defined by this package\n\tDefines ContextFilter = iota\n)\n```\n\n```go\nfunc (f ContextFilter) Describe() string\n```\nDescribe produces a representation of the context filter suitable for use in messages\n\n```go\nfunc (f ContextFilter) MarshalText() ([]byte, error)\n```\nMarshalText provides the textual representation\n\n```go\nfunc (f ContextFilter) Matches(ctx context.Context) bool\n```\nMatches the context filter\n\n```go\nfunc (f ContextFilter) String() string\n```\nString produces a textual representation of the context filter\n\n```go\nfunc (f *ContextFilter) UnmarshalText(b []byte) error\n```\nUnmarshalText converts the textual representation\n\n```go\ntype Expander = expander.Interface\n```\nExpander converts the given string key into its variable expansion\n\n```go\nfunc ExpandRequest(r *http.Request, ww wrapResponseWriter) Expander\n```\nExpandRequest provides an expander that provides variables from a request in the context of a server.\n\n```go\ntype HandlerSpec func(context.Context, httpclient.VirtualPath) (http.Handler, error)\n```\nHandlerSpec 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.\n\n```go\nfunc FileServerHandlerSpec() HandlerSpec\n```\nFileServerHandlerSpec 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.\n\n```go\nfunc RegistryHandlerSpec(name string) HandlerSpec\n```\nRegistryHandlerSpec 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.\n\n```go\ntype ID int\n```\nID identifies each of the flags and args registered by FlagsAndArgs\n\n```go\nconst (\n\tIDAccessLog ID\n\tIDAddr\n\tIDHideDirectoryListings\n\tIDHostname\n\tIDIdleTimeout\n\tIDMaxHeaderBytes\n\tIDOpenInBrowser\n\tIDPort\n\tIDReadHeaderTimeout\n\tIDReadTimeout\n\tIDServerHeader\n\tIDStaticDirectory\n\tIDTLSCertFile\n\tIDTLSKeyFile\n\tIDWriteTimeout\n)\n```\nVarious identifiers for flags and args registered by the package\n\n```go\nfunc LookupID(target any) (ID, bool)\n```\nLookupID gets the identity of a flag or arg registered by FlagsAndArgs, if present.\n\n```go\nfunc (i ID) MarshalText() ([]byte, error)\n```\nMarshalText provides the implementation of [encoding.TextMarshaler](/encoding#TextMarshaler)\n\n```go\nfunc (i ID) String() string\n```\n\n```go\nfunc (i *ID) UnmarshalText(data []byte) error\n```\nUnmarshalText provides the implementation of [encoding.TextUnarshaler](/encoding#TextUnarshaler)\n\n```go\ntype MiddlewareFunc func(next http.Handler) http.Handler\n```\nMiddlewareFunc defines a function that creates a middleware wrapper around another handler\n\n```go\ntype Option interface {\n\tcli.Action\n\t// contains filtered or unexported methods\n}\n```\nOption is an option to configure the server Option can be used as an Action, typically within the Uses or Before pipeline.\n\n```go\nfunc AddReadyFunc(ready ReadyFunc) Option\n```\nAddReadyFunc appends a callback for when the server is ready\n\n```go\nfunc AddShutdownFunc(shutdown ReadyFunc) Option\n```\nAddShutdownFunc adds a callback for when the server is shutting down\n\n```go\nfunc Handle(path string, h http.Handler) Option\n```\nHandle registers the given handler with the context server\n\n```go\nfunc HandleFunc(path string, h http.HandlerFunc) Option\n```\nHandleFunc registers the given handler with the context server\n\n```go\nfunc WithAccessLog(s string) Option\n```\nWithAccessLog sets the format string for the access log\n\n```go\nfunc WithAction(a cli.Action) Option\n```\nWithAction sets the action\n\n```go\nfunc WithAddr(addr string) Option\n```\nWithAddr sets the corresponding server field\n\n```go\nfunc WithDefaultAction() Option\n```\nWithDefaultAction sets the action to the default\n\n```go\nfunc WithDefaultServerFactory() Option\n```\nWithDefaultServerFactory sets up the default server factory and built-in server middleware (connection settings and handler setup).  This option is applied automatically by New.\n\n```go\nfunc WithHandler(handler http.Handler) Option\n```\nWithHandler sets the handler which will run on the server\n\n```go\nfunc WithHandlerFactory(f func(*Server) (http.Handler, error)) Option\n```\nWithHandlerFactory sets how to create the handler which will run on the server\n\n```go\nfunc WithHideDirectoryListings(v bool) Option\n```\nWithHideDirectoryListings disables directory listings\n\n```go\nfunc WithHostname(v string) Option\n```\nWithHostname sets the server hostname\n\n```go\nfunc WithIdleTimeout(d time.Duration) Option\n```\nWithIdleTimeout sets the amount of time to allow for idling\n\n```go\nfunc WithMaxHeaderBytes(n int) Option\n```\nWithMaxHeaderBytes sets the amount max header bytes\n\n```go\nfunc WithMiddleware(m MiddlewareFunc) Option\n```\nWithMiddleware adds handler middleware\n\n```go\nfunc WithPort(v int) Option\n```\nWithPort sets the server port\n\n```go\nfunc WithReadHeaderTimeout(d time.Duration) Option\n```\nWithReadHeaderTimeout sets the amount of time to allow for reading headers\n\n```go\nfunc WithReadTimeout(d time.Duration) Option\n```\nWithReadTimeout sets the amount of time to allow for reading requests\n\n```go\nfunc WithReadyFunc(ready ReadyFunc) Option\n```\nWithReadyFunc sets a callback for when the server is listening\n\n```go\nfunc WithServer(srv *http.Server) Option\n```\nWithServer 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.\n\n```go\nfunc WithServerFactory(fn func(context.Context) (*http.Server, error)) Option\n```\nWithServerFactory provides a factory for obtaining the http.Server.\n\n```go\nfunc WithServerHeader(s string) Option\n```\nWithServerHeader sets the contents of the server header\n\n```go\nfunc WithShutdownFunc(shutdown ReadyFunc) Option\n```\nWithShutdownFunc sets a callback for when the server is shutting down\n\n```go\nfunc WithShutdownTimeout(d time.Duration) Option\n```\nWithShutdownTimeout sets the amount of time to allow the server to shutdown\n\n```go\nfunc WithStaticDirectory(path string) Option\n```\nWithStaticDirectory hosts a static directory\n\n```go\nfunc WithTLSCertFile(filename string) Option\n```\nWithTLSCertFile sets the file to use for the TLS cert\n\n```go\nfunc WithTLSKeyFile(filename string) Option\n```\nWithTLSKeyFile sets the file to use for the TLS key\n\n```go\nfunc WithWriteTimeout(d time.Duration) Option\n```\nWithWriteTimeout sets the amount of time to allow for writing responses\n\n```go\ntype Options struct {\n\tAddr                  *string        `toml:\"addr\"                    json:\"addr,omitempty\"`\n\tHostname              *string        `toml:\"hostname\"                json:\"hostname,omitempty\"`\n\tPort                  *int           `toml:\"port\"                    json:\"port,omitempty\"`\n\tTLSCertFile           *string        `toml:\"tls-cert-file\"           json:\"tlsCertFile,omitempty\"`\n\tTLSKeyFile            *string        `toml:\"tls-key-file\"            json:\"tlsKeyFile,omitempty\"`\n\tServerHeader          *string        `toml:\"server-header\"           json:\"serverHeader,omitempty\"`\n\tAccessLog             *string        `toml:\"access-log\"              json:\"accessLog,omitempty\"`\n\tStaticDirectory       *string        `toml:\"static-directory\"        json:\"staticDirectory,omitempty\"`\n\tHideDirectoryListings *bool          `toml:\"hide-directory-listings\" json:\"hideDirectoryListings,omitempty\"`\n\tShutdownTimeout       *time.Duration `toml:\"shutdown-timeout\"        json:\"shutdownTimeout,omitempty\"`\n\tReadTimeout           *time.Duration `toml:\"read-timeout\"            json:\"readTimeout,omitempty\"`\n\tReadHeaderTimeout     *time.Duration `toml:\"read-header-timeout\"     json:\"readHeaderTimeout,omitempty\"`\n\tWriteTimeout          *time.Duration `toml:\"write-timeout\"           json:\"writeTimeout,omitempty\"`\n\tIdleTimeout           *time.Duration `toml:\"idle-timeout\"            json:\"idleTimeout,omitempty\"`\n\tMaxHeaderBytes        *int           `toml:\"max-header-bytes\"        json:\"maxHeaderBytes,omitempty\"`\n}\n```\nOptions contains settings for the server which have data representations. Each non-nil field is applied when Options is used as an Option.\n\n```go\nfunc (o *Options) Execute(ctx context.Context) error\n```\nExecute implements the Action.Execute method\n\n```go\ntype ReadyFunc func(context.Context)\n```\nReadyFunc provides a function for when the server has started or stopped\n\n```go\nfunc ComposeReadyFuncs(v ...ReadyFunc) ReadyFunc\n```\nComposeReadyFuncs provides a ReadyFunc that combines a sequence\n\n```go\nfunc OpenInBrowser(path ...string) ReadyFunc\n```\nOpenInBrowser is a function to open the server in the browser.  This function is passed as a value to WithReadyFunc\n\n```go\nfunc ReloadServer() ReadyFunc\n```\nReloadServer 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\n\n```go\nfunc ReportListening() ReadyFunc\n```\nReportListening is a ready func that prints a message to stderr that the server is listening\n\n```go\nfunc ReportShutdown() ReadyFunc\n```\nReportShutdown is a ready func that prints a goodbye message to stderr\n\n```go\ntype ReloadableHandler interface {\n\thttp.Handler\n\n\tInvalidate()\n}\n```\nReloadableHandler provides a handler whose internal state can be invalidated so that the next time it serves, it recomputes it\n\n```go\nfunc NewReloadableHandler(fn func(context.Context) (http.Handler, error)) ReloadableHandler\n```\nNewReloadableHandler 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.\n\n```go\ntype Server struct {\n\tcli.Action\n\t// contains filtered or unexported fields\n}\n```\nServer 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.\n\nThe simplest action to use is RunServer(), which runs the server:\n\n\t\u0026cli.App{\n\t   Name: \"goserv\",\n\t   Uses: \u0026httpserver.New(httpserver.WithHandler(...)),\n\t   Action: httpserver.RunServer(),\n\t}\n\nThis 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.\n\nThe 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.\n\nThe 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.\n\nIf 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.\n\n```go\nfunc FromContext(ctx context.Context) *Server\n```\nFromContext obtains the server from the context.\n\n```go\nfunc New(options ...Option) *Server\n```\nNew creates a new HTTP server with the given handler creation callback.\n\n```go\nfunc NewDefault() *Server\n```\nNewDefault creates the default server which supports static serving from the file directory\n\n```go\nfunc (s *Server) Addr() string\n```\nAddr specifies the address that the server will listen on\n\n```go\nfunc (s *Server) Apply(opts ...Option)\n```\nApply will apply the specified options to the server\n\n```go\nfunc (s *Server) Handle(path string, h http.Handler) (err error)\n```\n\n```go\nfunc (s *Server) HideDirectoryListing() bool\n```\n\n```go\nfunc (s *Server) ListenAndServe(ctx context.Context) error\n```\nListenAndServe creates the server if necessary and starts listening\n\n```go\nfunc (s *Server) NewServer(ctx context.Context) (*http.Server, error)\n```\nNewServer creates (or returns the cached) http.Server for the server\n\n```go\nfunc (s *Server) OpenInBrowser(path ...string) error\n```\nOpenInBrowser opens in the browser.  The request path can also be specified\n\n```go\nfunc (s *Server) Pipeline() cli.Action\n```\nPipeline retrieves the pipeline that runs when the server is added to a pipeline.\n\n```go\nfunc (s *Server) ReloadAll()\n```\nReloadAll 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.\n\n```go\nfunc (s *Server) ReportListening() error\n```\n\n```go\nfunc (s *Server) Shutdown(ctx context.Context) error\n```\nShutdown gracefully shuts down the server\n\n```go\nfunc (s *Server) ShutdownTimeout() time.Duration\n```\nShutdownTimeout specifies how long to wait for the server to shutdown when a signal is received\n\n```go\nfunc (s *Server) TLSCertFile() string\n```\nTLSCertFile specifies the certificate file to use in TLS\n\n```go\nfunc (s *Server) TLSKeyFile() string\n```\nTLSKeyFile specifies the certificate file to use in TLS\n\n","path":"github.com/Carbonfrost/joe-cli-http/httpserver","name":"httpserver","synopsis":"Package httpserver can host an HTTP server in the CLI app.","isRedistributable":true}
