handler

package
v0.1.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package handler holds the admin operations of a mock server, and the units of the admin API that serve them over HTTP. An operation, a method of Operations, works on the store the mock server serves its mocks from, or on a capability of the server, such as its mock files, and knows nothing of HTTP. Its unit is an http.Handler that reads what the operation takes from a request, and answers what it returns.

Index

Constants

This section is empty.

Variables

View Source
var OpenAPIDocument []byte

OpenAPIDocument is the OpenAPI document of the admin API, in YAML.

Functions

func AddMock

func AddMock(ops *Operations) http.Handler

AddMock adds the mock of the request body, a mock file in JSON or YAML, and answers its state: POST /mocks. A mock with an id in use is refused, and closed.

func Authenticate

func Authenticate(c Credentials, open []string, next http.Handler) http.Handler

Authenticate returns a handler that passes to next the requests with the credentials c asks for, and those of open, patterns of a method and a path such as "GET /livez", which match a request of that method, or HEAD for GET, and that exact path. It answers every other request 401, with the challenges of Basic, which a browser shows its sign-in prompt for, and of Bearer when c has a token. Credentials are compared in constant time.

func ClearRequests

func ClearRequests(ops *Operations) http.Handler

ClearRequests removes every request of the journal: DELETE /requests.

func Closing

func Closing() http.Handler

Closing answers a request that comes as the admin API closes: no operation starts then.

func CrossOriginDenied

func CrossOriginDenied() http.Handler

CrossOriginDenied answers a browser's cross-site request that would change the server, or query its journal, which http.CrossOriginProtection refused.

func Docs

func Docs(version string) http.Handler

Docs answers the page that documents the admin API from its OpenAPI document: GET /docs. The page loads Scalar at version, or at the version vlatte pins when it is empty. Only the pinned version is checked against the hash of its file: the hash of another isn't known. version goes into the page as it is: the caller checks it is a version.

func GetMock

func GetMock(ops *Operations) http.Handler

GetMock answers the mock of the path's id as a mock file describes it, so it can be sent back: GET /mocks/{id}.

func GetRequest

func GetRequest(ops *Operations) http.Handler

GetRequest answers the request of the path's id: GET /requests/{id}.

func Health

func Health(ops *Operations) http.Handler

Health answers that the admin API serves, and what it serves: the kind of the mock server, such as http, and the URL it serves its mocks at. GET /health.

func Home

func Home() http.Handler

Home answers the homepage of the admin API: GET /. It shows the state of the mock server, and boxes for what the server can't do say so.

func ListMocks

func ListMocks(ops *Operations) http.Handler

ListMocks answers the mocks of the server, enabled or not, in the order they match: GET /mocks.

func ListRequests

func ListRequests(ops *Operations) http.Handler

ListRequests answers the newest requests the server served: GET /requests. The limit and before parameters page through them.

func ListScenarios

func ListScenarios(ops *Operations) http.Handler

ListScenarios answers every scenario, in the order of their names, with its state, the states its mocks name and the moves they make: GET /scenarios.

func Live

func Live(ops *Operations, anonymous bool) http.Handler

Live answers that the admin API serves, as GET /health does: GET /livez. It checks nothing else, so a store that is down doesn't get the server restarted. With anonymous, it answers the status alone: anyone may ask it, as the probe sends no credentials.

func MCPHandler

func MCPHandler(s *mcp.Server) http.Handler

MCPHandler serves s over Streamable HTTP: POST /mcp. It keeps no sessions, so a client needs none, and answers in JSON. A request through a local address must name a local host, against DNS rebinding.

func MockSchema

func MockSchema(ops *Operations) http.Handler

MockSchema answers the JSON Schema of the server's mock files, in JSON or YAML: GET /schema.

func NewMCP

func NewMCP(ops *Operations) *mcp.Server

NewMCP returns the MCP server of ops: a tool per operation the mock server can do, named after it in snake_case, such as add_mock for Operations.AddMock. A tool's result is the operation's, in JSON, as its route answers it, and the error of a tool whose operation fails is the operation's problem document.

func NotSupported

func NotSupported(what string) http.Handler

NotSupported answers that the mock server can't do what a route does, such as "record".

func OpenAPI

func OpenAPI() http.Handler

OpenAPI answers the OpenAPI document of the admin API, in JSON or YAML: GET /openapi.

func QueryRequests

func QueryRequests(ops *Operations) http.Handler

QueryRequests answers the requests the query of the body selects, and their count: QUERY /requests. A request part, which the server's protocol makes a pattern of, narrows them as a mock matches. An empty body selects them all.

