httpsrv

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2025 License: MIT Imports: 18 Imported by: 0

README

English | 中文

HTTP Server

httpsrv is a convenient wrapper library for Go's net/http, designed to simplify and standardize the process of starting HTTP and HTTPS servers. It supports multiple TLS certificate management modes, including self-signed certificates, Let's Encrypt, external files, and remote APIs, allowing you to quickly launch a robust web server with simple configuration.


Features

  • Multiple Operating Modes:
    • HTTP: Quickly start a standard HTTP service.
    • Self-Signed: Automatically generate and manage self-signed TLS certificates for local development environments.
    • Let's Encrypt: Integrates with autocert to automatically obtain and renew Let's Encrypt certificates.
    • External: Use your existing certificate and private key files.
    • Remote API: Dynamically fetch certificates from a specified API endpoint.
  • Graceful Shutdown: Built-in Shutdown method for easy implementation of a graceful server shutdown.
  • Simple Configuration: Provides a clear and flexible configuration method through chain calls and the option pattern.
  • High Extensibility: The TLSer interface allows you to easily implement custom certificate management strategies, such as fetching certificates from Etcd, Consul, etc.

Examples of Usage

Below are usage examples for different modes.

1. Start a standard HTTP server

This is the simplest mode, requiring no TLS configuration.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-dev-frame/sponge/pkg/httpsrv"
)

func main() {
    // Create an HTTP Mux
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, HTTP World!")
    })

    // Configure http.Server
    httpServer := &http.Server{
        Addr:    ":8080",
        Handler: mux,
    }

    // Create and run the service
    fmt.Println("HTTP server listening on :8080")
    server := httpsrv.New(httpServer)
    if err := server.Run(); err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

2. HTTPS - Self-Signed Certificate (for development)

This mode automatically generates cert.pem and key.pem files, making it ideal for local development and testing.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-dev-frame/sponge/pkg/httpsrv"
)

func main() {
    // Create an HTTP Mux
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, HTTP World!")
    })

    // Configure http.Server
    httpServer := &http.Server{
        Addr:    ":8443",
        Handler: mux,
    }

    // Configure self-signed mode
    tlsConfig := httpsrv.NewTLSSelfSignedConfig(
        // Optional: Custom certificate storage directory
        //httpsrv.WithTLSSelfSignedCacheDir("certs/self-signed"),
        // Optional: Custom certificate validity period (in days)
        //httpsrv.WithTLSSelfSignedExpirationDays(365),
        // Optional: Add other IPs to the certificate
        //httpsrv.WithTLSSelfSignedWanIPs("192.168.1.100"),
    )
    
    // Create and run the service
    fmt.Println("HTTP server listening on :8443")
    server := httpsrv.New(httpServer, tlsConfig)
    if err := server.Run(); err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

3. HTTPS - Let's Encrypt (for production)

This mode automatically obtains certificates from Let's Encrypt and handles renewal.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-dev-frame/sponge/pkg/httpsrv"
)

func main() {
    // Create an HTTP Mux
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, HTTP World!")
    })

    httpServer := &http.Server{
        Addr:    ":443",
        Handler: mux,
    }

    // Configure Let's Encrypt mode
    tlsConfig := httpsrv.NewTLSEAutoEncryptConfig(
        "your-domain.com",        // Your domain
        "your-email@example.com", // Your email for Let's Encrypt notifications
        // Optional: Enable HTTP -> HTTPS automatic redirection (listens on :80 by default)
        //httpsrv.WithTLSEncryptEnableRedirect(),
        // Optional: Custom certificate cache directory
        //httpsrv.WithTLSEncryptCacheDir("certs/encrypt"),
    )

    fmt.Println("HTTP server listening on :443")
    server := httpsrv.New(httpServer, tlsConfig)
    if err := server.Run(); err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

4. HTTPS - Using External Certificate Files

If you already have your own certificate and private key files, you can use this mode.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-dev-frame/sponge/pkg/httpsrv"
)

