rest

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: Apache-2.0 Imports: 28 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// DefaultReadHeaderTimeout bounds how long a client may take to send its
	// request headers. This is the slowloris guard, and unlike WriteTimeout it
	// is safe for streaming endpoints because it stops applying once the
	// headers are in.
	DefaultReadHeaderTimeout = 10 * time.Second
	// DefaultIdleTimeout closes keep-alive connections that go silent.
	DefaultIdleTimeout = 120 * time.Second
	// DefaultMaxConcurrentStreams caps in-flight HTTP/2 streams per connection.
	// A single connection multiplexing unbounded streams is how one client
	// exhausts server concurrency.
	DefaultMaxConcurrentStreams = 250
)
View Source
const DefaultRevisionQueueDepth = 64

DefaultRevisionQueueDepth bounds how many submitted revisions may await publication per session. It is the backpressure point: revision submission is client-driven, so without a bound a fast typist's keystrokes become unbounded server-side work.

View Source
const DefaultStreamHeartbeat = 15 * time.Second

DefaultStreamHeartbeat is how often an idle subscriber is pinged. Proxies and load balancers commonly drop a connection that has been silent for 30-60s, and a preview session is idle whenever the author stops typing.

View Source
const DefaultStreamRetry = 2 * time.Second

DefaultStreamRetry is the reconnect delay advertised to SSE clients.

Variables

View Source
var (
	ErrPreviewDocumentEngineRequired = errors.New("rest: preview document engine is required")
	ErrPreviewCompilerFactoryNeeded  = errors.New("rest: preview compiler factory is required")
)
View Source
var ErrServerHandlerRequired = errors.New("rest: server handler is required")

ErrServerHandlerRequired reports a server built without a handler.

View Source
var ErrStreamingUnsupported = errors.New("rest: streaming unsupported by this ResponseWriter")

ErrStreamingUnsupported reports a ResponseWriter that cannot flush, so server-sent events cannot be delivered over it.

Functions

func NewServer

func NewServer(options ServerOptions) (*http.Server, error)

NewServer builds an http.Server that speaks HTTP/2 over both TLS and cleartext, with timeouts chosen so that streaming endpoints survive.

Serve it with ListenAndServeTLS when TLSConfig is set, ListenAndServe otherwise.

func RegisterPDFGenerationRoutes

func RegisterPDFGenerationRoutes(r chi.Router, api *PDFGenerationAPI)

RegisterPDFGenerationRoutes registers all PDF generation routes with the main router

func RegisterPDFGenerationRoutesWithDefaults

func RegisterPDFGenerationRoutesWithDefaults(r chi.Router)

RegisterPDFGenerationRoutesWithDefaults registers PDF generation routes with default configuration

func RegisterPreviewRoutes

func RegisterPreviewRoutes(router chi.Router, api *PreviewAPI)

RegisterPreviewRoutes mounts the browser transport at /api/v1/preview.

func RegisterStructConverterRoutes

func RegisterStructConverterRoutes(r chi.Router, api *StructConverterAPI)

RegisterStructConverterRoutes registers all struct converter routes with the main router

func RegisterStructConverterRoutesWithDefaults

func RegisterStructConverterRoutesWithDefaults(r chi.Router)

RegisterStructConverterRoutesWithDefaults registers struct converter routes with default configuration

Types

type AsyncPDFGenerationResponse

type AsyncPDFGenerationResponse struct {
	Success   bool   `json:"success"`
	RequestID string `json:"request_id"`
	Message   string `json:"message,omitempty"`
	StatusURL string `json:"status_url"`
	WatchMode bool   `json:"watch_mode,omitempty"` // Indicates if watch mode is active
}

AsyncPDFGenerationResponse represents the response for async PDF generation

type ConversionOptions