func Ready

func Ready(ops *Operations, anonymous bool) http.Handler

Ready answers that the mock store can serve its mocks, as GET /health does, or 503 when it can't: GET /readyz. With anonymous, it answers the status alone, and a 503 that doesn't tell why, which it logs.

func RecorderPage

func RecorderPage() http.Handler

RecorderPage answers the page that records a service: GET /recorder. On a server that can't record, it says so.

func RecordingStatus

func RecordingStatus(ops *Operations) http.Handler

RecordingStatus answers the state of the recording: GET /recording.

func ReloadMocks

func ReloadMocks(ops *Operations) http.Handler

ReloadMocks loads the mock files of the server again: POST /mocks/reload. When a file has problems, the server serves what it served before.

func RemoveAllMocks

func RemoveAllMocks(ops *Operations) http.Handler

RemoveAllMocks removes every mock, of files and code too, and closes them: DELETE /mocks.

func RemoveMock

func RemoveMock(ops *Operations) http.Handler

RemoveMock removes the mock of the path's id, and closes it: DELETE /mocks/{id}.

func ReplaceMock

func ReplaceMock(ops *Operations) http.Handler

ReplaceMock swaps the mock of the path's id for the mock of the request body, in one step, so a request finds one or the other, and answers its state: PUT /mocks/{id}. The body's id must be the path's. The replaced mock is closed.

func Reset

func Reset(ops *Operations) http.Handler

Reset removes the mocks the admin API added, loads the mocks of the server's sources again, its mock files and its persistent store, starts every scenario over, and clears the journal: POST /reset. Mocks added in code stay as they are. A server without mock files, scenarios, or a journal, skips them. The sources load first: when they fail to, nothing changes. The mocks of a persistent store come back from it, as it holds them: reset never deletes what it holds.

func ResetScenario

func ResetScenario(ops *Operations) http.Handler

ResetScenario moves the scenario of the path's name back to where it started: DELETE /scenarios/{name}. The query parameter key, even empty, resets the instance of that key only.

func ResetScenarios

func ResetScenarios(ops *Operations) http.Handler

ResetScenarios moves every scenario back to where it started: DELETE /scenarios.

func Routing

func Routing(mux *http.ServeMux) http.Handler

Routing answers, as problem documents, the requests mux has no route for: a path it doesn't have, or a method its path doesn't take, with the Allow header mux sets.

func SaveMocks

func SaveMocks(ops *Operations) http.Handler

SaveMocks writes the mocks the admin API added as mock files, and serves them from the files from then on, so they outlive the server: POST /mocks/save. A mock that can't be described as a mock file writes no file at all.

func ScenarioBoardPage

func ScenarioBoardPage() http.Handler

ScenarioBoardPage answers the page that shows and moves scenarios: GET /scenario-board. On a server that keeps no scenarios, it says so.

func ServeMCP

func ServeMCP(ctx context.Context, s *mcp.Server, in io.Reader, out io.Writer) error

ServeMCP serves s over in and out, newline-delimited JSON-RPC, as a client that starts the server as a process talks to it, until in ends or ctx is done.

func SetScenario

func SetScenario(ops *Operations) http.Handler

SetScenario moves the scenario of the path's name to the state of the request body, and answers it: PUT /scenarios/{name}. The query parameter key moves the instance of that key. The mocks that require that state match next. Names ignore case: Checkout is checkout.

func StartRecording

func StartRecording(ops *Operations) http.Handler

StartRecording starts a recording with the settings of the request body, those of the record section of the server's settings, and answers its state: POST /recording.

func Started

func Started(ops *Operations, anonymous bool) http.Handler

Started answers that the mock server started, as GET /livez does: GET /startupz. The admin API serves only once the mock server loaded its mocks, so until then the probe isn't answered.

func StopRecording

func StopRecording(ops *Operations) http.Handler

StopRecording stops the recording, waits until it wrote what it took, and answers what it wrote, which the server then serves: DELETE /recording. What it couldn't record, or serve, is in the answer's errors: the recording stopped all the same.

func UpdateMock

func UpdateMock(ops *Operations) http.Handler

UpdateMock changes the state of the mock of the path's id, and answers it: PATCH /mocks/{id}. A disabled mock matches no request, until enabled again. The mock is stored again with its new state, which a persistent store keeps: when the store refuses it, the mock keeps the state it had.

func ValidateMock

func ValidateMock(ops *Operations) http.Handler

ValidateMock builds the mock of the request body, as POST /mocks would, and answers its state without adding it: POST /mocks/validate. A mock with an id in use is a conflict, as it would be for POST /mocks.

