webapp

package module
v0.0.0-...-45fb5ce Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: Apache-2.0 Imports: 25 Imported by: 2

README

Package cloudeng.io/webapp

import cloudeng.io/webapp

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.

Constants

ACMEHTTP01Prefix
ACMEHTTP01Prefix = "/.well-known/acme-challenge/"

PreferredTLSMinVersion
PreferredTLSMinVersion = tls.VersionTLS13

PreferredTLSMinVersion is the preferred minimum TLS version for tls.Config instances created by this package.

Variables

PreferredCipherSuites
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
PreferredCurves = []tls.CurveID{
	tls.X25519,
	tls.CurveP256,
}

PreferredCurves is the list of preferred elliptic curves for tls.Config instances created by this package.

PreferredSignatureSchemes
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
func FindLeafPEM(certsPEM []*pem.Block) ([]byte, *x509.Certificate, error)

FindLeafPEM searches the supplied PEM blocks for the leaf certificate and returns its DER encoding along with the parsed x509.Certificate.

Func HealthzHandler
func HealthzHandler() http.Handler

HealthzHandler returns a handler that returns "ok" and a 200 status code.

Func NewHTTPClient
func NewHTTPClient(ctx context.Context, opts ...HTTPClientOption) (*http.Client, error)

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
func NewHTTPServerOnly(ctx context.Context, addr string, handler http.Handler) *http.Server

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 ParsePEM
func ParsePEM(pemData []byte) (privateKeys, publicKeys, certs []*pem.Block)

ParsePEM parses private keys and certificates from the provided PEM data.

Func ParsePrivateKeyDER
func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)

ParsePrivateKeyDER parses a DER encoded private key. It tries PKCS#1, PKCS#8 and then SEC 1 for EC keys.

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 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 SafePath
func SafePath(path string) error

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 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.

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.

Func TLSConfigUsingCertFiles
func TLSConfigUsingCertFiles(certFile, keyFile string) (*tls.Config, error)

TLSConfigUsingCertFiles returns a tls.Config configured with the certificate read from the supplied files.

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
func WaitForServers(ctx context.Context, interval time.Duration, addrs ...string) error

WaitForServers waits for all supplied addresses to be available by attempting to open a TCP connection to each address at the specified interval.

Func WaitForURLs
func WaitForURLs(ctx context.Context, interval time.Duration, urls ...string) error

WaitForURLs waits for all supplied URLs to be available by attempting to perform HTTP GET requests to each URL 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.

