Files
job-search/internal/util/bytesize.go
T
bwilliams c9f42b62ad Added websocket hub for handling websocket clients, with a wsserve command
which runs a plain TCP server for receiving websocket hub clients, with
server config, CSRF and rate limit middleware.

- internal/websocket: Hub pushing messages to WebSocket clients (ServeHTTP,
  example.com/ws upgrade with optional CSRF check) and plain TCP clients (ServeTCP,
  newline-delimited JSON envelopes); ping/pong keepalive, per-client message
  rate limit, slow consumer handling, graceful Shutdown, debug logging of
  messages sent and received
- internal/websocket/tcpserver: standalone TCP server for a hub, with accept
  back-off, a per-IP connection limit (server.websocket.connection_limit) and
  graceful shutdown
- internal/cli/wsserve: `wsserve` command running the TCP server, with
  --listen/--host/--port overrides
- internal/middleware: keyed token bucket rate limiter, real client IP from
  trusted proxies
- internal/httpx: RFC 9457 problem responses, request IDs in context
- internal/config: server section (host, port, shutdown timeout, rate limiter
  idle TTL, websocket); util.ByteSize settings (e.g. "32KiB"); lists of
  sections as single keys; empty lists stored as nil; isExplicitlySet for
  printLoadedConfig; JobSearchConfigSource renamed to JSCSourcesSource;
  TestSections checks every section's methods
- internal/util: ByteSize, parsed and formatted with go-humanize
2026-10-14 15:55:25 +01:00

54 lines
1.4 KiB
Go

package util
import (
"fmt"
"math"
"strconv"
"github.com/dustin/go-humanize"
)
// ByteSize is a size in bytes, configured as a string such as "32KiB", "1MB"
// or "1.5 GB" (see ParseByteSize). KB, MB, ... are powers of 1000 and KiB,
// MiB, ... powers of 1024; a bare number is bytes.
type ByteSize int64
// byteUnits are the units String may use, largest first.
var byteUnits = []struct {
name string
size int64
}{
{"EiB", humanize.EiByte}, {"EB", humanize.EByte},
{"PiB", humanize.PiByte}, {"PB", humanize.PByte},
{"TiB", humanize.TiByte}, {"TB", humanize.TByte},
{"GiB", humanize.GiByte}, {"GB", humanize.GByte},
{"MiB", humanize.MiByte}, {"MB", humanize.MByte},
{"KiB", humanize.KiByte}, {"KB", humanize.KByte},
}
// ParseByteSize parses a size such as "32KiB", "1 MB" or "4096". Unit names
// are case-insensitive.
func ParseByteSize(s string) (ByteSize, error) {
n, err := humanize.ParseBytes(s)
if err != nil {
return 0, err
}
if n > math.MaxInt64 {
return 0, fmt.Errorf("byte size %q is too large", s)
}
return ByteSize(n), nil
}
// String formats b exactly, in the largest unit that divides it (e.g. "32KiB",
// "1MB"), or in bytes ("1500B"), so it parses back to the same value.
func (b ByteSize) String() string {
if b != 0 {
for _, u := range byteUnits {
if int64(b)%u.size == 0 {
return strconv.FormatInt(int64(b)/u.size, 10) + u.name
}
}
}
return strconv.FormatInt(int64(b), 10) + "B"
}