Types

type Credentials

type Credentials struct {
	// Username and Password are the credentials of Basic. Empty, Basic takes only the token.
	Username string
	Password string

	// Token is the bearer token: in an Authorization: Bearer header, or as the password of Basic, with any username,
	// as a browser sends it. Empty asks for none.
	Token string
}

Credentials are what the admin API asks every request for, but those of its probes. The zero value asks for none.

func (Credentials) Required

func (c Credentials) Required() bool

Required reports whether c asks for credentials.

type HealthStatus

type HealthStatus struct {
	Status string `json:"status"`
	Kind   string `json:"kind,omitempty"`
	URL    string `json:"url,omitempty"`
}

HealthStatus is the answer of Operations.Health: GET /health.

type MockList

type MockList struct {
	Mocks []MockSummary `json:"mocks"`
}

MockList is the answer of Operations.ListMocks: GET /mocks.

type MockSummary

type MockSummary struct {
	ID       string `json:"id"`
	Name     string `json:"name,omitempty"`
	Priority int    `json:"priority"`
	Enabled  bool   `json:"enabled"`
	Hits     int64  `json:"hits"`
	Origin   string `json:"origin,omitempty"`
}

MockSummary is what the admin API tells of a mock besides its description: its state.

type Operations

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

Operations are the admin operations of a mock server, apart from how a request reaches them: each route of the admin API runs one. An operation that needs a capability the server lacks, such as Operations.ReloadMocks on a server without mock files, returns a not_supported problem, as its route answers 501. Bodies are documents, in JSON or YAML, as the routes take them. Problem gives the problem document of an error.

func NewOperations

func NewOperations(caps adminapi.Capabilities) *Operations

NewOperations returns the admin operations of the mock server of caps, which has its Mocks.

func (*Operations) AddMock

func (o *Operations) AddMock(ctx context.Context, doc []byte, format string) (MockSummary, error)

AddMock adds the mock of doc, a mock file in format, and returns its state. A mock with an id in use is refused, and closed. It needs a server that makes mocks from documents.

func (*Operations) Builds

func (o *Operations) Builds() bool

Builds reports whether the server builds mocks from documents, for Operations.AddMock, Operations.ValidateMock and Operations.ReplaceMock.

func (*Operations) ClearRequests

func (o *Operations) ClearRequests() error

ClearRequests removes every request of the journal. It needs a server that keeps a journal.

func (*Operations) GetMock

func (o *Operations) GetMock(ctx context.Context, id string) (descriptor.Descriptor, error)

GetMock returns the mock of id as a mock file describes it, so it can be sent back. A mock server whose mocks can't describe themselves returns a not_supported problem.

func (*Operations) GetRequest

func (o *Operations) GetRequest(id string) (*journal.Entry, error)

GetRequest returns the request of id. It needs a server that keeps a journal.

func (*Operations) HasFiles

func (o *Operations) HasFiles() bool

HasFiles reports whether the server serves mock files, for Operations.ReloadMocks and Operations.SaveMocks.

func (*Operations) HasJournal

func (o *Operations) HasJournal() bool

HasJournal reports whether the server keeps a journal of requests, for Operations.ListRequests and its siblings.

func (*Operations) HasMockSchema

func (o *Operations) HasMockSchema() bool

HasMockSchema reports whether the server describes its mock files with a JSON Schema, for Operations.MockSchema.

func (*Operations) HasScenarios

func (o *Operations) HasScenarios() bool

HasScenarios reports whether the server keeps scenarios, for Operations.ListScenarios and its siblings.

func (*Operations) Health

func (o *Operations) Health() HealthStatus

Health returns that the admin API serves, and what it serves: the kind of the mock server, such as http, and the URL it serves its mocks at.

func (*Operations) ListMocks

func (o *Operations) ListMocks(ctx context.Context) (MockList, error)

ListMocks returns the mocks of the server, enabled or not, in the order they match.

func (*Operations) ListRequests

func (o *Operations) ListRequests(ctx context.Context, limit int, before uint64) (RequestList, error)

ListRequests returns the newest requests the server served: a page of limit of them, of the requests before before, the next of a page, or the newest for 0. A limit of 0 returns their count only; one outside 0 to 1000 is an invalid_parameter problem. It needs a server that keeps a journal.

func (*Operations) ListScenarios

func (o *Operations) ListScenarios(ctx context.Context) (ScenarioList, error)

ListScenarios returns every scenario, in the order of their names: those the server's mocks name, and those set without a mock. It needs a server that keeps scenarios.

