api

package
v2.1.93 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const ContextHeaderName = "X-Cxs-Context"

ContextHeaderName is the header name for passing context replacements via HTTP requests. The value should be base64-encoded JSON.

View Source
const DefaultServiceConfigURL = "/.config"
View Source
const (
	// RootServiceName is the name used in URLs for services with empty name.
	// Services with empty name are registered as "" but accessed via "/.root" in the UI.
	// The dot prefix makes it a reserved name to avoid conflicts with actual service names.
	RootServiceName = ".root"
)

Variables

This section is empty.

Functions

func ComparePathMethod

func ComparePathMethod(path1, method1, path2, method2 string) bool

ComparePathMethod compares two path/method pairs for sorting. Returns true if (path1, method1) should come before (path2, method2). Order: path (alphabetically), then method (GET, POST, others alphabetically).

func ContextReplacementsMiddleware

func ContextReplacementsMiddleware(next http.Handler) http.Handler

ContextReplacementsMiddleware extracts the X-Cxs-Context header and stores the decoded context data on the request's Go context.

func CreateHealthRoutes

func CreateHealthRoutes(router *Router) error

func CreateHistoryRoutes added in v2.1.76

func CreateHistoryRoutes(router *Router) error

CreateHistoryRoutes adds history routes to the router.

func CreateHomeRoutes

func CreateHomeRoutes(router *Router) error

CreateHomeRoutes creates routes for home.

func CreateServiceConfigRoutes added in v2.1.84

func CreateServiceConfigRoutes(router *Router) error

CreateServiceConfigRoutes adds service config routes to the router.

func CreateServiceRoutes

func CreateServiceRoutes(router *Router) error

CreateServiceRoutes adds service routes to the router.

func ExtractContextFromRequest

func ExtractContextFromRequest(r *http.Request) map[string]any

ExtractContextFromRequest reads and decodes the X-Cxs-Context header from an HTTP request. Returns nil if the header is absent or cannot be decoded.

func NormalizeServiceName

func NormalizeServiceName(specPath string) string

NormalizeServiceName extracts a valid service name from a spec file path. It takes the base filename (without extension) and converts it to snake_case, ensuring it's a valid Go package/service identifier.

Examples:

  • "petstore.yaml" -> "petstore"
  • "IP Push Notification_sandbox.json" -> "ip_push_notification_sandbox"
  • "FaSta_-_Station_Facilities_Status-2.1.359.yaml" -> "fa_sta_station_facilities_status_2_1_359"

func SendHTML

func SendHTML(w http.ResponseWriter, statusCode int, data []byte)

SendHTML is a helper function to send HTML responses.

func UnmarshalResponseInto

func UnmarshalResponseInto[T any](data []byte, contentType string, dest *T) error

UnmarshalResponseInto unmarshals response data into the provided destination. Content type handling:

  • JSON types (application/json, +json variants) → JSON unmarshal
  • Everything else → assigns directly ([]byte or string)

func UserContextFromGoContext

func UserContextFromGoContext(ctx context.Context) map[string]any

UserContextFromGoContext retrieves user-provided context replacements from a Go context.

Types

type BufferedWriter

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

BufferedWriter is a writer that captures the response. Used to capture the template execution result.

func NewBufferedResponseWriter

func NewBufferedResponseWriter() *BufferedWriter

NewBufferedResponseWriter creates a new buffered writer.

func (*BufferedWriter) Header

func (bw *BufferedWriter) Header() http.Header

Header returns the header.

func (*BufferedWriter) Write

func (bw *BufferedWriter) Write(p []byte) (int, error)

Write writes the data to the buffer.

func (*BufferedWriter) WriteHeader

func (bw *BufferedWriter) WriteHeader(statusCode int)

WriteHeader writes the status code.

type GenerateRequest

type GenerateRequest struct {
	Path    string         `json:"path"`
	Method  string         `json:"method"`
	Context map[string]any `json:"context"`
}

GenerateRequest is a struct that represents a request to generate a resource.

type GenerateResponse

type GenerateResponse struct {
}

type Handler

type Handler interface {
	Routes() RouteDescriptions
	RegisterRoutes(router chi.Router)
	Generate(w http.ResponseWriter, r *http.Request)
}

Handler defines a minimal interface for request handlers.

type HandlerOption

type HandlerOption func(*handlerOptions)

HandlerOption configures service registration behavior.

func WithMiddleware

func WithMiddleware(mw []func(*middleware.Params) func(http.Handler) http.Handler) HandlerOption

WithMiddleware prepends middleware before the built-in middleware chain.

type HistoryHandler added in v2.1.76

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

HistoryHandler handles history routes.

type HistoryListResponse added in v2.1.76

type HistoryListResponse struct {
	Items []*db.HistoryEntry `json:"items"`
}

HistoryListResponse is the response for history list endpoint.

type HistorySummary added in v2.1.82

type HistorySummary struct {
	ID        string              `json:"id"`
	Resource  string              `json:"resource"`
	Request   *db.HistoryRequest  `json:"request,omitempty"`
	Response  *db.HistoryResponse `json:"response,omitempty"`
	CreatedAt time.Time           `json:"createdAt"`
}

HistorySummary is a slim version of HistoryEntry for list responses (no bodies).

type HistorySummaryListResponse added in v2.1.82

type HistorySummaryListResponse struct {
	Items []*HistorySummary `json:"items"`
}

HistorySummaryListResponse is the response for history list endpoint.

type JSONResponse

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

JSONResponse is a response builder for JSON responses.

func NewJSONResponse

func NewJSONResponse(w http.ResponseWriter) *JSONResponse

NewJSONResponse creates a new JSONResponse instance.

func (*JSONResponse) Send