func main() {
    // Create an HTTP Mux
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, HTTP World!")
    })

    httpServer := &http.Server{
        Addr:    ":8443",
        Handler: mux,
    }

    // Configure external file mode
    tlsConfig := httpsrv.NewTLSExternalConfig(
        "/path/to/your/cert.pem",
        "/path/to/your/key.pem",
    )

    fmt.Println("HTTP server listening on :8443")
    server := httpsrv.New(httpServer, tlsConfig)
    if err := server.Run(); err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

5. HTTPS - Fetching Certificates from a Remote API

This mode allows you to dynamically pull the certificate and private key from a URL. The API should return a JSON object containing cert_file and key_file fields, with their values being Base64-encoded PEM data, as shown below:

{
  "cert_file": "-----BEGIN CERTIFICATE-----\nCERTIFICATE_DATA\n-----END CERTIFICATE-----",
  "key_file": "-----BEGIN PRIVATE KEY-----\nPRIVATE_KEY_DATA\n-----END PRIVATE KEY-----"
}
package main

import (
    "fmt"
    "github.com/go-dev-frame/sponge/pkg/httpsrv"
    "net/http"
)

func main() {
    // Create an HTTP Mux
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, HTTP World!")
    })

    httpServer := &http.Server{
        Addr:    ":8443",
        Handler: mux,
    }

    // Configure remote API mode
    tlsConfig := httpsrv.NewTLSRemoteAPIConfig(
        "https://your-api-endpoint.com/certs",
        // Optional: Set request headers for authentication, etc.
        //httpsrv.WithTLSRemoteAPIHeaders(map[string]string{"Authorization": "Bearer your-token"}),
        // Optional: Set http.Client request timeout
        //httpsrv.WithTLSRemoteAPITimeout(10*time.Second),
    )

    fmt.Println("HTTP server listening on :8443")
    server := httpsrv.New(httpServer, tlsConfig)
    if err := server.Run(); err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Mode

type Mode string

Mode defines the server's running mode.

const (
	// ModeTLSSelfSigned runs the server using a self-signed TLS certificate (localhost or testing use).
	ModeTLSSelfSigned Mode = "self-signed"
	// ModeTLSEncrypt runs the server using a Let's Encrypt certificate (automatic certificate management).
	ModeTLSEncrypt Mode = "encrypt"
	// ModeTLSExternal runs the server using user-provided TLS certificate and key files.
	ModeTLSExternal Mode = "external"
	// ModeRemoteAPI runs the server using remote API to manage TLS certificate.
	ModeRemoteAPI = "remote-api"
)

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server TLS server.

func New

func New(server *http.Server, tlser ...TLSer) *Server

New returns a new Server with TLSer injected.

func (*Server) Run

func (s *Server) Run() error

Run starts the server according to the provided configuration.

func (*Server) Scheme

func (s *Server) Scheme() string

Scheme returns the scheme of the server, e.g. http or https.

func (*Server) Shutdown

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

Shutdown gracefully shuts down the server and releases resources.

type TLSAutoEncryptConfig

type TLSAutoEncryptConfig struct {
	// contains filtered or unexported fields
}

func NewTLSEAutoEncryptConfig

func NewTLSEAutoEncryptConfig(domain string, email string, opts ...TLSEncryptOption) *TLSAutoEncryptConfig

func (*TLSAutoEncryptConfig) Run

func (c *TLSAutoEncryptConfig) Run(server *http.Server) error

func (*TLSAutoEncryptConfig) Validate

func (c *TLSAutoEncryptConfig) Validate() error

type TLSEncryptOption

type TLSEncryptOption func(*tlsEncryptOptions)

TLSEncryptOption set tlsEncryptOptions.

func WithTLSEncryptCacheDir

func WithTLSEncryptCacheDir(cacheDir string) TLSEncryptOption

WithTLSEncryptCacheDir sets the directory to store Let's Encrypt certificates.

