Files
job-search/internal/cli/serve/command.go
T
bwilliams a279405cae Added the HTTP server and serve command, with proxy, CSRF, TLS and security header config; wsserve is now ws serve, alongside a new ws dial
The serve command runs internal/server: the API under /api (health, and
the CSRF token endpoint) and the WebSocket hub under /ws, over HTTP or TLS,
with an optional HTTP to HTTPS redirect, the PROXY protocol from trusted
sources and a graceful shutdown that closes WebSockets first. Its middleware
covers the client IP behind trusted proxies, request IDs, request logging,
panic recovery, global and API rate limits, Host and body size checks,
security response headers, compression, CSRF protection (cross-origin
checks and signed double-submit tokens) and JSON-only API bodies. Middleware
that logs takes a WithLogger option.

New server config sections: proxy, csrf, tls, headers and frontend (not
used yet), plus max_header_bytes, max_body_bytes, global and API rate limits
and HTTP read, write and idle timeouts. Every setting documents what 0 or
empty means, and internal/config/README.md is reorganised by section.
server.timeouts.read_header must be greater than 0, and a header or idle
timeout of 0 means no limit rather than the read timeout.

WebSocket upgrades are protected by the Origin check: the server's own
origin, or one of csrf.cross_origin_protection.trusted_origins, which the
hub now takes with WithTrustedOrigins.

wsserve becomes "ws serve". "ws dial" opens a WebSocket on /ws to test it:
--ping sends a ping and waits for the pong, --message sends messages and
prints the replies, --origin tests the Origin check, and with neither
--ping nor --message each line of stdin is sent until Ctrl+C.
2026-10-15 17:47:40 +01:00

106 lines
2.8 KiB
Go

package serve
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"github.com/spf13/cobra"
"git.avsdev.uk/Go/job-search/internal/cli"
"git.avsdev.uk/Go/job-search/internal/server"
)
// NewCommand returns the serve command, which serves the frontend, the REST
// API and the WebSocket endpoint.
func NewCommand(opts *cli.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "serve",
Short: "Serve the frontend (/), REST API (/api) and WebSocket (/ws)",
Long: `Serve the embedded Vite frontend, the REST API under /api and the
WebSocket endpoint under /ws.`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
slog.Debug("command persistent pre-run", "command", "serve")
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
slog.Debug("command persistent post-run", "command", "serve")
},
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
slog.Debug("command run", "command", "serve")
addrOverride, _ := cmd.Flags().GetString("listen")
hostOverride, _ := cmd.Flags().GetString("host")
portOverride, _ := cmd.Flags().GetInt("port")
foreground, _ := cmd.Flags().GetBool("foreground")
if addrOverride != "" {
listenParts := strings.Split(addrOverride, ":")
if len(listenParts) != 2 {
return errors.New(
"--listen should be in the format of 127.0.0.1:9393",
)
}
port, err := strconv.Atoi(listenParts[1])
if err != nil {
return fmt.Errorf("failed to parse --listen port: %w", err)
}
hostOverride = listenParts[0]
portOverride = port
}
conf, err := opts.RunSetup(cmd, true, foreground)
if err != nil {
return fmt.Errorf("load configuration: %w", err)
}
if portOverride != 0 {
conf.Server.Port = portOverride
}
if hostOverride != "" {
conf.Server.Host = hostOverride
}
// ctx is cancelled on the first SIGINT (Ctrl+C) or SIGTERM.
ctx, stop := signal.NotifyContext(
context.Background(), os.Interrupt, syscall.SIGTERM,
)
defer stop()
// After the first signal, restore default signal handling so a second
// Ctrl+C force-kills the process if graceful shutdown hangs.
go func() {
<-ctx.Done()
stop()
}()
appServer, err := server.New(&conf.Server)
if err != nil {
return err
}
return appServer.Run(ctx)
},
}
flags := cmd.Flags()
flags.String(
"listen", "", "listen address (default from config, 127.0.0.1:9393)",
)
flags.String(
"host", "", "listen address (default from config, 127.0.0.1)",
)
flags.Int("port", 0, "listen address (default from config, 9393)")
flags.Bool("foreground", false, "run in the foreground")
cmd.MarkFlagsMutuallyExclusive("listen", "host")
cmd.MarkFlagsMutuallyExclusive("listen", "port")
return cmd
}