func (*Operations) MockSchema

func (o *Operations) MockSchema() ([]byte, error)

MockSchema returns the JSON Schema of the server's mock files, a JSON document, so a client writes mocks the server takes. It needs a server that describes its mock files.

func (*Operations) QueryRequests

func (o *Operations) QueryRequests(ctx context.Context, doc []byte, format string) (RequestList, error)

QueryRequests returns the requests the query of doc, a document in format, selects, and their count. A request part, which the server's protocol makes a pattern of, narrows them as a mock matches. An empty document selects them all. It needs a server that keeps a journal.

func (*Operations) Ready

func (o *Operations) Ready(ctx context.Context) error

Ready returns the error of the mock store when it can't serve its mocks, such as when the database behind it is down, as a problem of status 503.

func (*Operations) RecordingStatus

func (o *Operations) RecordingStatus() (RecordingState, error)

RecordingStatus returns the state of the recording. It needs a server that records.

func (*Operations) Records

func (o *Operations) Records() bool

Records reports whether the server records, for Operations.StartRecording and its siblings.

func (*Operations) ReloadMocks

func (o *Operations) ReloadMocks() error

ReloadMocks loads the mock files of the server again. When a file has problems, the server serves what it served before. It needs a server with mock files.

func (*Operations) RemoveAllMocks

func (o *Operations) RemoveAllMocks(ctx context.Context) error

RemoveAllMocks removes every mock, of files and code too, and closes them.

func (*Operations) RemoveMock

func (o *Operations) RemoveMock(ctx context.Context, id string) error

RemoveMock removes the mock of id, and closes it.

func (*Operations) ReplaceMock

func (o *Operations) ReplaceMock(ctx context.Context, id string, doc []byte, format string) (MockSummary, error)

ReplaceMock swaps the mock of id for the mock of doc, a mock file in format, in one step, so a request finds one or the other, and returns its state. The document's id must be id. The replaced mock is closed. It needs a server that makes mocks from documents.

func (*Operations) Reset

func (o *Operations) Reset(ctx context.Context) error

Reset removes the mocks the admin API added, loads the mocks of the server's sources again, its mock files and its persistent store, starts every scenario over, and clears the journal. Mocks added in code stay as they are. A server without mock files, scenarios, or a journal, skips them. The sources load first: when they fail to, nothing changes. The mocks of a persistent store come back from it, as it holds them: reset never deletes what it holds.

func (*Operations) ResetScenario

func (o *Operations) ResetScenario(name string, in ...matchscenario.Instance) error

ResetScenario moves the scenario name back to where it started: every instance of it, or only the one in picks, such as matchscenario.Key("t1"). Names ignore case: Checkout is checkout. It needs a server that keeps scenarios.

func (*Operations) ResetScenarios

func (o *Operations) ResetScenarios() error

ResetScenarios moves every scenario back to where it started. It needs a server that keeps scenarios.

func (*Operations) SaveMocks

func (o *Operations) SaveMocks(ctx context.Context, doc []byte, format string) (SavedFiles, error)

SaveMocks writes the mocks the admin API added as mock files, with the settings of doc, a document in format, and serves them from the files from then on, so they outlive the server. It returns the files' paths. A mock that can't be described as a mock file writes no file at all. It needs a server with mock files.

func (*Operations) SetScenario

func (o *Operations) SetScenario(
	ctx context.Context,
	name string,
	doc []byte,
	format string,
	in ...matchscenario.Instance,
) (Scenario, error)

SetScenario moves the scenario name to the state of doc, a document in format, such as {"state": "paid"}, and returns it: its shared instance, or the one in picks, such as matchscenario.Key("t1"). The mocks that require that state match next. Names ignore case: Checkout is checkout. A state none of the scenario's mocks names is an unknown_state problem. It needs a server that keeps scenarios.

func (*Operations) StartRecording

func (o *Operations) StartRecording(doc []byte, format string) (RecordingState, error)

StartRecording starts a recording with the settings of doc, a document in format with the keys of the record section of the server's settings, and returns its state. It needs a server that records.

func (*Operations) StopRecording

func (o *Operations) StopRecording(ctx context.Context) (RecordingResult, error)

StopRecording stops the recording, waits until it wrote what it took, and returns what it wrote, which the server then serves. What it couldn't record, or serve, is in the result's errors: the recording stopped all the same. It needs a server that records.

func (*Operations) UpdateMock

func (o *Operations) UpdateMock(ctx context.Context, id string, doc []byte, format string) (MockSummary, error)