type ConversionOptions struct {
	TagName        string `json:"tag_name,omitempty"`
	DefaultFlatten bool   `json:"default_flatten,omitempty"`
	OmitEmpty      bool   `json:"omit_empty,omitempty"`
	TimeFormat     string `json:"time_format,omitempty"`
	DurationFormat string `json:"duration_format,omitempty"`
	SliceSeparator string `json:"slice_separator,omitempty"`
}

ConversionOptions represents conversion options

type ConvertStructRequest

type ConvertStructRequest struct {
	Data     interface{}            `json:"data"`
	Options  *ConversionOptions     `json:"options,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

ConvertStructRequest represents a request to convert a struct

type ConvertStructResponse

type ConvertStructResponse struct {
	Variables map[string]interface{} `json:"variables"`
	Metadata  map[string]interface{} `json:"metadata"`
	Success   bool                   `json:"success"`
	Message   string                 `json:"message,omitempty"`
}

ConvertStructResponse represents the response from struct conversion

type ConverterConfigResponse

type ConverterConfigResponse struct {
	TagName         string   `json:"tag_name"`
	DefaultFlatten  bool     `json:"default_flatten"`
	OmitEmpty       bool     `json:"omit_empty"`
	TimeFormat      string   `json:"time_format"`
	DurationFormat  string   `json:"duration_format"`
	SliceSeparator  string   `json:"slice_separator"`
	RegisteredTypes []string `json:"registered_types"`
	ConverterCount  int      `json:"converter_count"`
}

ConverterConfigResponse represents the current converter configuration

type ConverterInfo

type ConverterInfo struct {
	Type        string `json:"type"`
	CanConvert  bool   `json:"can_convert"`
	Description string `json:"description,omitempty"`
}

ConverterInfo represents information about a registered converter

type ConvertersListResponse

type ConvertersListResponse struct {
	Converters []ConverterInfo `json:"converters"`
	Count      int             `json:"count"`
}

ConvertersListResponse represents the list of registered converters

type EnginesResponse

type EnginesResponse struct {
	Engines []string `json:"engines"`
	Default string   `json:"default"`
}

EnginesResponse represents supported LaTeX engines

type EventSink

type EventSink interface {
	// Send delivers one event. A returned error ends the subscription.
	Send(ctx context.Context, event PreviewEvent) error
	// Heartbeat signals liveness on an idle stream. Implementations for which
	// the protocol already keeps itself alive may return nil without writing.
	Heartbeat(ctx context.Context) error
	// Close releases the subscriber, reporting why the stream ended.
	Close(ctx context.Context, err error) error
}

EventSink is one subscriber's wire format. It is the seam that keeps the event feed independent of the transport carrying it: SSE and WebSocket are two implementations, and a third costs no change to the feed.

The set of transports is open, so this is an interface rather than a switch over a transport enum.

type FormatsResponse

type FormatsResponse struct {
	Formats []string `json:"formats"`
	Default string   `json:"default"`
}

FormatsResponse represents supported output formats

type GeneratedFile

type GeneratedFile struct {
	Type        string `json:"type"` // pdf, png, jpeg, svg
	Size        int64  `json:"size"`
	DownloadURL string `json:"download_url"`
	ExpiresAt   string `json:"expires_at,omitempty"`
}

GeneratedFile represents a generated file

type GenerationStatusResponse

type GenerationStatusResponse struct {
	RequestID string          `json:"request_id"`
	Status    string          `json:"status"`             // pending, processing, completed, failed
	Progress  int             `json:"progress,omitempty"` // 0-100
	Message   string          `json:"message,omitempty"`
	Files     []GeneratedFile `json:"files,omitempty"`
	Error     string          `json:"error,omitempty"`
}

GenerationStatusResponse represents the status of an async generation

type HealthResponse

type HealthResponse struct {
	Status    string `json:"status"`
	Timestamp string `json:"timestamp"`
	Version   string `json:"version"`
}

HealthResponse represents the health check response

type PDFGenerationAPI

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

PDFGenerationAPI provides REST endpoints for PDF generation functionality

func NewPDFGenerationAPI

func NewPDFGenerationAPI(cfg *config.Config) *PDFGenerationAPI

NewPDFGenerationAPI creates a new PDFGenerationAPI instance

func (*PDFGenerationAPI) DownloadFile

func (api *PDFGenerationAPI) DownloadFile(w http.ResponseWriter, r *http.Request)

DownloadFile downloads a generated file GET /api/v1/pdf/download/{requestId}

func (*PDFGenerationAPI) DownloadFileFormat

func (api *PDFGenerationAPI) DownloadFileFormat(w http.ResponseWriter, r *http.Request)

DownloadFileFormat downloads a generated file in specific format GET /api/v1/pdf/download/{requestId}/{format}

func (*PDFGenerationAPI) GeneratePDF

func (api *PDFGenerationAPI) GeneratePDF(w http.ResponseWriter, r *http.Request)

GeneratePDF generates a PDF synchronously POST /api/v1/pdf/generate

func (*PDFGenerationAPI) GeneratePDFAsync

func (api *PDFGenerationAPI) GeneratePDFAsync(w http.ResponseWriter, r *http.Request)

GeneratePDFAsync generates a PDF asynchronously POST /api/v1/pdf/generate/async

func (*PDFGenerationAPI) GeneratePDFFromStruct

func (api *PDFGenerationAPI) GeneratePDFFromStruct(w http.ResponseWriter, r *http.Request)

GeneratePDFFromStruct generates a PDF from a struct (converts struct to variables automatically) POST /api/v1/pdf/generate/from-struct

func (*PDFGenerationAPI) GetActiveWatchModes

func (api *PDFGenerationAPI) GetActiveWatchModes(w http.ResponseWriter, r *http.Request)

GetActiveWatchModes returns information about active watch modes GET /api/v1/pdf/watch

func (*PDFGenerationAPI) GetGenerationStatus

func (api *PDFGenerationAPI) GetGenerationStatus(w http.ResponseWriter, r *http.Request)

GetGenerationStatus gets the status of an async generation GET /api/v1/pdf/status/{requestId}

func (*PDFGenerationAPI) GetSupportedEngines

func (api *PDFGenerationAPI) GetSupportedEngines(w http.ResponseWriter, r *http.Request)

GetSupportedEngines returns supported LaTeX engines GET /api/v1/pdf/engines

func (*PDFGenerationAPI) GetSupportedFormats

func (api *PDFGenerationAPI) GetSupportedFormats(w http.ResponseWriter, r *http.Request)

GetSupportedFormats returns supported output formats GET /api/v1/pdf/formats

func (*PDFGenerationAPI) GetTemplateVariables

func (api *PDFGenerationAPI) GetTemplateVariables(w http.ResponseWriter, r *http.Request)

GetTemplateVariables extracts variables from a template GET /api/v1/pdf/templates/variables?template_path=...

func (*PDFGenerationAPI) HealthCheck

func (api *PDFGenerationAPI) HealthCheck(w http.ResponseWriter, r *http.Request)

HealthCheck provides a health check endpoint GET /api/v1/pdf/health

func (*PDFGenerationAPI) Routes

func (api *PDFGenerationAPI) Routes() chi.Router

Routes returns the chi router with all PDF generation endpoints

func (*PDFGenerationAPI) StopAllWatchModes

func (api *PDFGenerationAPI) StopAllWatchModes(w http.ResponseWriter, r *http.Request)

StopAllWatchModes stops all active watch modes DELETE /api/v1/pdf/watch

func (*PDFGenerationAPI) StopWatchMode

func (api *PDFGenerationAPI) StopWatchMode(w http.ResponseWriter, r *http.Request)

StopWatchMode stops a specific watch mode DELETE /api/v1/pdf/watch/{watchId}

func (*PDFGenerationAPI) ValidateTemplate

func (api *PDFGenerationAPI) ValidateTemplate(w http.ResponseWriter, r *http.Request)

ValidateTemplate validates a LaTeX template POST /api/v1/pdf/templates/validate

type PDFGenerationOptions

type PDFGenerationOptions struct {
	Engine       string                `json:"engine,omitempty"`        // pdflatex, xelatex, lualatex
	OutputFormat string                `json:"output_format,omitempty"` // pdf, png, jpeg, svg
	Conversion   RESTConversionOptions `json:"conversion,omitempty"`
	Debug        bool                  `json:"debug,omitempty"`
	Cleanup      bool                  `json:"cleanup,omitempty"`
	Timeout      int                   `json:"timeout,omitempty"`     // seconds
	WatchMode    bool                  `json:"watch_mode,omitempty"`  // Enable file watching
	Passes       int                   `json:"passes,omitempty"`      // Number of compilation passes (1-10)
	UseLatexmk   bool                  `json:"use_latexmk,omitempty"` // Whether to use latexmk
}

PDFGenerationOptions represents PDF generation options

type PDFGenerationRequest

type PDFGenerationRequest struct {
	TemplatePath string                 `json:"template_path"`
	Variables    map[string]interface{} `json:"variables"`
	Options      *PDFGenerationOptions  `json:"options,omitempty"`
}

PDFGenerationRequest represents a request to generate a PDF

type PDFGenerationResponse

type PDFGenerationResponse struct {
	Success     bool              `json:"success"`
	RequestID   string            `json:"request_id"`
	Message     string            `json:"message,omitempty"`
	Files       []GeneratedFile   `json:"files,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	DownloadURL string            `json:"download_url,omitempty"`
	WatchMode   bool              `json:"watch_mode,omitempty"` // Indicates if watch mode is active
}

