Documentation
¶
Overview ¶
Package webapp and its sub-packages provide support for building webapps. This includes utility routines for managing http.Server instances, generating self-signed TLS certificates etc. The sub-packages provide support for managing the assets to be served, various forms of authentication and common toolchains such as webpack. For production purposes assets are built into the server's binary, but for development they are built into the binary but can be overridden from a local filesystem or from a running development server that manages those assets (eg. a webpack dev server instance). This provides the flexibility for both simple deployment of production servers and iterative development within the same application.
An example/template can be found in cmd/webapp.
Index ¶
- Constants
- Variables
- func FindLeafPEM(certsPEM []*pem.Block) ([]byte, *x509.Certificate, error)
- func GetConfigForClientNoSNI(matcher func(addr string) bool, ...) func(*tls.ClientHelloInfo) (*tls.Config, error)
- func HealthzHandler() http.Handler
- func NewHTTPClient(ctx context.Context, opts ...HTTPClientOption) (*http.Client, error)
- func NewHTTPServer(ctx context.Context, addr string, handler http.Handler) (net.Listener, *http.Server, error)
- func NewHTTPServerOnly(ctx context.Context, addr string, handler http.Handler) *http.Server
- func NewTLSServer(ctx context.Context, addr string, handler http.Handler, cfg *tls.Config) (net.Listener, *http.Server, error)
- func NewTLSServerOnly(ctx context.Context, addr string, handler http.Handler, cfg *tls.Config) *http.Server
- func ParseCertsPEM(pemData []byte) ([]*x509.Certificate, error)
- func ParseCipherSuite(name string) (uint16, error)
- func ParseCurveID(name string) (tls.CurveID, error)
- func ParsePEM(pemData []byte) (privateKeys, publicKeys, certs []*pem.Block)
- func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)
- func ParseSignatureAlgorithm(name string) (x509.SignatureAlgorithm, error)
- func ParseSignatureScheme(name string) (tls.SignatureScheme, error)
- func ParseTLSVersion(name string) (uint16, error)
- func ReadAndParseCertsPEM(ctx context.Context, fs file.ReadFileFS, pemFile string) ([]*x509.Certificate, error)
- func ReadAndParsePrivateKeyPEM(ctx context.Context, fs file.ReadFileFS, pemFile string) (crypto.Signer, error)
- func ReadBodyLimit(r *http.Request, replace bool, limit int64) ([]byte, error)
- func RedirectPort80(ctx context.Context, redirects ...Port80Redirect) error
- func RemoteAddrFromClientHello(hello *tls.ClientHelloInfo) string
- func SafePath(path string) error
- func SerialNumberHex(serial *big.Int) string
- func SerialNumberOpenSSL(serial *big.Int) string
- func ServeTLSWithShutdown(ctx context.Context, ln net.Listener, srv *http.Server, grace time.Duration) error
- func ServeWithShutdown(ctx context.Context, ln net.Listener, srv *http.Server, grace time.Duration) error
- func TLSConfigUsingCertFiles(certFile, keyFile string) (*tls.Config, error)
- func TLSConfigUsingCertFilesFS(ctx context.Context, store file.ReadFileFS, certFile, keyFile string) (*tls.Config, error)
- func TLSConfigUsingCertStore(ctx context.Context, store file.ReadFileFS, ...) (*tls.Config, error)
- func VerifyCertChain(dnsname string, certs []*x509.Certificate, roots *x509.CertPool) ([][]*x509.Certificate, error)
- func WaitForServers(ctx context.Context, interval time.Duration, addrs ...string) error
- func WaitForURLs(ctx context.Context, client *http.Client, interval time.Duration, ...) error
- type CertServingCache
- type CertServingCacheOption
- type CipherSuites
- type CounterAdd
- type CounterInc
- type CounterVecAdd
- type CounterVecInc
- type HTTPClientOption
- type HTTPServerConfig
- type HTTPServerError
- func (e HTTPServerError) BadRequest(w http.ResponseWriter, r *http.Request, m string, args ...any)
- func (e HTTPServerError) Forbidden(w http.ResponseWriter, r *http.Request, m string, args ...any)
- func (e HTTPServerError) Internal(w http.ResponseWriter, r *http.Request, m string, args ...any)
- func (e HTTPServerError) NotFound(w http.ResponseWriter, r *http.Request, m string, args ...any)
- func (e HTTPServerError) SendAndLog(w http.ResponseWriter, r *http.Request, status int, m string, args ...any)
- func (e HTTPServerError) Unauthorized(w http.ResponseWriter, r *http.Request, m string, args ...any)
- type HTTPServerFlags
- type Observe
- type Port80Redirect
- type Redirect
- type RedirectTarget
- type ServeFSWithHeaders
- type ServeWithHeaders
- type SignatureAlgorithms
- type TLSCertConfig
- type TLSCertFlags
- type TLSCurves
- type TLSSignatureSchemes
- type TLSVersion
- type TLSVersions
Examples ¶
Constants ¶
const ( // ACMEHTTP01Prefix is the well-known prefix for ACME HTTP-01 challenges. ACMEHTTP01Prefix = "/.well-known/acme-challenge/" // ACMEHTTP01HTTPPrefix is the well-known prefix for ACME HTTP-01 challenges // when used with http.ServeMux ACMEHTTP01HTTPPrefix = ACMEHTTP01Prefix // ACMEHTTP01ChiPrefix is the well-known prefix for ACME HTTP-01 challenges // when used with chi.Router ACMEHTTP01ChiPrefix = ACMEHTTP01Prefix + "*" )
const PreferredTLSMinVersion = tls.VersionTLS13
PreferredTLSMinVersion is the preferred minimum TLS version for tls.Config instances created by this package.
Variables ¶
var PreferredCipherSuites = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, }
PreferredCipherSuites is the list of preferred cipher suites for tls.Config instances created by this package.
PreferredCurves is the list of preferred elliptic curves for tls.Config instances created by this package.
var PreferredSignatureSchemes = []tls.SignatureScheme{ tls.ECDSAWithP256AndSHA256, tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512, }
PreferredSignatureSchemes is the list of preferred signature schemes generally used for obtainint TLS certificates.
Functions ¶
func FindLeafPEM ¶
FindLeafPEM searches the supplied PEM blocks for the leaf certificate and returns its DER encoding along with the parsed x509.Certificate.
func GetConfigForClientNoSNI ¶
func GetConfigForClientNoSNI(matcher func(addr string) bool, getConfig func(*tls.ClientHelloInfo) (*tls.Config, error)) func(*tls.ClientHelloInfo) (*tls.Config, error)
GetConfigForClientNoSNI returns a function that can be used as the GetConfigForClient callback in a tls.Config to allow connections from addresses that match the provided matcher function that do not include an SNI (Server Name Indication) in the TLS handshake. This is primarily intended for use with load balancer health checks etc.
func HealthzHandler ¶
HealthzHandler returns a handler that returns "ok" and a 200 status code.
func NewHTTPClient ¶
NewHTTPClient creates a new HTTP client configured according to the specified options.
func NewHTTPServer ¶
func NewHTTPServer(ctx context.Context, addr string, handler http.Handler) (net.Listener, *http.Server, error)
NewHTTPServer returns a new *http.Server using netutil.ParseAddrDefaultPort(addr "http") to obtain the address to listen on and NewHTTPServerOnly to create the server.
func NewHTTPServerOnly ¶
NewHTTPServerOnly returns a new *http.Server whose address defaults to ":http" and with it's BaseContext set to the supplied context. ErrorLog is set to log errors via the ctxlog package.
func NewTLSServer ¶
func NewTLSServer(ctx context.Context, addr string, handler http.Handler, cfg *tls.Config) (net.Listener, *http.Server, error)
NewTLSServer returns a new *http.Server using netutil.ParseAddrDefaultPort(addr, "https") to obtain the address to listen on and NewTLSServerOnly to create the server.
func NewTLSServerOnly ¶
func NewTLSServerOnly(ctx context.Context, addr string, handler http.Handler, cfg *tls.Config) *http.Server
NewTLSServerOnly returns a new *http.Server whose address defaults to ":https" and with it's BaseContext set to the supplied context and TLSConfig set to the supplied config. ErrorLog is set to log errors via the ctxlog package.
func ParseCertsPEM ¶
func ParseCertsPEM(pemData []byte) ([]*x509.Certificate, error)
ParseCertsPEM parses certificates from the provided PEM data.
func ParseCipherSuite ¶
ParseCipherSuite returns the cipher suite ID for the given name, as returned by tls.CipherSuiteName, e.g. "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". It returns an error if name does not match any cipher suite known to the crypto/tls package, including its insecure ones.
func ParseCurveID ¶
ParseCurveID returns the tls.CurveID for the given name, as returned by tls.CurveID.String(), e.g. "CurveP256" or "X25519". It returns an error if name does not match any known curve/group ID.
func ParsePrivateKeyDER ¶
ParsePrivateKeyDER parses a DER encoded private key. It tries PKCS#1, PKCS#8 and then SEC 1 for EC keys.
func ParseSignatureAlgorithm ¶
func ParseSignatureAlgorithm(name string) (x509.SignatureAlgorithm, error)
ParseSignatureAlgorithm returns the x509.SignatureAlgorithm for the given name, as returned by x509.SignatureAlgorithm.String(), e.g. "SHA256-RSA" or "Ed25519". It returns an error if name does not match any known signature algorithm.
func ParseSignatureScheme ¶
func ParseSignatureScheme(name string) (tls.SignatureScheme, error)
ParseSignatureScheme returns the tls.SignatureScheme for the given name, as returned by tls.SignatureScheme.String(), e.g. "ECDSAWithP256AndSHA256". It returns an error if name does not match any known signature scheme.
func ParseTLSVersion ¶
ParseTLSVersion returns the TLS version constant for the given name, as returned by tls.VersionName, e.g. "TLS 1.3". It also accepts a "0x0304"- style hex value (the fallback format tls.VersionName itself returns for versions it does not recognize) or a plain decimal number (e.g. "772"), for backwards compatibility with configs that specify the raw version number. It returns an error if name does not match any of these forms.
func ReadAndParseCertsPEM ¶
func ReadAndParseCertsPEM(ctx context.Context, fs file.ReadFileFS, pemFile string) ([]*x509.Certificate, error)
ReadAndParseCertsPEM loads certificates from the specified PEM file.
func ReadAndParsePrivateKeyPEM ¶
func ReadAndParsePrivateKeyPEM(ctx context.Context, fs file.ReadFileFS, pemFile string) (crypto.Signer, error)
ReadAndParsePrivateKeyPEM reads and parses a PEM encoded private key from the specified file.
func ReadBodyLimit ¶
ReadBodyLimit reads the request body with a size limit and returns it as a byte slice. If the body exceeds the limit ReadBodyLimit will return an http.MaxBytesError. If replace is true, the request body is replaced with a new reader that returns the same byte slice.
func RedirectPort80 ¶
func RedirectPort80(ctx context.Context, redirects ...Port80Redirect) error
RedirectPort80 starts an http.Server that will redirect port 80 to the specified redirect targets. The server will run in the background until the supplied context is canceled.
func RemoteAddrFromClientHello ¶
func RemoteAddrFromClientHello(hello *tls.ClientHelloInfo) string
RemoteAddrFromClientHello returns the remote address of the connection from the provided ClientHelloInfo. If the ClientHelloInfo or its Conn field is nil, it returns an empty string.
func SafePath ¶
SafePath checks if the given path is safe for use as a filename screening for control characters, windows device names, relative paths, paths (eg. a/b is not allowed) etc.
func SerialNumberHex ¶
SerialNumberHex formats a serial number as a hex string with leading zeros.
func SerialNumberOpenSSL ¶
SerialNumberOpenSSL formats a serial number in the same way as OpenSSL does.
func ServeTLSWithShutdown ¶
func ServeTLSWithShutdown(ctx context.Context, ln net.Listener, srv *http.Server, grace time.Duration) error
ServeTLSWithShutdown is like ServeWithShutdown except for a TLS server. Note that any TLS options must be configured prior to calling this function via the TLSConfig field in http.Server. If srv.BaseContext is nil it will be set to return ctx.
func ServeWithShutdown ¶
func ServeWithShutdown(ctx context.Context, ln net.Listener, srv *http.Server, grace time.Duration) error
ServeWithShutdown runs srv.ListenAndServe in background and then waits for the context to be canceled. It will then attempt to shutdown the web server within the specified grace period. If srv.BaseContext is nil it will be set to return ctx.
Example ¶
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"time"
"cloudeng.io/webapp"
)
func main() {
ctx := context.Background()
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
ln, srv, err := webapp.NewHTTPServer(ctx, "127.0.0.1:0", handler)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
host, port, _ := net.SplitHostPort(ln.Addr().String())
if port != "0" {
fmt.Printf("server listening on: %s:<some-port>\n", host)
}
if err := webapp.ServeWithShutdown(ctx, ln, srv, 5*time.Second); err != nil {
log.Printf("server shutdown error: %v", err)
}
fmt.Println("server shutdown complete")
}
Output: server listening on: 127.0.0.1:<some-port> server shutdown complete
func TLSConfigUsingCertFiles ¶
TLSConfigUsingCertFiles returns a tls.Config configured with the certificate read from the supplied files.
func TLSConfigUsingCertFilesFS ¶
func TLSConfigUsingCertFilesFS(ctx context.Context, store file.ReadFileFS, certFile, keyFile string) (*tls.Config, error)
TLSConfigUsingCertFilesFS returns a tls.Config configured with the certificate read from the supplied files which are accessed via the specified file.ReadFileFS.
func TLSConfigUsingCertStore ¶
func TLSConfigUsingCertStore(ctx context.Context, store file.ReadFileFS, cacheOpts ...CertServingCacheOption) (*tls.Config, error)
TLSConfigUsingCertStore returns a tls.Config configured with the certificate obtained from the specified certificate store accessed via a CertServingCache created with the supplied options.
func VerifyCertChain ¶
func VerifyCertChain(dnsname string, certs []*x509.Certificate, roots *x509.CertPool) ([][]*x509.Certificate, error)
VerifyCertChain verifies the supplied certificate chain using the provided root certificates and verifies that the leaf certificate is valid for the specified dnsname. It returns the verified chains on success.
func WaitForServers ¶
WaitForServers waits for all supplied addresses to be available by attempting to open a TCP connection to each address at the specified interval.
Types ¶
type CertServingCache ¶
type CertServingCache struct {
// contains filtered or unexported fields
}
CertServingCache implements an in-memory cache of TLS/SSL certificates loaded from a backing store. Validation of the certificates is performed on loading rather than every use. It provides a GetCertificate method that can be used by tls.Config. A TTL (default of 6 hours) is used so that the in-memory cache will reload certificates from the store on a periodic basis (with some jitter) to allow for certificates to be refreshed.
func NewCertServingCache ¶
func NewCertServingCache(_ context.Context, certStore file.ReadFileFS, opts ...CertServingCacheOption) *CertServingCache
NewCertServingCache returns a new instance of CertServingCache that uses the supplied file.ReadFileFS. The supplied context is a placeholder for future use and is not currently used. The GetCertificate method uses the context in the tls.ClientHelloInfo to read the certificate from the store.
func (*CertServingCache) GetCertificate ¶
func (m *CertServingCache) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)
GetCertificate can be assigned to tls.Config.GetCertificate.
type CertServingCacheOption ¶
type CertServingCacheOption func(*CertServingCache)
CertServingCacheOption represents options to NewCertServingCache.
func WithCertCacheAllowedHosts ¶
func WithCertCacheAllowedHosts(hosts ...string) CertServingCacheOption
WithCertCacheAllowedHosts sets the allowed hosts that the cache will serve certificates for.
func WithCertCacheNowFunc ¶
func WithCertCacheNowFunc(fn func() time.Time) CertServingCacheOption
WithCertCacheNowFunc sets the function used to obtain the current time. This is generally only required for testing purposes.
func WithCertCacheRootCAs ¶
func WithCertCacheRootCAs(rootCAs *x509.CertPool) CertServingCacheOption
WithCertCacheRootCAs sets the rootCAs to be used when verifying the validity of the certificate loaded from the back store.
func WithCertCacheTTL ¶
func WithCertCacheTTL(ttl time.Duration) CertServingCacheOption
WithCertCacheTTL sets the in-memory TTL beyond which cache entries are refreshed. This is generally only required for testing purposes.
type CipherSuites ¶
type CipherSuites []uint16
CipherSuites is a list of TLS cipher suite names, e.g. "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" as returned by tls.CipherSuiteName. When unmarshaled from YAML it accepts a list of such names, plus the special name "insecure" which expands to every cipher suite returned by tls.InsecureCipherSuites, and converts them to the corresponding crypto/tls constants.
func (CipherSuites) MarshalYAML ¶
func (c CipherSuites) MarshalYAML() (any, error)
MarshalYAML implements yaml.Marshaler.
func (CipherSuites) String ¶
func (c CipherSuites) String() string
String implements fmt.Stringer, returning a comma separated list of the cipher suite names in c, as returned by tls.CipherSuiteName.
func (*CipherSuites) UnmarshalYAML ¶
func (c *CipherSuites) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML implements yaml.Unmarshaler.
type CounterAdd ¶
CounterAdd is a function that adds a delta to a counter metric.
type CounterInc ¶
CounterInc is a function that increments a counter metric.
type CounterVecAdd ¶
CounterVecAdd is a function that adds a delta to a counter metric with the given labels.
type CounterVecInc ¶
CounterVecInc is a function that increments a counter metric with the given labels.
type HTTPClientOption ¶
type HTTPClientOption func(o *httpClientOptions)
HTTPClientOption is used to configure an HTTP client.
func WithCustomCAPEMFile ¶
func WithCustomCAPEMFile(caPEMFile string) HTTPClientOption
WithCustomCAPEMFile configures the HTTP client to use the specified custom CA PEM data as a root CA.
func WithCustomCAPool ¶
func WithCustomCAPool(caPool *x509.CertPool) HTTPClientOption
WithCustomCAPool configures the HTTP client to use the specified custom CA pool. It takes precedence over WithCustomCAPEMFile.
func WithDNSServer ¶
func WithDNSServer(addr string) HTTPClientOption
WithDNSServer configures the HTTP client to send all of its DNS resolution requests to the DNS server at the specified address, rather than using the system's default resolver. addr may be a bare IP address, in which case the standard DNS port (53) is used, or an address that includes an explicit port.
func WithTracingTransport ¶
func WithTracingTransport(to ...httptracing.TraceRoundtripOption) HTTPClientOption
WithTracingTransport configures the HTTP client to use a tracing round tripper with the specified options.
type HTTPServerConfig ¶
type HTTPServerConfig struct {
Address string `yaml:"address,omitempty"`
TLSCerts TLSCertConfig `yaml:"tls_certs,omitempty"`
}
HTTPServerConfig defines configuration for an http server.
type HTTPServerError ¶
type HTTPServerError string
HTTPServerError is an error that is returned by the HTTP server to the client and logged using ctxlog. The value of the error is used to identify the error in logs using the key 'error_src'. In addition, a random 64-bit integer is generated for each error and included in the response body and logs using the key 'error_id'.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
"strings"
"cloudeng.io/webapp"
)
func main() {
var err webapp.HTTPServerError = "my-component"
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
err.NotFound(w, req, "the page was not found", "user_id", 123)
res := w.Result()
fmt.Printf("Status: %d\n", res.StatusCode)
body := w.Body.String()
if strings.HasPrefix(body, "Not Found (") {
fmt.Println("Body format is correct")
}
}
Output: Status: 404 Body format is correct
func (HTTPServerError) BadRequest ¶
func (e HTTPServerError) BadRequest(w http.ResponseWriter, r *http.Request, m string, args ...any)
func (HTTPServerError) Forbidden ¶
func (e HTTPServerError) Forbidden(w http.ResponseWriter, r *http.Request, m string, args ...any)
func (HTTPServerError) Internal ¶
func (e HTTPServerError) Internal(w http.ResponseWriter, r *http.Request, m string, args ...any)
func (HTTPServerError) NotFound ¶
func (e HTTPServerError) NotFound(w http.ResponseWriter, r *http.Request, m string, args ...any)
func (HTTPServerError) SendAndLog ¶
func (e HTTPServerError) SendAndLog(w http.ResponseWriter, r *http.Request, status int, m string, args ...any)
SendAndLog sends the error to the client and logs it using ctxlog.
func (HTTPServerError) Unauthorized ¶
func (e HTTPServerError) Unauthorized(w http.ResponseWriter, r *http.Request, m string, args ...any)
type HTTPServerFlags ¶
type HTTPServerFlags struct {
Address string `subcmd:"https,:8080,address to run https web server on"`
TLSCertFlags
}
HTTPServerFlags defines commonly used flags for running an http server. TLS certificates may be retrieved either from a local cert and key file as specified by tls-cert and tls-key; this is generally used for testing or when the domain certificates are available only as files. The altnerative, preferred for production, source for TLS certificates is from a cache as specified by tls-cert-cache-type and tls-cert-cache-name. The cache may be on local disk, or preferably in some shared service such as Amazon's Secrets Service.
func (HTTPServerFlags) HTTPServerConfig ¶
func (cl HTTPServerFlags) HTTPServerConfig() HTTPServerConfig
HTTPServerConfig returns an HTTPServerConfig based on the supplied flags.
type Port80Redirect ¶
Port80Redirect is a Redirect that that will be registered using http.ServeMux with the specified pattern.
type Redirect ¶
type Redirect struct {
Description string // description of the redirect, only used for logging
Target RedirectTarget // function that returns the target URL and HTTP status code
Log bool // if true then log the redirect
}
Redirect defines a URL path prefix which will be redirected to the specified target.
func RedirectAcmeHTTP01 ¶
RedirectAcmeHTTP01 returns a Redirect that will redirect ACME HTTP-01 challenges to the specified host.
func RedirectToHTTPSPort ¶
RedirectToHTTPSPort returns a Redirect that will redirect to the specified address using https but with the following defaults: - if addr does not contain a host then the host from the request is used - if addr does not contain a port then port 443 is used.
func (Redirect) Handler ¶
func (r Redirect) Handler() http.HandlerFunc
Handler returns a function that will redirect requests using the Target function to determine the target URL and HTTP status code and will log the redirect. It is provided for use with other middleware packages that expect an http.Handler.
type RedirectTarget ¶
RedirectTarget is a function that given an http.Request returns the target URL for the redirect and the HTTP status code to use. The request and in particular the Request.URL should not be modified by RedirectTarget.
func LiteralRedirectTarget ¶
func LiteralRedirectTarget(to string, code int) RedirectTarget
LiteralRedirectTarget returns a RedirectTarget that always redirects to the specified URL with the specified status code.
type ServeFSWithHeaders ¶
type ServeFSWithHeaders struct {
// contains filtered or unexported fields
}
ServeFSWithHeaders is an http.Handler that serves files from an fs.FS with specified headers for specific URL paths.
func NewServeFSWithHeaders ¶
func NewServeFSWithHeaders(fs fs.FS, next http.Handler, rewrite func(string) string) *ServeFSWithHeaders
NewServeFSWithHeaders creates a new ServeFSWithHeaders handler that serves files from the provided fs.FS. The urlpaths registered via SetHeaders are used to look up which headers to apply; the optional rewrite function is applied to the URL path at registration time to produce the FS file path.
A leading '/' is stripped from the (possibly rewritten) path so URL paths like "/index.html" map naturally to FS paths like "index.html".
The next handler is called for any URL path for which SetHeaders has not been called. If next is nil such requests are answered with 404 Not Found.
func (*ServeFSWithHeaders) ServeHTTP ¶
func (s *ServeFSWithHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*ServeFSWithHeaders) SetHeaders ¶
func (s *ServeFSWithHeaders) SetHeaders(headers http.Header, urlpaths ...string)
SetHeaders registers headers for the given URL paths. The FS path for each URL path is computed once here (applying rewrite if set, then stripping a leading '/'), so ServeHTTP never derives a file path from request data. If headers is empty the file is served via http.ServeFileFS without extra headers.
type ServeWithHeaders ¶
type ServeWithHeaders struct {
// contains filtered or unexported fields
}
ServeWithHeaders is an http.Handler that serves a byte slice with specified headers and only supports GET requests to a specific URL path.
func NewServeWithHeaders ¶
func NewServeWithHeaders(headers http.Header, data []byte, urlpath string) ServeWithHeaders
NewServeWithHeaders creates a new ServeWithHeaders handler.
func (ServeWithHeaders) ServeHTTP ¶
func (s ServeWithHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves the file with the specified headers. If the requested URL path does not match the handler's URL path, it responds with 404 Not Found.
func (ServeWithHeaders) URLPath ¶
func (s ServeWithHeaders) URLPath() string
URLPath returns the URL path that this handler serves.
type SignatureAlgorithms ¶
type SignatureAlgorithms []x509.SignatureAlgorithm
SignatureAlgorithms is a list of x509 signature algorithm names, e.g. "SHA256-RSA" as returned by x509.SignatureAlgorithm.String(). When unmarshaled from YAML it accepts a list of such names, plus the special shortnames "rsa", "dsa", "ecdsa", "ed25519" and "rsa-pss" which each expand to every algorithm of that type, and converts them to the corresponding crypto/x509 constants.
func (SignatureAlgorithms) MarshalYAML ¶
func (s SignatureAlgorithms) MarshalYAML() (any, error)
MarshalYAML implements yaml.Marshaler.
func (SignatureAlgorithms) String ¶
func (s SignatureAlgorithms) String() string
String implements fmt.Stringer, returning a comma separated list of the signature algorithm names in s, as returned by x509.SignatureAlgorithm.String().
func (*SignatureAlgorithms) UnmarshalYAML ¶
func (s *SignatureAlgorithms) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML implements yaml.Unmarshaler.
type TLSCertConfig ¶
type TLSCertConfig struct {
CertFile string `yaml:"cert_file,omitempty"`
KeyFile string `yaml:"key_file,omitempty"`
}
TLSCertConfig defines configuration for TLS certificates obtained from local files.
type TLSCertFlags ¶
type TLSCertFlags struct {
CertFile string `subcmd:"tls-cert,,tls certificate file"`
KeyFile string `subcmd:"tls-key,,tls private key file"`
}
TLSCertFlags defines commonly used flags for obtaining TLS/SSL certificates. Certificates may be obtained in one of two ways: from a cache of certificates, or from local files.
func (TLSCertFlags) TLSCertConfig ¶
func (cl TLSCertFlags) TLSCertConfig() TLSCertConfig
Config returns a TLSCertConfig based on the supplied flags.
type TLSCurves ¶
TLSCurves is a list of TLS curve/group names, e.g. "CurveP256" or "X25519" as returned by tls.CurveID.String(). When unmarshaled from YAML it accepts a list of such names and converts them to the corresponding crypto/tls constants.
func (TLSCurves) MarshalYAML ¶
MarshalYAML implements yaml.Marshaler.
type TLSSignatureSchemes ¶
type TLSSignatureSchemes []tls.SignatureScheme
TLSSignatureSchemes is a list of TLS signature scheme names, e.g. "ECDSAWithP256AndSHA256" as returned by tls.SignatureScheme.String(). When unmarshaled from YAML it accepts a list of such names and converts them to the corresponding crypto/tls constants.
func (TLSSignatureSchemes) MarshalYAML ¶
func (s TLSSignatureSchemes) MarshalYAML() (any, error)
MarshalYAML implements yaml.Marshaler.
func (TLSSignatureSchemes) String ¶
func (s TLSSignatureSchemes) String() string
String implements fmt.Stringer, returning a comma separated list of the signature scheme names in s, as returned by tls.SignatureScheme.String().
func (*TLSSignatureSchemes) UnmarshalYAML ¶
func (s *TLSSignatureSchemes) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML implements yaml.Unmarshaler.
type TLSVersion ¶
type TLSVersion uint16
TLSVersion is a single TLS version, e.g. "TLS 1.3" as returned by tls.VersionName. When unmarshaled from YAML it accepts such a name, or a "0x..." hex value for a version tls.VersionName does not recognize, and converts it to the corresponding uint16 version number.
func (TLSVersion) MarshalYAML ¶
func (v TLSVersion) MarshalYAML() (any, error)
MarshalYAML implements yaml.Marshaler.
func (TLSVersion) String ¶
func (v TLSVersion) String() string
String implements fmt.Stringer, returning the version name, as returned by tls.VersionName.
func (*TLSVersion) UnmarshalYAML ¶
func (v *TLSVersion) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML implements yaml.Unmarshaler.
type TLSVersions ¶
type TLSVersions []uint16
TLSVersions is a list of TLS version names, e.g. "TLS 1.3" as returned by tls.VersionName. When unmarshaled from YAML it accepts a list of such names, or "0x..." hex values for versions tls.VersionName does not recognize, and converts them to the corresponding uint16 version numbers.
func (TLSVersions) MarshalYAML ¶
func (v TLSVersions) MarshalYAML() (any, error)
MarshalYAML implements yaml.Marshaler.
func (TLSVersions) String ¶
func (v TLSVersions) String() string
String implements fmt.Stringer, returning a comma separated list of the version names in v, as returned by tls.VersionName.
func (*TLSVersions) UnmarshalYAML ¶
func (v *TLSVersions) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML implements yaml.Unmarshaler.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
acme
module
|
|
|
webapp
module
|
|
|
Package cssutil provides utilities for working with CSS classes in HTML documents, including support for generating Tailwind CSS safelist configurations.
|
Package cssutil provides utilities for working with CSS classes in HTML documents, including support for generating Tailwind CSS safelist configurations. |
|
Package devtest provides utilities for the development and testing of web applications, including TLS certificate generation and management.
|
Package devtest provides utilities for the development and testing of web applications, including TLS certificate generation and management. |
|
chromedputil
Package chromedputil provides utility functions for working with the Chrome DevTools Protocol via github.com/chromedp.
|
Package chromedputil provides utility functions for working with the Chrome DevTools Protocol via github.com/chromedp. |
|
Package jsonapi provides utilities for working with json REST APIs.
|
Package jsonapi provides utilities for working with json REST APIs. |
|
Package tlsvalidate provides functions for validating TLS certificates across multiple hosts and addresses.
|
Package tlsvalidate provides functions for validating TLS certificates across multiple hosts and addresses. |
|
webauth
|
|
|
acme
Package acme provides support for working with ACNE service providers such as letsencrypt.org.
|
Package acme provides support for working with ACNE service providers such as letsencrypt.org. |
|
acme/certcache
Package certcache provides support for working with autocert caches with persistent backing stores for storing and distributing certificates.
|
Package certcache provides support for working with autocert caches with persistent backing stores for storing and distributing certificates. |
|
jwtutil
Package jwtutil provides support for creating and verifying JSON Web Tokens (JWTs) managed by the github.com/lestrrat-go/jwx/v3/jwk package.
|
Package jwtutil provides support for creating and verifying JSON Web Tokens (JWTs) managed by the github.com/lestrrat-go/jwx/v3/jwk package. |
|
webauthn/passkeys
Package passkeys provides support for creating and authenticating WebAuthn passkeys.
|
Package passkeys provides support for creating and authenticating WebAuthn passkeys. |
|
auth0
module
|
|