UpdateMock changes the state of the mock of id to the one of doc, a document in format, such as {"enabled": false}, and returns it. A disabled mock matches no request, until enabled again. The mock is stored again with its new state, which a persistent store keeps: when the store refuses it, the mock keeps the state it had.

func (*Operations) ValidateMock

func (o *Operations) ValidateMock(ctx context.Context, doc []byte, format string) (MockSummary, error)

ValidateMock builds the mock of doc, a mock file in format, as Operations.AddMock would, and returns its state without adding it. A mock with an id in use is a conflict, as it would be for Operations.AddMock. It needs a server that makes mocks from documents.

type ProblemDocument

type ProblemDocument struct {
	Status   int           `json:"status"`
	Title    string        `json:"title"`
	Code     string        `json:"code"`
	Detail   string        `json:"detail"`
	Instance string        `json:"instance"`
	Problems []ProblemItem `json:"problems,omitempty"`
}

ProblemDocument is an RFC 9457 problem document, as the admin API answers an error. Its type is about:blank, so its title is the status's phrase, and code tells problems apart.

func Problem

func Problem(err error, instance string) ProblemDocument

Problem returns the problem document of err, an error of an operation, about instance, what the operation was asked for, such as the path of a request. An error the caller can't fix, such as a store that failed, is an internal one, of status 500, but for a body over its limit.

type ProblemItem

type ProblemItem struct {
	Code    string `json:"code"`
	Origin  string `json:"origin,omitempty"`
	Key     string `json:"key,omitempty"`
	Value   string `json:"value,omitempty"`
	Message string `json:"message"`
	Hint    string `json:"hint,omitempty"`
}

ProblemItem is one problem of a document: a mock, a body or a mock file.

type RecordedMock

type RecordedMock struct {
	ID        string   `json:"id"`
	Name      string   `json:"name,omitempty"`
	File      string   `json:"file"`
	BodyFiles []string `json:"body_files,omitempty"`
	Responses int      `json:"responses"`
}

RecordedMock is a mock file a recording wrote.

type RecordingResult

type RecordingResult struct {
	Status     RecordingState `json:"status"`
	Recordings []RecordedMock `json:"recordings"`
	Errors     []string       `json:"errors,omitempty"`
}

RecordingResult is what a recording wrote, and what it couldn't.

type RecordingState

type RecordingState struct {
	Active  bool  `json:"active"`
	Calls   int64 `json:"calls"`
	Mocks   int64 `json:"mocks"`
	Dropped int64 `json:"dropped"`
	Failed  int64 `json:"failed"`
}

RecordingState counts the calls of a recording.

type RequestList

type RequestList struct {
	Count    int              `json:"count"`
	Requests []*journal.Entry `json:"requests"`
	Next     uint64           `json:"next,omitzero"`
}

RequestList is the answer of Operations.ListRequests and Operations.QueryRequests, GET and QUERY /requests: count is how many requests the query selects, whatever page requests holds, and next, the before of the next page, when there is one.

type SavedFiles

type SavedFiles struct {
	Files []string `json:"files"`
}

SavedFiles is the answer of Operations.SaveMocks: POST /mocks/save.

type Scenario

type Scenario struct {
	Name        string               `json:"name"`
	State       string               `json:"state"`
	Instances   []ScenarioInstance   `json:"instances"`
	States      []ScenarioState      `json:"states"`
	Transitions []ScenarioTransition `json:"transitions"`
}

Scenario is a scenario: where its shared instance and its keyed ones are, the states its mocks name, and the moves they make.

type ScenarioInstance

type ScenarioInstance struct {
	Key   string `json:"key"`
	State string `json:"state"`
}

ScenarioInstance is the instance of a scenario of one key, which the mocks with a scenario key move for each key of their requests.

type ScenarioList

type ScenarioList struct {
	Scenarios []Scenario `json:"scenarios"`
}

ScenarioList is the answer of Operations.ListScenarios: GET /scenarios.

type ScenarioState

type ScenarioState struct {
	Name      string `json:"name"`
	Reachable bool   `json:"reachable"`
}

ScenarioState is a state a mock of a scenario names. An unreachable one is a state no path of mock moves leads to from started: requests get there only after the scenario is set to it or to another such state.

type ScenarioTransition

type ScenarioTransition struct {
	From   string `json:"from,omitempty"`
	To     string `json:"to"`
	MockID string `json:"mock_id"`
}

ScenarioTransition is the move a mock makes when it is picked to answer: from a state, or any when From is empty, to another.

Jump to

Keyboard shortcuts

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