server

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EnvS2ServerConfig         = "S2_SERVER_CONFIG"
	EnvS2ServerListen         = "S2_SERVER_LISTEN"
	EnvS2ServerConsoleListen  = "S2_SERVER_CONSOLE_LISTEN"
	EnvS2ServerHealthPath     = "S2_SERVER_HEALTH_PATH"
	EnvS2ServerType           = "S2_SERVER_TYPE"
	EnvS2ServerRoot           = "S2_SERVER_ROOT"
	EnvS2ServerMaxUploadSize  = "S2_SERVER_MAX_UPLOAD_SIZE"
	EnvS2ServerMaxPreviewSize = "S2_SERVER_MAX_PREVIEW_SIZE"
	EnvS2ServerUser           = "S2_SERVER_USER"
	EnvS2ServerPassword       = "S2_SERVER_PASSWORD" // #nosec G101 -- env var name, not a credential
	EnvS2ServerBuckets        = "S2_SERVER_BUCKETS"
)
View Source
const (
	DefaultMaxUploadSize      = 5 << 30  // 5 GiB — default for osfs/s3 backends.
	DefaultMemfsMaxUploadSize = 16 << 20 // 16 MiB — conservative default for the in-memory backend.
	DefaultMaxPreviewSize     = 10 << 20 // 10 MiB
)

Variables

View Source
var DefaultRoot = "data"

DefaultRoot is the default storage root path used by DefaultConfig when the user does not supply one via -root, -f, or S2_SERVER_ROOT.

It is intentionally a var (not a const) so that binaries can be built with a different default via linker flags, matching the same idiom used for version injection:

go build -ldflags "-X github.com/mojatter/s2/server.DefaultRoot=/var/lib/s2" ./cmd/s2-server

This lets the stock "go install" binary default to a relative "data" directory (so a new user can run s2-server in any directory and immediately see where data lands) while the Docker image is built with /var/lib/s2 baked in.

View Source
var ErrReservedBucketName = errors.New("bucket name is reserved")

ErrReservedBucketName is returned by Buckets.Create when the requested name collides with a path reserved on the S3 listener — currently the first segment of cfg.HealthPath.

View Source
var StaticFS embed.FS

Functions

func FilterKeep

func FilterKeep(objs []s2.Object) []s2.Object

FilterKeep removes .keep marker files from a list of objects.

func PreviewType added in v0.4.2

func PreviewType(ext string) string

PreviewType returns the preview category for the given file extension: "image", "video", "audio", "pdf", "text", or "" (unsupported).

func RegisterConsoleHandleFunc added in v0.4.0

func RegisterConsoleHandleFunc(pattern string, handler HandlerFunc)

RegisterConsoleHandleFunc registers a handler that will be served by ConsoleHandler(). Patterns use Go 1.22 ServeMux syntax.

func RegisterS3HandleFunc added in v0.4.0

func RegisterS3HandleFunc(pattern string, handler HandlerFunc)

RegisterS3HandleFunc registers a handler that will be served by S3Handler(). Patterns use Go 1.22 ServeMux syntax.

func RegisterTemplate

func RegisterTemplate(name string)

func Run

func Run(args []string) error

Types

type Buckets

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

func (*Buckets) Create

func (bs *Buckets) Create(ctx context.Context, name string) error

func (*Buckets) CreateFolder

func (bs *Buckets) CreateFolder(ctx context.Context, bucket, key string) error

func (*Buckets) CreatedAt

func (bs *Buckets) CreatedAt(ctx context.Context, name string) time.Time

CreatedAt returns the creation time of a bucket by reading the .keep marker file. If the marker is missing, the current time is returned as a fallback.

func (*Buckets) Delete

func (bs *Buckets) Delete(ctx context.Context, name string) error

func (*Buckets) Exists

func (bs *Buckets) Exists(name string) (bool, error)

Exists reports whether a bucket directory exists under the storage root. It is implemented as a single Stat against the bucket path rather than a directory listing of the storage root, so it stays O(1) regardless of how many buckets exist — and, more importantly, regardless of how many objects each bucket holds. Every S3 request runs this on the hot path through Buckets.Get.

Note: Buckets is tied to the fs-family Storage backends (osfs, memfs), which expose a real directory hierarchy. Pairing it with the s3 backend would need a different implementation because S3 has no "directory" primitive; s3 is intended for library-style use against a single bucket, not as a multi-bucket server backend.

func (*Buckets) Get

func (bs *Buckets) Get(ctx context.Context, name string) (s2.Storage, error)