func WithTLSEncryptEnableRedirect

func WithTLSEncryptEnableRedirect(httpAddr ...string) TLSEncryptOption

WithTLSEncryptEnableRedirect enables the HTTP-to-HTTPS redirect service. By default, it listens on ":80". An optional httpAddr can be provided to specify a different address.

type TLSExternalConfig

type TLSExternalConfig struct {
	// contains filtered or unexported fields
}

func NewTLSExternalConfig

func NewTLSExternalConfig(certFile, keyFile string) *TLSExternalConfig

func (*TLSExternalConfig) Run

func (c *TLSExternalConfig) Run(server *http.Server) error

func (*TLSExternalConfig) Validate

func (c *TLSExternalConfig) Validate() error

type TLSRemoteAPIConfig

type TLSRemoteAPIConfig struct {
	// contains filtered or unexported fields
}

TLSRemoteAPIConfig implements certificate retrieval from other service API

func NewTLSRemoteAPIConfig

func NewTLSRemoteAPIConfig(url string, opts ...TLSRemoteAPIOption) *TLSRemoteAPIConfig

func (*TLSRemoteAPIConfig) Run

func (c *TLSRemoteAPIConfig) Run(server *http.Server) error

func (*TLSRemoteAPIConfig) Validate

func (c *TLSRemoteAPIConfig) Validate() error

type TLSRemoteAPIOption

type TLSRemoteAPIOption func(*tlsRemoteAPIOptions)

TLSRemoteAPIOption set tlsRemoteAPIOptions.

func WithTLSRemoteAPICacheDir

func WithTLSRemoteAPICacheDir(cacheDir string) TLSRemoteAPIOption

WithTLSRemoteAPICacheDir set cacheDir for tlsRemoteAPI.

func WithTLSRemoteAPIHeaders

func WithTLSRemoteAPIHeaders(headers map[string]string) TLSRemoteAPIOption

WithTLSRemoteAPIHeaders set headers for tlsRemoteAPI.

func WithTLSRemoteAPITimeout

func WithTLSRemoteAPITimeout(timeout time.Duration) TLSRemoteAPIOption

WithTLSRemoteAPITimeout set timeout for tlsRemoteAPI.

type TLSRemoteAPIResponse

type TLSRemoteAPIResponse struct {
	CertFile []byte `json:"cert_file"`
	KeyFile  []byte `json:"key_file"`
}

type TLSSelfSignedConfig

type TLSSelfSignedConfig struct {
	// contains filtered or unexported fields
}

func NewTLSSelfSignedConfig

func NewTLSSelfSignedConfig(opts ...TLSSelfSignedOption) *TLSSelfSignedConfig

func (*TLSSelfSignedConfig) Run

func (c *TLSSelfSignedConfig) Run(server *http.Server) error

func (*TLSSelfSignedConfig) Validate

func (c *TLSSelfSignedConfig) Validate() error

type TLSSelfSignedOption

type TLSSelfSignedOption func(*tlsSelfSignedOptions)

TLSSelfSignedOption set tlsSelfSignedOptions.

func WithTLSSelfSignedCacheDir

func WithTLSSelfSignedCacheDir(cacheDir string) TLSSelfSignedOption

WithTLSSelfSignedCacheDir sets the cache directory for self-signed certificates.

func WithTLSSelfSignedExpirationDays

func WithTLSSelfSignedExpirationDays(expirationDays int) TLSSelfSignedOption

WithTLSSelfSignedExpirationDays sets the expiration days for self-signed certificates.

func WithTLSSelfSignedWanIPs

func WithTLSSelfSignedWanIPs(wanIPs ...string) TLSSelfSignedOption

WithTLSSelfSignedWanIPs sets the IP addresses to include in the certificate.

type TLSer

type TLSer interface {
	Validate() error
	Run(server *http.Server) error
}

TLSer abstract different TLS operation schemes

Jump to

Keyboard shortcuts

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