func (r *JSONResponse) Send(data any)

Send sends the data as JSON to the client.

func (*JSONResponse) WithHeader

func (r *JSONResponse) WithHeader(key string, value string) *JSONResponse

WithHeader adds a header to the response.

func (*JSONResponse) WithStatusCode

func (r *JSONResponse) WithStatusCode(code int) *JSONResponse

WithStatusCode sets the status code of the response.

type ResourceResponse

type ResourceResponse struct {
	Method      string `json:"method"`
	Path        string `json:"path"`
	Extension   string `json:"extension"`
	ContentType string `json:"contentType"`
	Content     string `json:"content"`
}

type RouteDescription

type RouteDescription struct {
	ID          string `json:"id"`
	Method      string `json:"method"`
	Path        string `json:"path"`
	ContentType string `json:"contentType"`
}

RouteDescription describes a route for the UI Application. Path is relative to the service prefix.

type RouteDescriptions

type RouteDescriptions []*RouteDescription

RouteDescriptions is a slice of RouteDescription. Allows to add custom methods.

func (RouteDescriptions) Sort

func (rs RouteDescriptions) Sort()

Sort sorts the routes by path and method. The order is: GET, POST, other methods (alphabetically)

type RouteType

type RouteType string
const (
	RouteTypeOpenAPI RouteType = "openapi"
	RouteTypeStatic  RouteType = "static"
)

type Router

type Router struct {
	chi.Router
	// contains filtered or unexported fields
}

Router is the central HTTP router for all services

func NewRouter

func NewRouter(options ...RouterOption) *Router

NewRouter creates a new central router with default middleware

func (*Router) Config

func (r *Router) Config() *config.AppConfig

Config returns the app configuration

func (*Router) GetContexts

func (r *Router) GetContexts() []map[string]map[string]any

GetContexts returns the list of contexts

func (*Router) GetDB

func (r *Router) GetDB(serviceName string) db.DB

GetDB returns the database for a specific service. Returns nil if the service is not registered.

func (*Router) GetServices

func (r *Router) GetServices() map[string]*ServiceItem

func (*Router) RegisterHTTPHandler

func (r *Router) RegisterHTTPHandler(
	cfg *config.ServiceConfig,
	handlerFactory func(db.DB) Handler,
	opts ...HandlerOption,
)

RegisterHTTPHandler registers a Handler as a service. The handlerFactory receives the service DB and returns the handler. The service will be registered at the route "/{cfg.Name}".

func (*Router) RegisterService

func (r *Router) RegisterService(
	cfg *config.ServiceConfig,
	handler Handler,
	opts ...HandlerOption,
)

RegisterService registers a service with the router. The service config must have a Name field set. The service will be registered at the route "/{cfg.Name}".

type RouterOption

type RouterOption func(*Router)

func WithConfigOption

func WithConfigOption(cfg *config.AppConfig) RouterOption

type SavedResourceResponse

type SavedResourceResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	ID      int    `json:"id"`
}

type ServiceConfigHandler added in v2.1.84

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

ServiceConfigHandler handles service configuration routes.

type ServiceDescription

type ServiceDescription struct {
	Method    string
	Path      string
	Ext       string
	IsOpenAPI bool
}

ServiceDescription is a struct created from the service payload to facilitate file path composition.

type ServiceEmbedded

type ServiceEmbedded struct {
	Name string `json:"name"`
}

type ServiceHandler

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

ServiceHandler handles service routes.

type ServiceItem

type ServiceItem struct {
	Name    string                `json:"name"`
	Handler Handler               `json:"-"`
	Config  *config.ServiceConfig `json:"-"`
}

ServiceItem represents a service with its handler. Service can hold multiple OpenAPI specs.

type ServiceItemResponse

type ServiceItemResponse struct {
	Name           string `json:"name"`
	ResourceNumber int    `json:"resourceNumber"`
}

type ServiceListResponse

type ServiceListResponse struct {
	Items []*ServiceItemResponse `json:"items"`
}

type ServiceParams

type ServiceParams struct {
	// AppConfig is the application-wide configuration.
	// Contains BaseURL, InternalURL, and Extra map for custom values.
	AppConfig *config.AppConfig

	// ServiceConfig is the service-specific configuration.
	ServiceConfig *config.ServiceConfig

	// DB is the database connection for this service.
	DB db.DB
}

ServiceParams provides access to application and service configuration along with the database connection. This struct is passed to user services to allow access to configuration without coupling to framework internals.

Example usage in service.go:

func newService(params *api.ServiceParams) *service {
    baseURL := params.AppConfig.BaseURL
    extra := params.AppConfig.Extra["myKey"]
    return &service{params: params}
}

For custom configuration, you can:

  1. Use Extra map in app.yml for simple key-value config
  2. Embed and load your own config files in newService

Example app.yml with Extra:

baseURL: https://api.example.com
extra:
  myApiKey: "secret"
  maxRetries: 3

type ServicePayload

type ServicePayload struct {
	IsOpenAPI   bool   `json:"isOpenApi"`
	Method      string `json:"method"`
	Path        string `json:"path"`
	Response    []byte `json:"response"`
	ContentType string `json:"contentType"`
	URL         string `json:"url"`
}

ServicePayload is a struct that represents a new service payload.

type ServiceResourcesResponse

type ServiceResourcesResponse struct {
	Endpoints RouteDescriptions `json:"endpoints"`
}

type SimpleResponse

type SimpleResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

SimpleResponse is a simple response type to indicate the success of an operation.

type StaticResponse

type StaticResponse struct {
	ContentType string
	Content     string
}

StaticResponse represents a static response for static handlers.

Jump to

Keyboard shortcuts

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