PDFGenerationResponse represents the response from PDF generation

type PDFGenerationStructRequest

type PDFGenerationStructRequest struct {
	TemplatePath string                `json:"template_path"`
	Data         interface{}           `json:"data"` // Struct to convert to variables
	Options      *PDFGenerationOptions `json:"options,omitempty"`
}

PDFGenerationStructRequest represents a request to generate a PDF from a struct

type PDFHealthResponse

type PDFHealthResponse struct {
	Status    string `json:"status"`
	Timestamp string `json:"timestamp"`
	Version   string `json:"version"`
}

PDFHealthResponse represents the health check response for PDF API

type PreviewAPI

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

PreviewAPI owns revisioned preview sessions. Mount Routes at a stable prefix, for example /api/v1/preview.

func NewPreviewAPI

func NewPreviewAPI(options PreviewAPIOptions) (*PreviewAPI, error)

NewPreviewAPI builds the HTTP/SSE adapter without changing legacy PDF routes.

func (*PreviewAPI) Close

func (api *PreviewAPI) Close() error

Close terminates all sessions owned by this transport.

func (*PreviewAPI) Routes

func (api *PreviewAPI) Routes() chi.Router

Routes exposes creation, monotonic revision submission, replayable SSE events, cancellation, and closure.

type PreviewAPIOptions