Functions
func NewCertServingCache(ctx 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 cached and used by the GetCertificate method, this allows for credentials etc to be passed to the ReadFileCtx method called by GetCertificate via the context.

Methods
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.

Functions
func WithCertCacheAllowedHosts(hosts ...string) CertServingCacheOption

WithCertCacheAllowedHosts sets the allowed hosts that the cache will serve certificates for.

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(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(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 CounterAdd
type CounterAdd func(ctx context.Context, delta float64)

CounterAdd is a function that adds a delta to a counter metric.

Type CounterInc
type CounterInc func(ctx context.Context)

CounterInc is a function that increments a counter metric.

Type CounterVecAdd
type CounterVecAdd func(ctx context.Context, delta float64, labels ...string)

CounterVecAdd is a function that adds a delta to a counter metric with the given labels.

Type CounterVecInc
type CounterVecInc func(ctx context.Context, labels ...string)

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.

Functions
func WithCustomCAPEMFile(caPEMFile string) HTTPClientOption

WithCustomCAPEMFile configures the HTTP client to use the specified custom CA PEM data as a root CA.

func WithCustomCAPool(caPool *x509.CertPool) HTTPClientOption

WithCustomCAPool configures the HTTP client to use the specified custom CA pool. It takes precedence over WithCustomCAPEMFile.

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.

Methods
func (hc HTTPServerConfig) TLSConfig() (*tls.Config, error)
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.

Methods
func (cl HTTPServerFlags) HTTPServerConfig() HTTPServerConfig

HTTPServerConfig returns an HTTPServerConfig based on the supplied flags.

Type Observe
type Observe func(ctx context.Context, value float64)

Observe is a function that records a value for an observer metric.

Type Port80Redirect
type Port80Redirect struct {
	Pattern string
	Redirect
}

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.

Functions
func RedirectAcmeHTTP01(host string) Redirect

RedirectAcmeHTTP01 returns a Redirect that will redirect ACME HTTP-01 challenges to the specified host.

func RedirectToHTTPSPort(addr string) Redirect

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.

Methods
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
type RedirectTarget func(*http.Request) (string, int)

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.

Functions
func LiteralRedirectTarget(to string, code int) RedirectTarget

LiteralRedirectTarget returns a RedirectTarget that always redirects to the specified URL with the specified status code.

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.

Methods
func (tc TLSCertConfig) TLSConfig() (*tls.Config, error)

TLSConfig returns a tls.Config.

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.

Methods
func (cl TLSCertFlags) TLSCertConfig() TLSCertConfig

Config returns a TLSCertConfig based on the supplied flags.

Examples

ExampleServeWithShutdown

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

Examples

Constants

View Source
const ACMEHTTP01Prefix = "/.well-known/acme-challenge/"
View Source
const PreferredTLSMinVersion = tls.VersionTLS13

PreferredTLSMinVersion is the preferred minimum TLS version for tls.Config instances created by this package.

Variables

PreferredCipherSuites is the list of preferred cipher suites for tls.Config instances created by this package.

View Source
var PreferredCurves = []tls.CurveID{
	tls.X25519,
	tls.CurveP256,
}

PreferredCurves is the list of preferred elliptic curves for tls.Config instances created by this package.

PreferredSignatureSchemes is the list of preferred signature schemes generally used for obtainint TLS certificates.

Functions

func FindLeafPEM

func FindLeafPEM(certsPEM []*pem.Block) ([]byte, *x509.Certificate, error)

FindLeafPEM searches the supplied PEM blocks for the leaf certificate and returns its DER encoding along with the parsed x509.Certificate.

func HealthzHandler

func HealthzHandler() http.Handler

HealthzHandler returns a handler that returns "ok" and a 200 status code.

func NewHTTPClient

func NewHTTPClient(ctx context.Context, opts ...HTTPClientOption) (*http.Client, error)

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

func NewHTTPServerOnly(ctx context.Context, addr string, handler http.Handler) *http.Server

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 ParsePEM

func ParsePEM(pemData []byte) (privateKeys, publicKeys, certs []*pem.Block)

ParsePEM parses private keys and certificates from the provided PEM data.

func ParsePrivateKeyDER

func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)

ParsePrivateKeyDER parses a DER encoded private key. It tries PKCS#1, PKCS#8 and then SEC 1 for EC keys.

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 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 SafePath

func SafePath(path string) error

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 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

func TLSConfigUsingCertFiles(certFile, keyFile string) (*tls.Config, error)

TLSConfigUsingCertFiles returns a tls.Config configured with the certificate read from the supplied files.

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

func WaitForServers(ctx context.Context, interval time.Duration, addrs ...string) error

WaitForServers waits for all supplied addresses to be available by attempting to open a TCP connection to each address at the specified interval.

func WaitForURLs

func WaitForURLs(ctx context.Context, client *http.Client, interval time.Duration, urls ...string) error

WaitForURLs waits for all supplied URLs to be available by attempting to perform HTTP GET requests to each URL 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(ctx 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 cached and used by the GetCertificate method, this allows for credentials etc to be passed to the ReadFileCtx method called by GetCertificate via the context.

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 CounterAdd

type CounterAdd func(ctx context.Context, delta float64)

CounterAdd is a function that adds a delta to a counter metric.

type CounterInc

type CounterInc func(ctx context.Context)

CounterInc is a function that increments a counter metric.

type CounterVecAdd

type CounterVecAdd func(ctx context.Context, delta float64, labels ...string)

CounterVecAdd is a function that adds a delta to a counter metric with the given labels.

type CounterVecInc

type CounterVecInc func(ctx context.Context, labels ...string)

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 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.

func (HTTPServerConfig) TLSConfig

func (hc HTTPServerConfig) TLSConfig() (*tls.Config, error)

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 Observe

type Observe func(ctx context.Context, value float64)

Observe is a function that records a value for an observer metric.

type Port80Redirect

type Port80Redirect struct {
	Pattern string
	Redirect
}

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

func RedirectAcmeHTTP01(host string) Redirect

RedirectAcmeHTTP01 returns a Redirect that will redirect ACME HTTP-01 challenges to the specified host.

func RedirectToHTTPSPort

func RedirectToHTTPSPort(addr string) Redirect

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

type RedirectTarget func(*http.Request) (string, int)

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 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.

func (TLSCertConfig) TLSConfig

func (tc TLSCertConfig) TLSConfig() (*tls.Config, error)

TLSConfig returns a tls.Config.

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.

Directories

Path Synopsis
cmd
acme module
webapp module
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/golang-jwt/jwt/v5 package.
Package jwtutil provides support for creating and verifying JSON Web Tokens (JWTs) managed by the github.com/golang-jwt/jwt/v5 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

Jump to

Keyboard shortcuts

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