func (*Buckets) Names

func (bs *Buckets) Names() ([]string, error)

type Config

type Config struct {
	s2.Config
	// Listen is the address the S3-compatible API listens on.
	Listen string `json:"listen"`
	// ConsoleListen is the address the Web Console listens on. The
	// console runs on a dedicated listener so the S3 API can own the
	// root path without any prefix. Set to an empty string to disable
	// the console entirely.
	ConsoleListen string `json:"console_listen"`
	// HealthPath is the path the health check endpoint is mounted at on
	// the S3 listener. Its first path segment is reserved and cannot be
	// used as a bucket name (Buckets.Create returns ErrReservedBucketName
	// for that name). The default "/healthz" reserves the bucket name
	// "healthz". Must start with "/" and have at least one segment after
	// it. Set to an empty string to disable the health endpoint entirely.
	HealthPath string `json:"health_path"`
	// MaxUploadSize is the maximum upload size in bytes. When 0, a backend-specific
	// default is used (see EffectiveMaxUploadSize): 5 GiB for osfs/s3, 16 MiB for
	// memfs. The conservative memfs default protects the host from accidental
	// OOM when a large upload targets the in-memory backend; set an explicit
	// value here to override.
	MaxUploadSize int64 `json:"max_upload_size"`
	// MaxPreviewSize is the maximum file size for text preview in bytes (0 = default 10MB).
	MaxPreviewSize int64 `json:"max_preview_size"`
	// User is the username for authentication (Basic Auth for Web Console, Access Key ID for S3 API).
	// When empty, authentication is disabled.
	User string `json:"user"`
	// Password is the password for authentication (Basic Auth password for Web Console, Secret Access Key for S3 API).
	Password string `json:"password"`
	// Buckets is a list of bucket names to create on startup if they don't already exist.
	Buckets []string `json:"buckets"`
}

Config is a configuration for the server.

func DefaultConfig

func DefaultConfig() *Config

func (*Config) EffectiveMaxUploadSize added in v0.2.0

func (cfg *Config) EffectiveMaxUploadSize() int64

EffectiveMaxUploadSize returns the upload size limit to enforce for this configuration. When MaxUploadSize is explicitly set (> 0) it is returned as-is; otherwise a backend-specific default is chosen so that switching Type to memfs does not silently inherit the 5 GiB default.

func (*Config) LoadEnv

func (cfg *Config) LoadEnv() error

func (*Config) LoadFile

func (cfg *Config) LoadFile(filename string) error

func (*Config) Validate added in v0.4.0

func (cfg *Config) Validate() error

Validate checks the configuration for obvious mistakes that would otherwise surface as confusing runtime errors. It is called by NewServer; callers that build a Config by hand can invoke it themselves before passing it in.

type ErrBucketNotFound

type ErrBucketNotFound struct {
	Name string
}

ErrBucketNotFound is returned when a bucket does not exist.

func (*ErrBucketNotFound) Error

func (e *ErrBucketNotFound) Error() string

type Flags

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

Flags holds the parsed command-line arguments for s2-server. Pointer-typed fields distinguish "explicitly set" from "left at default"; only explicitly set flags override values loaded from file/env.

type HandlerFunc

type HandlerFunc func(srv *Server, w http.ResponseWriter, r *http.Request)

type Server

type Server struct {
	Config    *Config
	Template  *template.Template
	Buckets   *Buckets
	StartedAt time.Time // server start time, used as epoch for upload ID generation
}

Server is a web server that provides a Web Console and S3-compatible API for S2.

func NewServer

func NewServer(ctx context.Context, cfg *Config) (*Server, error)

NewServer creates a new server with the specified configuration.

func (*Server) ConsoleHandler added in v0.4.0

func (s *Server) ConsoleHandler() http.Handler

ConsoleHandler builds an HTTP handler that serves the Web Console. Returns nil when no console routes have been registered, which lets the caller decide whether to start a second listener at all.

func (*Server) S3Handler added in v0.4.0

func (s *Server) S3Handler() http.Handler

S3Handler builds an HTTP handler that serves the S3-compatible API. It includes routes registered via RegisterS3HandleFunc and, when cfg.HealthPath is non-empty, a health endpoint at that path.

func (*Server) Start

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

Start starts the S3 API listener and, when cfg.ConsoleListen is set and there are console routes registered, the Web Console listener. Both are shut down gracefully when ctx is cancelled or either listener dies.

Directories

Path Synopsis
handlers

Jump to

Keyboard shortcuts

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