type PreviewAPIOptions struct {
	Engine          *rootapi.DocumentEngine
	CompilerFactory PreviewCompilerFactory
	SessionOptions  preview.Options
	HistoryLimit    int

	// Heartbeat is how often an idle stream signals liveness. Defaults to
	// DefaultStreamHeartbeat.
	Heartbeat time.Duration
	// RetryHint tells SSE clients how long to wait before reconnecting.
	// Defaults to DefaultStreamRetry.
	RetryHint time.Duration
	// OriginPatterns lists host patterns permitted to open a WebSocket. Empty
	// means same-origin only, which is what a browser preview needs.
	OriginPatterns []string
	// RevisionQueueDepth bounds revisions awaiting publication per session.
	// Defaults to DefaultRevisionQueueDepth.
	RevisionQueueDepth int
}

PreviewAPIOptions configures the browser-facing streaming transports.

type PreviewCompilerFactory

type PreviewCompilerFactory interface {
	NewCompiler() (preview.Compiler, error)
}

PreviewCompilerFactory gives every browser session isolated compiler state.

type PreviewCompilerFactoryFunc

type PreviewCompilerFactoryFunc func() (preview.Compiler, error)

PreviewCompilerFactoryFunc adapts a constructor function.

func (PreviewCompilerFactoryFunc) NewCompiler

