webserv

package module
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2024 License: MIT Imports: 10 Imported by: 4

README

build coverage goreport Docs

webserv

Thin web server stub.

Given a listen address, certificate directory, user name and data directory:

  • If certificate directory is not blank, reads fullchain.pem and privkey.pem from it.
  • If the listen address does not specify a port, default port depends on initial user privileges and if we have a certificate.
  • Starts listening on the address and port.
  • If user name is given, switch to that user.
  • If data directory is given, create it if needed and then switch current directory to it.

Usage

go get github.com/linkdata/webserv

package main

import (
	"flag"
	"log/slog"
	"net/http"

	"github.com/linkdata/webserv"
)

var (
	flagListen  = flag.String("listen", "", "serve HTTP requests on given [address][:port]")
	flagCertDir = flag.String("certdir", "", "where to find fullchain.pem and privkey.pem")
	flagUser    = flag.String("user", "www-data", "switch to this user after startup (*nix only)")
	flagDataDir = flag.String("datadir", "$HOME", "where to store data files after startup")
)

func main() {
	flag.Parse()

	cfg := webserv.Config{
		Listen:  *flagListen,
		CertDir: *flagCertDir,
		User:    *flagUser,
		DataDir: *flagDataDir,
	}

	l, err := cfg.Apply(slog.Default())
	if err == nil {
		defer l.Close()
		slog.Info("listening", "address", l.Addr(), "url", cfg.ListenURL)
		http.DefaultServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			_, _ = w.Write([]byte("<html><body>Hello world!</body></html>"))
		})
		err = http.Serve(l, nil)
	}
	slog.Error(err.Error())
}

Documentation

Overview

Example
package main

import (
	"flag"
	"log/slog"
	"net/http"
	"os"
	"time"

	"github.com/linkdata/webserv"
)

var (
	flagListen  = flag.String("listen", "", "serve HTTP requests on given [address][:port]")
	flagCertDir = flag.String("certdir", "", "where to find fullchain.pem and privkey.pem")
	flagUser    = flag.String("user", "www-data", "switch to this user after startup (*nix only)")
	flagDataDir = flag.String("datadir", "$HOME", "where to store data files after startup")
)

// make sure we don't time out on the Go playground
func dontTimeOutOnGoPlayground() {
	go func() {
		time.Sleep(time.Second)
		slog.Info("goodbye!")
		os.Exit(0)
	}()
}

func main() {
	flag.Parse()

	cfg := webserv.Config{
		Listen:  *flagListen,
		CertDir: *flagCertDir,
		User:    *flagUser,
		DataDir: *flagDataDir,
	}

	l, err := cfg.Apply(slog.Default())
	if err == nil {
		defer l.Close()
		slog.Info("listening", "address", l.Addr(), "url", cfg.ListenURL)
		http.DefaultServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			_, _ = w.Write([]byte("<html><body>Hello world!</body></html>"))
		})
		dontTimeOutOnGoPlayground()
		err = http.Serve(l, nil)
	}
	slog.Error(err.Error())
}

Index

Examples

Constants

View Source
const (
	FullchainPem = "fullchain.pem"
	PrivkeyPem   = "privkey.pem"
)

Variables

View Source
var ErrBecomeUser = errBecomeUser{}

Functions

func BecomeUser

func BecomeUser(userName string) error

BecomeUser switches to the given userName if not empty.

It sets the GID, UID and changes the USER and HOME environment variables accordingly. It unsets XDG_CONFIG_HOME.

Returns ErrBecomeUserNotImplemented if the current OS is not supported.

func DefaultDataDir

func DefaultDataDir(dataDir, defaultSuffix string) (string, error)

DefaultDataDir returns dataDir if not empty, otherwise if defaultSuffix is not empty it returns the joined path of os.UserConfigDir() and defaultSuffix.

func Listener

func Listener(listenAddr, certDir, fullchainPem, privkeyPem string) (l net.Listener, listenUrl, absCertDir string, err error)

Listener creates a net.Listener given an optional preferred address or port and an optional directory containing certificate files.

If certDir is not empty, it calls LoadCert to load fullchain.pem and privkey.pem.

The listener will default to all addresses and standard port depending on privileges and if a certificate was loaded or not.

These defaults can be overridden with the listenAddr argument.

Returns the net.Listener and listenURL if there was no error. If certificates were successfully loaded, absCertDir will be the absolute path to that directory.

func LoadCert

func LoadCert(certDir, fullchainPem, privkeyPem string) (cert *tls.Certificate, absCertDir string, err error)

LoadCert does nothing if certDir is empty, otherwise it expands environment variables and transforms it into an absolute path. It then tries to load a X509 key pair from the files named fullchainPem and privkeyPem from the resulting directory.

If fullchainPem is empty, it defaults to "fullchain.pem". If privkeyPem is empty, it defaults to "privkey.pem".

Return a non-nil cert and absolute path to certDir if there are no errors.

func UseDataDir

func UseDataDir(dataDir string, mode fs.FileMode) (string, error)

UseDataDir expands environment variables in dataDir and transforms it into an absolute path. Then, if mode is not zero, it creates the path if it does not exist. Does nothing if dataDir is empty.

Returns the final path or an empty string if dataDir was empty.

Types

type Config

type Config struct {
	Listen               string      // optional specific address (and/or port) to listen on
	CertDir              string      // if set, directory to look for fullchain.pem and privkey.pem
	FullchainPem         string      // set to override filename for "fullchain.pem"
	PrivkeyPem           string      // set to override filename for "privkey.pem"
	User                 string      // if set, user to switch to after opening listening port
	DataDir              string      // if set, change current directory to it
	DataDirMode          fs.FileMode // if nonzero, create DataDir if it does not exist using this mode
	DefaultDataDirSuffix string      // if set and DataDir is not set, use the user's default data dir plus this suffix
	ListenURL            string      // after Apply called, an URL we listen on (e.g. "https://localhost:8443")
}

func (*Config) Apply

func (cfg *Config) Apply(logger InfoLogger) (l net.Listener, err error)

Apply performs initial setup for a simple web server, optionally logging informational messages if it loads certificates, switches the current user, or switches to the data directory.

First it loads certificates if CertDir is set, and then starts a net.Listener (TLS or normal). The listener will default to all addresses and standard port depending on privileges and if a certificate was loaded or not.

If Listen was set, any address or port given there overrides these defaults.

If User is set it then switches to that user and the users primary group. Note that this is not supported on Windows.

If DataDir or DefaultDataDirSuffix is set, calculates the absolute data directory path and sets DataDir. If DataDirMode is nonzero, the directory will be created if necessary.

On a non-error return, CertDir and DataDir will be absolute paths or be empty, and ListenURL will be a printable and connectable URL like "http://localhost:80".

type InfoLogger added in v0.8.0

type InfoLogger interface {
	Info(msg string, keyValuePairs ...any)
}

InfoLogger matches log/slog.Info(), but allows one to use another logger using an adaptor.

Jump to

Keyboard shortcuts

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