func (function PreviewCompilerFactoryFunc) NewCompiler() (preview.Compiler, error)

type PreviewEvent

type PreviewEvent struct {
	ID       uint64          `json:"id"`
	Type     string          `json:"type"`
	Revision uint64          `json:"revision"`
	Result   *preview.Result `json:"result,omitempty"`
	Error    string          `json:"error,omitempty"`
}

PreviewEvent is directly consumable by a reducer: changed pages replace by number, removed pages delete by number, and revisions never decrease.

type PreviewRequest

type PreviewRequest struct {
	Data    interface{}        `json:"data"`
	Options *ConversionOptions `json:"options,omitempty"`
	Limit   int                `json:"limit,omitempty"`
}

PreviewRequest represents a request to preview conversion

type PreviewResponse

type PreviewResponse struct {
	Variables map[string]interface{} `json:"variables"`
	Count     int                    `json:"count"`
	Truncated bool                   `json:"truncated"`
	Message   string                 `json:"message,omitempty"`
}

PreviewResponse represents the response from preview conversion

type RESTConversionOptions

type RESTConversionOptions struct {
	DoConvert bool    `json:"do_convert,omitempty"`
	Format    string  `json:"format,omitempty"`  // png, jpeg, svg
	Quality   int     `json:"quality,omitempty"` // 1-100
	DPI       int     `json:"dpi,omitempty"`     // dots per inch
	Scale     float64 `json:"scale,omitempty"`   // scale factor
}

RESTConversionOptions represents conversion options for images in REST API

type ServerOptions

type ServerOptions struct {
	Addr    string
	Handler http.Handler

	// ReadHeaderTimeout bounds request-header reads. Defaults to
	// DefaultReadHeaderTimeout.
	ReadHeaderTimeout time.Duration
	// IdleTimeout bounds idle keep-alive connections. Defaults to
	// DefaultIdleTimeout.
	IdleTimeout time.Duration
	// WriteTimeout is a deadline on the WHOLE response, so any non-zero value
	// truncates server-sent events and WebSocket streams once it elapses.
	// Zero, the default, is correct for this API; set it only on a server that
	// mounts no streaming route.
	WriteTimeout time.Duration
	// ReadTimeout is likewise a deadline on the whole request body. Zero, the
	// default, keeps WebSocket connections readable for their lifetime.
	ReadTimeout time.Duration

	// MaxConcurrentStreams caps concurrent HTTP/2 streams per connection.
	// Defaults to DefaultMaxConcurrentStreams.
	MaxConcurrentStreams uint32

	// TLSConfig enables HTTPS. When nil the server still speaks HTTP/2 over
	// cleartext (h2c), which is what a TLS-terminating proxy in front of it
	// needs in order to keep using HTTP/2 on the back end.
	TLSConfig *tls.Config
}

ServerOptions configures an HTTP server suited to this API's long-lived streaming endpoints.

type StructConverterAPI

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

StructConverterAPI provides REST endpoints for struct conversion functionality

func NewStructConverterAPI

func NewStructConverterAPI() *StructConverterAPI

NewStructConverterAPI creates a new StructConverterAPI instance

func NewStructConverterAPIWithConverter

func NewStructConverterAPIWithConverter(conv *converter.StructConverter) *StructConverterAPI

NewStructConverterAPIWithConverter creates a new StructConverterAPI with a custom converter

func (*StructConverterAPI) ConvertStruct

func (api *StructConverterAPI) ConvertStruct(w http.ResponseWriter, r *http.Request)

ConvertStruct converts a struct to AutoPDF variables POST /api/v1/struct-converter/convert

func (*StructConverterAPI) ConvertStructFlattened

func (api *StructConverterAPI) ConvertStructFlattened(w http.ResponseWriter, r *http.Request)

ConvertStructFlattened converts a struct to flattened AutoPDF variables POST /api/v1/struct-converter/convert/flattened

func (*StructConverterAPI) ConvertStructForTemplate

func (api *StructConverterAPI) ConvertStructForTemplate(w http.ResponseWriter, r *http.Request)

ConvertStructForTemplate converts a struct optimized for template usage POST /api/v1/struct-converter/convert/template

func (*StructConverterAPI) GetConverterConfig

func (api *StructConverterAPI) GetConverterConfig(w http.ResponseWriter, r *http.Request)

GetConverterConfig returns the current converter configuration GET /api/v1/struct-converter/config

func (*StructConverterAPI) HealthCheck

func (api *StructConverterAPI) HealthCheck(w http.ResponseWriter, r *http.Request)

HealthCheck provides a health check endpoint GET /api/v1/struct-converter/health

func (*StructConverterAPI) ListConverters

func (api *StructConverterAPI) ListConverters(w http.ResponseWriter, r *http.Request)

ListConverters returns the list of registered converters GET /api/v1/struct-converter/converters

func (*StructConverterAPI) PreviewConversion

func (api *StructConverterAPI) PreviewConversion(w http.ResponseWriter, r *http.Request)

PreviewConversion provides a preview of struct conversion with limited output POST /api/v1/struct-converter/preview

func (*StructConverterAPI) RegisterConverter

func (api *StructConverterAPI) RegisterConverter(w http.ResponseWriter, r *http.Request)

RegisterConverter registers a new converter (placeholder - would need custom converter types) POST /api/v1/struct-converter/converters

func (*StructConverterAPI) Routes

func (api *StructConverterAPI) Routes() chi.Router

Routes returns the chi router with all struct converter endpoints

func (*StructConverterAPI) UnregisterConverter

func (api *StructConverterAPI) UnregisterConverter(w http.ResponseWriter, r *http.Request)

UnregisterConverter unregisters a converter DELETE /api/v1/struct-converter/converters/{type}

func (*StructConverterAPI) UpdateConverterConfig

func (api *StructConverterAPI) UpdateConverterConfig(w http.ResponseWriter, r *http.Request)

UpdateConverterConfig updates the converter configuration PUT /api/v1/struct-converter/config

func (*StructConverterAPI) ValidateStruct

func (api *StructConverterAPI) ValidateStruct(w http.ResponseWriter, r *http.Request)

ValidateStruct validates a struct for conversion POST /api/v1/struct-converter/validate

type TemplateValidationRequest

type TemplateValidationRequest struct {
	TemplatePath string `json:"template_path"`
}

TemplateValidationRequest represents a request to validate a template

type TemplateValidationResponse

type TemplateValidationResponse struct {
	Valid    bool     `json:"valid"`
	Errors   []string `json:"errors,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

TemplateValidationResponse represents the response from template validation

type TemplateVariablesResponse

type TemplateVariablesResponse struct {
	Variables []string `json:"variables"`
	Count     int      `json:"count"`
}

TemplateVariablesResponse represents template variables

type ValidationRequest

type ValidationRequest struct {
	Data interface{} `json:"data"`
}

ValidationRequest represents a request to validate a struct

type ValidationResponse

type ValidationResponse struct {
	Valid    bool     `json:"valid"`
	Errors   []string `json:"errors,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

ValidationResponse represents the response from struct validation

Jump to

Keyboard shortcuts

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