mockhttp

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 76 Imported by: 0

Documentation

Overview

Package mockhttp runs HTTP mock servers for tests.

Start a Server, add mocks built with Get, Post and the other builders, and point the code under test at Server.URL:

m := mockhttp.MustNew()
m.MustStart()
defer m.Close()

m.MustMock(mockhttp.Getf("/hello").Reply(mockhttp.OK().PlainText("hello world")))

Use github.com/caffeine-projects/vlatte/match to match headers, query parameters or bodies. Builder.FormField and Builder.FormFile match the fields and files of forms, as net/http parses them, and Reply.Multipart replies with multipart bodies, streamed part by part when parts have delays. Reply.EventStream replies with Server-Sent Events, sent event by event. Mocks can also come from YAML or JSON files; see FromFile and ConfigBuilder.MockFilePatterns.

Settings come from code, then from a .vlatterc.json, .vlatterc.yaml or .vlatterc.yml file and VLATTE_* environment variables, each overriding the one before. ConfigBuilder.ConfigSources picks the sources, and ConfigUsage lists every setting.

Example
package main

import (
	"fmt"
	"io"
	"net/http"

	"github.com/caffeine-projects/vlatte/mockhttp"
)

func main() {
	m := mockhttp.MustNew(mockhttp.Setup().Silent())
	m.MustStart()
	defer m.Close()

	scoped := m.MustMock(mockhttp.Getf("/hello").Reply(mockhttp.OK().PlainText("hello world")))

	res, err := http.Get(m.URL("/hello"))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(body), scoped.Called())
}
Output:
200 hello world true
Example (EventStream)
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/caffeine-projects/vlatte"
	"github.com/caffeine-projects/vlatte/mockhttp"
)

func main() {
	m := mockhttp.MustNew(mockhttp.Setup().Silent())
	m.MustStart()
	defer m.Close()

	// Stream a completion as Server-Sent Events, a JSON chunk at a time, as LLM APIs do.
	m.MustMock(mockhttp.Postf("/v1/completions").
		Reply(mockhttp.OK().EventStream(mockhttp.NewEventStream(
			mockhttp.NewEvent().DataJSON(map[string]string{"text": "Hel"}),
			mockhttp.NewEvent().DataJSON(map[string]string{"text": "lo"}),
			mockhttp.NewEvent().Name("done").Data("[DONE]"),
		).EventDelay(vlatte.Latency(time.Millisecond)))))

	res, err := http.Post(m.URL("/v1/completions"), mockhttp.MIMEApplicationJSON, strings.NewReader(`{"prompt":"hi"}`))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	stream, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.Header.Get(mockhttp.HeaderContentType))
	fmt.Print(string(stream))
}
Output:
text/event-stream
data: {"text":"Hel"}

data: {"text":"lo"}

event: done
data: [DONE]
Example (Multipart)
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"

	"github.com/caffeine-projects/vlatte/match"
	"github.com/caffeine-projects/vlatte/mockhttp"
)

func main() {
	m := mockhttp.MustNew(mockhttp.Setup().Silent())
	m.MustStart()
	defer m.Close()

	// Match an upload by its fields and files, and reply with a multipart body.
	m.MustMock(mockhttp.Postf("/upload").
		FormField("title", match.Equal("Holiday")).
		FormFile("photo", mockhttp.FileWith().Filename(match.HasSuffix(".png"))).
		Reply(mockhttp.Created().Multipart(mockhttp.MultipartMixed(
			mockhttp.NewPart().ContentType("text/plain").BodyText("saved"),
		).Boundary("b"))))

	// A Multipart writes request bodies too.
	contentType, body, err := mockhttp.MultipartForm(
		mockhttp.NewPart().Name("title").BodyText("Holiday"),
		mockhttp.NewPart().Name("photo").Filename("me.png").Body([]byte("PNG")),
	).Encode(nil, nil)
	if err != nil {
		panic(err)
	}

	res, err := http.Post(m.URL("/upload"), contentType, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	reply, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, res.Header.Get(mockhttp.HeaderContentType))
	fmt.Printf("%q\n", reply)
}
Output:
201 multipart/mixed; boundary=b
"--b\r\nContent-Type: text/plain\r\n\r\nsaved\r\n--b--\r\n"

Index

Examples

Constants

View Source
const (
	// DefaultWorkDir is the work directory of a server without a name, and holds a named server's: see Config.WorkDir.
	DefaultWorkDir = "testdata/vlatte"

	// WorkDirVar, at the start of a path, stands for the server's work directory, as in "{workdir}/_mocks".
	WorkDirVar = "{workdir}"
)
View Source
const (
	// DefaultConfigFileName is the base name of the config file looked up by default:
	// .vlatterc.json, .vlatterc.yaml or .vlatterc.yml.
	DefaultConfigFileName = ".vlatterc"
	// EnvPrefix starts the names of the environment variables that configure a server, such as VLATTE_ADDR.
	EnvPrefix = "VLATTE"
)
View Source
const (
	HeaderAccept                          = "Accept"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderContentType                     = "Content-Type"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderAllow                           = "Allow"
	HeaderAuthorization                   = "Authorization"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderVary                            = "Vary"
	HeaderOrigin                          = "Origin"
	HeaderContentLength                   = "Content-Length"
	HeaderConnection                      = "Connection"
	HeaderTrailer                         = "Trailer"
	HeaderLocation                        = "Location"
	HeaderCacheControl                    = "Cache-Control"
	HeaderCookie                          = "Cookie"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderRetryAfter                      = "Retry-After"
	HeaderUpgrade                         = "Upgrade"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderXHTTPMethodOverride             = "X-HTTP-Method-Override"
	HeaderXRealIP                         = "X-Real-Ip"
	HeaderXRequestID                      = "X-Request-Id"
	HeaderXCorrelationID                  = "X-Correlation-Id"
	HeaderXRequestedWith                  = "X-Requested-With"
	HeaderServer                          = "Server"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderIdempotencyKey                  = "Idempotency-Key"
	HeaderETag                            = "Etag"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfMatch                         = "If-Match"
	HeaderExpires                         = "Expires"
	HeaderLink                            = "Link"
	HeaderUserAgent                       = "User-Agent"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderTraceparent                     = "Traceparent"
	HeaderXRateLimitLimit                 = "X-Ratelimit-Limit"
	HeaderXRateLimitRemaining             = "X-Ratelimit-Remaining"
	HeaderXRateLimitReset                 = "X-Ratelimit-Reset"

	// HeaderVlatteError says why vlatte, and not a mock, answered a request: one of the vlatte.Failure* values.
	HeaderVlatteError = vlatte.HeaderFailure
)

Header names, for building and matching mocks.

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationCharsetUTF8           = MIMEApplicationJSON + "; " + _charsetUTF8
	MIMEApplicationProblemJSON           = "application/problem+json"
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + _charsetUTF8
	MIMETextMarkdown                     = "text/markdown"
	MIMETextMarkdownCharsetUTF8          = MIMETextMarkdown + "; " + _charsetUTF8
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + _charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + _charsetUTF8
	MIMEFormURLEncoded                   = "application/x-www-form-urlencoded"
	MIMEFormURLEncodedCharsetUTF8        = MIMEFormURLEncoded + "; " + _charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + _charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + _charsetUTF8
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEMultipartForm                    = "multipart/form-data"
	MIMETextEventStream                  = "text/event-stream"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types, for building and matching mocks.

View Source
const Kind vlatte.Kind = "http"

Kind identifies HTTP mocks in protocol-neutral code, such as event listeners and callbacks.

View Source
const StatusNoMatch = http.StatusTeapot

StatusNoMatch describes an HTTP response where no Mock was found.

It uses http.StatusTeapot to reduce the chance of using the same expected response from the actual server being mocked. Basically, every request that doesn't match against a Mock, will have a response with http.StatusTeapot. It is also the default status of a failure, such as a reply that fails: see Config.ErrorStatusCode.

Variables

View Source
var (
	// ErrNoExpectations is returned by [Builder.Build] for a mock with no request matcher and no [Builder.Times].
	ErrNoExpectations = errors.New("mock: at least 1 request matcher must be set")

	// ErrNoReplies is returned by [Builder.Build] for a mock with no reply: see [Builder.Reply].
	ErrNoReplies = errors.New("mock: no reply set: use Reply")
)
View Source
var (
	// ConfigMockFilePattern is the default filename glob pattern to search for local mock files, in the server's work
	// directory: the recordings of the default record directory too.
	ConfigMockFilePattern = append([]string{WorkDirVar + "/_mocks/*mock.yaml", WorkDirVar + "/_mocks/*mock.yml"}, recordedMockFiles(_defaultRecordDir)...)
)

Defaults

View Source
var DefaultCORSConfig = CORSConfig{
	AllowedOrigin: "*",
	AllowedMethods: strings.Join([]string{
		http.MethodGet,
		http.MethodPost,
		http.MethodHead,
		http.MethodPut,
		http.MethodDelete,
		http.MethodPatch,
	}, ","),
	AllowedHeaders:    "",
	AllowCredentials:  false,
	ExposeHeaders:     "",
	MaxAge:            0,
	SuccessStatusCode: http.StatusNoContent,
}

DefaultCORSConfig is the CORS configuration that ConfigBuilder.CORS and the cors configuration keys start from: any origin, the methods GET, POST, HEAD, PUT, DELETE and PATCH, any header a preflight request asks for, and 204 for preflight requests.

View Source
var DefaultConfigDirectories = []string{".", "testdata"}

DefaultConfigDirectories are the directories searched for the config file, in order.

Functions

func ConfigUsage

func ConfigUsage() string

ConfigUsage describes every server setting: its flag, environment variable, file key, allowed values and default.

func EncodeMock

func EncodeMock(mock *Mock, format string) ([]byte, error)

EncodeMock describes mock in format, json, yaml or yml, as the admin API's GET /mocks/{id} does: what a persistent store of the admin API keeps, such as a document of a database. DecodeMock builds the mock back. Relative body files are named from the working directory. A mock that can't be described fails.

func FromBytes

func FromBytes(data []byte, format string) vlatte.Builder[*Mock, *Server]

FromBytes builds a mock from a JSON or YAML document. format is json, yaml or yml. Like a mock file, the document is data; see FromFile. A relative body_file opens from the working directory. Multiple YAML mock documents are rejected.

func FromFile

func FromFile(path string) vlatte.Builder[*Mock, *Server]

FromFile builds a mock from a JSON or YAML file, chosen by its extension: .json, .yaml or .yml.

The file is data: only the settings that are templates, such as a templated reply body, are compiled, with the template engine of the server. Templates read the server's key-value store, data and URL when a request arrives. A relative body_file opens from the file's directory. When the file has problems, the error is a list of every one, each with its key and a hint. A YAML file must contain one mock; use ConfigBuilder.MockFilePatterns to load multiple mock documents.

func MockFileFormats

func MockFileFormats() []string

MockFileFormats lists the formats of mock files and recordings, as file extensions without the dot.

Types

type AdminAPI

type AdminAPI = *adminapi.API

AdminAPI is a handle to the built-in admin API: a RESTful HTTP server of its own, apart from the mocks, that lists, adds and changes them while the server runs. Make one with github.com/caffeine-projects/vlatte/admin.New. A nil AdminAPI serves none.

type AdminStore

type AdminStore func(app *Server) (vlatte.Store[*Mock], error)

AdminStore makes the persistent store of the mocks the admin API adds, for the server app. The store keeps their descriptions, by ID, such as in files or a database: EncodeMock describes a mock, and DecodeMock builds it back. The mocks of mock files and code never reach it.

func FileStore

func FileStore(dir string) AdminStore

FileStore makes a persistent store of the mocks the admin API adds: a mock file each, <id>.mock.yaml in dir, as EncodeMock describes the mock. Only the store reads them: keep dir out of the mock file patterns, or its mocks would load twice. A relative dir starts at the server's root directory, and WorkDirVar at its work directory, as in "{workdir}/_admin". A file a person adds, edits or removes takes effect on the server's next reload. A mock whose description doesn't load back is refused: its file would fail every later start. A file's mock must have the ID the file's name gives, as the store finds a mock's file by its name: one that doesn't fails the start and the reload.

type Backend

type Backend interface {
	Listen() error
	ListenTLS() error
	Serve() error
	Close() error
	Info() *BackendInfo
}

Backend is the HTTP server that serves a mock server's handler. A mock server starts it in two steps: Listen or ListenTLS binds its address, so Info has its URL, while the server loads its mocks and starts its recording; then Serve answers the connections, those that came meanwhile included. It starts once.

type BackendConfig

type BackendConfig struct {
	App     *Server
	Handler http.Handler
}

BackendConfig bundles the inputs a BackendFactory needs to build the Backend of a Server.

type BackendFactory

type BackendFactory interface {
	NewBackend(config BackendConfig) (Backend, error)
}

BackendFactory builds the Backend of a mock server. The default factory builds it on an httptest.Server.

type BackendInfo

type BackendInfo struct {
	URL string
}

BackendInfo describes a running Backend.

type Builder

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

Builder describes a mock. Build makes a new Mock from it each time, for the given server, and leaves the builder as it was: one builder can be added to many servers, or more than once to one, and changing it after Mock changes only the mocks built afterwards.

Mocks built from one builder share what it holds: its matchers, mappers, callbacks, pipes and delay. Each has its own ID (unless set with ID), hits, count of Times and Once, enabled state, scenario binding and Replier.

func AnyMethod

func AnyMethod() *Builder

AnyMethod creates a new empty Builder.

func Delete

func Delete(m vlatte.Matcher) *Builder

Delete initializes a mock for Delete method.

func Deletef

func Deletef(path string, a ...any) *Builder

Deletef initializes a mock for Delete method.

func Get

func Get(m vlatte.Matcher) *Builder

Get initializes a mock for GET method.

func Getf

func Getf(path string, a ...any) *Builder

Getf initializes a mock for GET method.

func Head(m vlatte.Matcher) *Builder

Head initializes a mock for Head method.

func Headf

func Headf(path string, a ...any) *Builder

Headf initializes a mock for Head method.

func Patch

func Patch(u vlatte.Matcher) *Builder

Patch initializes a mock for Patch method.

func Patchf

func Patchf(path string, a ...any) *Builder

Patchf initializes a mock for Patch method.

func Post

func Post(m vlatte.Matcher) *Builder

Post initializes a mock for Post method.

func Postf

func Postf(path string, a ...any) *Builder

Postf initializes a mock for Post method.

func ProxyAll

func ProxyAll(reply *ProxyReply) *Builder

ProxyAll returns a mock that answers the requests no other mock matches with reply: it matches any method and path, and comes last, at the priority math.MaxInt. It leaves CONNECTs alone, and, on a server that is a forward proxy, the requests in absolute form, which the proxy sends on to the hosts they name. Its description holds the reply under proxy_all, which a mock file loads back as the same mock.

func Put

func Put(m vlatte.Matcher) *Builder

Put inits a mock for Put method.

func Putf

func Putf(path string, a ...any) *Builder

Putf initializes a mock for Put method.

func Request

func Request() *Builder

Request creates a new empty Builder.

func (*Builder) BasicAuth

func (b *Builder) BasicAuth(username, password string) *Builder

BasicAuth matches the credentials of the request's Basic Authorization header, exactly.

func (*Builder) BasicAuthMatches

func (b *Builder) BasicAuthMatches(username, password vlatte.Matcher) *Builder

BasicAuthMatches defines matchers for the username and the password of the request's Basic Authorization header, as http.Request.BasicAuth reads them. Without Basic credentials, both are nil.

func (*Builder) Body

func (b *Builder) Body(matcherList ...vlatte.Matcher) *Builder

Body adds matchers to the HTTP request body. With more than one, the body must match them all, such as matchers of several fields of a JSON body:

m.Body(match.JSONPath("name", match.Equal("test")), match.JSONPath("address.street", match.Contain("nowhere")))

It panics when given no matcher.

func (*Builder) Build

func (b *Builder) Build(app *Server) (*Mock, error)

Build makes a new Mock for app from the builder, and leaves the builder as it was. Used internally by Server.

func (*Builder) Callback

func (b *Builder) Callback(fn vlatte.EventFunc[vlatte.OnComplete]) *Builder

Callback adds fn as an on_complete event of the mock, named callback in the logs, with no listener to register. It runs as the mock's other events and the global ones do: at the same time as them, once the mock replied, and the response waits for it, so a test checks what it did right after the call. fn gets an *OnComplete, read-only as the events run at the same time, and a context that the client leaving doesn't end, and Server.Close does. An error or a panic of fn is logged as a warning, and told by the request's journal entry, unless Close canceled it, and never changes the response. Mock files can't set callbacks, and a mock's description leaves them out.

func (*Builder) ClientIP

func (b *Builder) ClientIP(m vlatte.Matcher) *Builder

ClientIP defines a matcher for the address of the client, as http.Request.RemoteAddr has it, without its port. Behind a proxy it is the proxy's: X-Forwarded-For is a header, which Header matches.

func (*Builder) ContentType

func (b *Builder) ContentType(value string, a ...any) *Builder

ContentType matches the Content-Type of the request, ignoring case. A value without parameters matches the media type alone, whatever parameters the request has, such as the boundary of a multipart form: ContentType("multipart/form-data") matches "multipart/form-data; boundary=x". A value with parameters matches the whole header.

func (*Builder) Cookie

func (b *Builder) Cookie(name string, m vlatte.Matcher) *Builder

Cookie defines a matcher for the value of a cookie, by its name, which keeps its case. It reads the first cookie with that name, as http.Request.Cookie does, and nil when the request has none, which no text matches.

func (*Builder) Delay

func (b *Builder) Delay(d vlatte.Delay) *Builder

Delay chooses the wait before each reply. Nil disables it. An evaluation error prevents the reply.

func (*Builder) Enabled

func (b *Builder) Enabled(enabled bool) *Builder

Enabled sets whether the mocks built afterwards start enabled. All mocks are enabled by default. A mock already built changes through its Scope.

func (*Builder) FormField

func (b *Builder) FormField(name string, m vlatte.Matcher) *Builder

FormField defines a matcher for a field of the body's form, urlencoded or multipart, by its name. It reads the field as http.Request.PostFormValue does: its first value, and never the query.

func (*Builder) FormFieldf

func (b *Builder) FormFieldf(field string, value string, a ...any) *Builder

FormFieldf defines a matcher for a specific form field by its key.

func (*Builder) FormFields

func (b *Builder) FormFields(name string, m vlatte.Matcher) *Builder

FormFields defines a matcher for every value of a field of the body's form: a []string, empty when the form has no such field. Like FormField, it never reads the query.

func (*Builder) FormFile

func (b *Builder) FormFile(name string, p *FilePattern) *Builder

FormFile adds a matcher of the files of a field of a multipart form, by the field's name: some file of the field must match p, or every one when p is Every. A request without such a file, or without a multipart form, doesn't match.

func (*Builder) Header

func (b *Builder) Header(name string, m vlatte.Matcher) *Builder

Header adds a matcher to a specific http.Header key.

func (*Builder) Headerf

func (b *Builder) Headerf(name string, value string, a ...any) *Builder

Headerf adds a matcher to a specific http.Header key.

func (*Builder) Headers

func (b *Builder) Headers(name string, m vlatte.Matcher) *Builder

Headers defines a matcher for every value of a header: a []string in the order the request sent them, empty when the request has no such header. Header reads only the first value. Values a request sends in one line, such as "a, b", are one value.

func (*Builder) Host

func (b *Builder) Host(m vlatte.Matcher) *Builder

Host defines a matcher for the host the request names, without its port, whatever the port: its Host header, or the host of a request in absolute form, as a forward proxy gets, such as "api.local". An IPv6 address comes without brackets. Host names ignore case: compare them with match.EqualIgnoreCase.

func (*Builder) ID

func (b *Builder) ID(id string) *Builder

ID sets the ID of the mock, such as "users-get". Without one, each mock built gets a generated ID. An ID holds only letters, digits, '.', '_', '~' and '-', and a server holds one mock per ID.

func (*Builder) Map

func (b *Builder) Map(mapper Mapper) *Builder

Map adds a Mapper that allows modifying the response after it was built. Multiple mappers can be added. A mapper finds the body in Body: one that streams, such as a proxy's, is read whole for it first.

func (*Builder) Matches

func (b *Builder) Matches(m vlatte.Matcher) *Builder

Matches adds a matcher of the whole request: m gets the *http.Request, as the predicate of RequestMatches does. A mock file's request.custom adds matchers this way, such as custom ones of the server's registry: see ConfigBuilder.Matchers. Unlike a predicate, a matcher that describes itself is described, under request.custom, so the admin API's store keeps it.

func (*Builder) Method

func (b *Builder) Method(methods ...string) *Builder

Method sets the HTTP request methods to match, ignoring case: one, or several, of which the request has one. It panics without a method.

func (*Builder) MethodMatches

func (b *Builder) MethodMatches(m vlatte.Matcher) *Builder

MethodMatches defines a matcher.Matcher for the request method. Useful to set a Mock for multiple HTTP Request methods.

func (*Builder) Name

func (b *Builder) Name(name string) *Builder

Name defines a name for the mock. Useful for debugging.

func (*Builder) OnCompleteEvent

func (b *Builder) OnCompleteEvent(cfg vlatte.EventConfig) *Builder

OnCompleteEvent adds an on-complete event to the mock. It runs once the mock replied, and the response waits for it, unless cfg.AfterResponse is set: see vlatte.EventConfig.AfterResponse.

func (*Builder) Once

func (b *Builder) Once() *Builder

Once sets that each mock built from the builder serves one request.

func (*Builder) PathParam

func (b *Builder) PathParam(name string, m vlatte.Matcher) *Builder

PathParam defines a matcher for a parameter of the path template, by its name: the segment it takes, decoded. With URLPathTemplate("/users/{id}"), PathParam("id", match.Equal("7")) matches /users/7. Build fails when the mock has no path template, or its template has no such parameter.

func (*Builder) Pipe

func (b *Builder) Pipe(pipes ...vlatte.Pipe) *Builder

Pipe adds pipes that the body of each answer of the mock passes through, in order, before it reaches the client: to delay it, send it in parts, change it or cut it. See vlatte.Pipe. Each answer has a flow of its own, so a stage keeps what it counts for that answer only.

Flushes pass through the pipes too, and so does the end of the answer, an empty body included. A stage that aborts the flow, with vlatte.ErrAbort or vlatte.ErrReset, cuts the answer after what it sent: the mock counts the call and runs its callbacks and events, then cuts the connection. ErrReset resets an HTTP/1 connection. A failure, such as a failing reply, is vlatte's answer, and skips the pipes.

func (*Builder) Priority

func (b *Builder) Priority(p int) *Builder

Priority sets the priority of the mock. Mocks with a lower priority are matched first; mocks of equal priority, in the order they were added.

func (*Builder) Queries

func (b *Builder) Queries(name string, m vlatte.Matcher) *Builder

Queries define a matcher.Matcher for query parameters that contains multiple values.

func (*Builder) Query

func (b *Builder) Query(name string, m vlatte.Matcher) *Builder

Query defines a matcher to a specific query.

func (*Builder) Queryf

func (b *Builder) Queryf(name string, value string, a ...any) *Builder

Queryf defines a matcher to a specific query.

func (*Builder) Reply

func (b *Builder) Reply(f ReplierFactory) *Builder

Reply sets what the mock replies with. Build asks f for a new Replier for each mock, so f can serve many mocks. Reply, SequentialReply, RandomReply, ProxyReply, FuncReply and EchoReply are factories, and Shared turns any Replier into one. The mock owns the Replier f makes: when it implements io.Closer, the mock closes it when it leaves the server. A Replier that Shared gives to many mocks is never closed by them.

func (*Builder) RequestMatches

func (b *Builder) RequestMatches(predicate func(r *http.Request) (bool, error)) *Builder

RequestMatches applies the given predicate to the incoming http.Request.

func (*Builder) RequestURI

func (b *Builder) RequestURI(uri string) *Builder

RequestURI matches the path and query of the request exactly, as match.RequestURI does and a mock file's relative url, such as "/items?page=2", does: the same path, and the same parameters, in any order, each with its values in order. It panics when uri isn't a URL.

func (*Builder) ScenarioIs

func (b *Builder) ScenarioIs(scenario string) *Builder

ScenarioIs puts the mock in the given scenario. Without Builder.ScenarioStateIs, it matches in any state of it.

func (*Builder) ScenarioKey

func (b *Builder) ScenarioKey(tmpl string) *Builder

ScenarioKey sets the template of the key of the instance of the mock's scenario a request plays in, such as {{ .Request.Header.Get "X-Test-Id" }}: each key is a scenario of its own, starting in started, so tests that run at once with keys of their own don't move each other's. It renders with the request data of reply templates, with .Provided and .Extra empty, as no mock is picked yet. It renders more than once for a request: as the mock matches, as it takes its turn and to journal the move, so a key reads the request only, never .Scenarios, a random value or the time. A key that renders empty plays in the shared instance, the one of mocks without a key. A template that fails to render fails the request's matching. Read a keyed instance with Server.Scenarios, and move it with Server.SetScenario and matchscenario.Key.

func (*Builder) ScenarioStateIs

func (b *Builder) ScenarioStateIs(requiredState string) *Builder

ScenarioStateIs mark this mock to be served only if the scenario state is equal to the given required state.

func (*Builder) ScenarioStateWillBe

func (b *Builder) ScenarioStateWillBe(newState string) *Builder

ScenarioStateWillBe sets the state the scenario moves to when this mock is picked to answer a request, before it answers: the next request matches in that state. With Builder.ScenarioStateIs, of two requests in that state, only one gets this mock; without it, the mock matches in every state, so every request gets it. The scenario moves even when the mock then fails to answer, as when its client leaves during its delay.

func (*Builder) Scheme

func (b *Builder) Scheme(scheme string) *Builder

Scheme sets the HTTP request scheme to be matched.

func (*Builder) SchemeMatches

func (b *Builder) SchemeMatches(m vlatte.Matcher) *Builder

SchemeMatches sets a matcher.Matcher for the URL scheme part.

func (*Builder) SetSource

func (b *Builder) SetSource(src string) *Builder

SetSource sets the source of the Mock. This could be a filename or any relevant information about the source of the Mock. This is mostly used internally.

func (*Builder) StartScenario

func (b *Builder) StartScenario(name string) *Builder

StartScenario sets that this mock will start a new scenario with the given name.

func (*Builder) Times

func (b *Builder) Times(times int64) *Builder

Times sets how many requests each mock built from the builder serves: 1 or more. Each mock counts its own, so a mock built again, as Remock does, starts from zero. The last call wins.

func (*Builder) URL

func (b *Builder) URL(m vlatte.Matcher) *Builder

URL defines a matcher to be applied to the http.Request url.URL.

func (*Builder) URLFragment

func (b *Builder) URLFragment(m vlatte.Matcher) *Builder

URLFragment defines a matcher to be applied to the URL fragment: the decoded text after a "#" in the request target. An escaped "%23" is part of the path. Go's http.Client doesn't send fragments: a request with URL.Opaque set to the path and fragment, such as "/users#top", does.

func (*Builder) URLFragmentf

func (b *Builder) URLFragmentf(format string, a ...any) *Builder

URLFragmentf sets a Matcher that compares the URL fragment with the given value, as a glob. The expected value will be formatted with the provided format specifier.

func (*Builder) URLPath

func (b *Builder) URLPath(m vlatte.Matcher) *Builder

URLPath defines a matcher to be applied to the url.URL path.

func (*Builder) URLPathTemplate

func (b *Builder) URLPathTemplate(template string) *Builder

URLPathTemplate matches the path with a template, such as /users/{id}/orders/{orderId}: the path has as many segments, each literal one the same once decoded, and a non-empty one for each parameter. A parameter is a whole segment, and %7B writes a literal brace. PathParam matches a parameter, and templates read them as .Request.PathParams. A mock has one path template, which other matchers of the URL or the path add to.

func (*Builder) URLPathf

func (b *Builder) URLPathf(format string, a ...any) *Builder

URLPathf matches the path with a glob, formatted with the format specifier: only "*" is special, it crosses "/", and case counts, so "/users/*" matches "/users/7/orders", and not "/Users/7".

func (*Builder) URLf

func (b *Builder) URLf(format string, a ...any) *Builder

URLf matches the full URL, such as "http://127.0.0.1:8080/items?page=2", with a glob, formatted with the format specifier: only "*" is special, it crosses "/", and case counts.

func (*Builder) UpstreamPipe

func (b *Builder) UpstreamPipe(pipes ...vlatte.Pipe) *Builder

UpstreamPipe adds pipes that what the mock sends on passes through, in order, as its target reads it: the body of the request a proxy reply sends, such as to delay it, send it in parts or cut it. See vlatte.Pipe. Pipes can change its length, so the target gets it chunked. A request without a body has nothing for them.

The server reads the body of a request before it matches a mock, so the client's upload has ended by then: these pipes apply to what the mock sends on, not to how it reads the client. A body the server doesn't read whole, with NoBodyParsing or past MaxBodyParsingLimit, is read from the client as the target reads it, a small piece at a time, so a stage that slows it slows the upload too, once the connection's buffers are full. A mock with wire pipes takes its connection over before it replies, so it reads such a body through these pipes first: they pace the upload, and a proxy's target gets the body as they passed it on, at once. A stage that aborts the flow, with vlatte.ErrAbort or vlatte.ErrReset, fails the call to the target and cuts the client's answer, once the mock counted the call.

func (*Builder) WirePipe

func (b *Builder) WirePipe(pipes ...vlatte.Pipe) *Builder

WirePipe adds pipes that every byte of each answer of the mock passes through, in order, as the client reads it: the status line, the headers, the framing of the body and the body, after the pipes of Pipe. They can send what isn't HTTP: nothing at all, half the headers, garbage after a valid head. See vlatte.Pipe.

The mock answers on its connection, which it takes over, in HTTP/1.x, with Connection: close, so the connection ends with the answer. A request over HTTP/2 can't give its connection over: it gets vlatte's error answer. A stage that aborts the flow, with vlatte.ErrAbort or vlatte.ErrReset, has the connection closed, or reset, without the rest of the answer, once the mock counted the call and ran its callbacks and events. A failure, such as a failing reply, is vlatte's answer, and skips the pipes. A recording leaves the call out.

type CORSConfig

type CORSConfig struct {
	// AllowedOrigin lists the allowed origins, comma-separated. * allows any. Browsers refuse * for requests with
	// credentials, so with AllowCredentials the origin of the request is allowed instead.
	AllowedOrigin    string
	AllowCredentials bool

	// AllowedMethods lists the allowed methods, comma-separated. * allows the method a preflight request asks for.
	AllowedMethods string

	// AllowedHeaders lists the allowed headers, comma-separated. Empty, or *, allows the headers a preflight request
	// asks for.
	AllowedHeaders string

	// ExposeHeaders lists the headers browsers let scripts read, comma-separated. Browsers read * as a header name
	// for requests with credentials.
	ExposeHeaders string

	// MaxAge is how many seconds browsers may cache the answer to a preflight request. -1 sends none.
	MaxAge int

	// SuccessStatusCode is the status of the answer to a preflight request, 204 when 0. Browsers fail a preflight
	// answered with a status other than 2xx.
	SuccessStatusCode int
}

CORSConfig represents the possible options to configure CORS.

func (*CORSConfig) Apply

func (c *CORSConfig) Apply(opts *CORSConfig)

Apply allows CORSConfig to be used as a CORSConfigurer

type CORSConfigBuilder

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

CORSConfigBuilder facilitates building CORS options. It sets only the options it is given: the others keep the values they have, such as the ones of DefaultCORSConfig.

func CORS

func CORS() *CORSConfigBuilder

CORS initializes a CORSConfig builder for a fluent configuration.

func (*CORSConfigBuilder) AllowCredentials

func (b *CORSConfigBuilder) AllowCredentials(allow bool) *CORSConfigBuilder

AllowCredentials sets "Access-Control-Allow-Credentials" misc.Header

func (*CORSConfigBuilder) AllowMethods

func (b *CORSConfigBuilder) AllowMethods(methods ...string) *CORSConfigBuilder

AllowMethods sets the allowed HTTP methods. The header "Access-Control-Allow-Methods" will be used.

func (*CORSConfigBuilder) AllowOrigin

func (b *CORSConfigBuilder) AllowOrigin(origin ...string) *CORSConfigBuilder

AllowOrigin sets the allowed origins.

func (*CORSConfigBuilder) AllowedHeaders

func (b *CORSConfigBuilder) AllowedHeaders(headers ...string) *CORSConfigBuilder

AllowedHeaders sets the allowed headers. It will set the header "Access-Control-Allow-Headers".

func (*CORSConfigBuilder) Apply

func (b *CORSConfigBuilder) Apply(opts *CORSConfig)

Apply sets the options given to the builder on opts.

func (*CORSConfigBuilder) ExposeHeaders

func (b *CORSConfigBuilder) ExposeHeaders(headers ...string) *CORSConfigBuilder

ExposeHeaders sets the header "Access-Control-Expose-Headers".

func (*CORSConfigBuilder) MaxAge

func (b *CORSConfigBuilder) MaxAge(maxAge int) *CORSConfigBuilder

MaxAge sets CORS max age.

func (*CORSConfigBuilder) SuccessStatusCode

func (b *CORSConfigBuilder) SuccessStatusCode(code int) *CORSConfigBuilder

SuccessStatusCode sets a custom status code returned on CORS Options request. If none is specified, the default status code is http.StatusNoContent.

type CORSConfigurer

type CORSConfigurer interface {
	Apply(opts *CORSConfig)
}

CORSConfigurer lets users configure CORS.

type Config

type Config struct {
	// Common fields
	Name                  string
	RootDir               string
	WorkDir               string
	TLSConfig             *tls.Config
	TLSCertificates       []tls.Certificate
	TLSClientCAs          *x509.CertPool
	KV                    vlatte.KV
	Logger                *zerolog.Logger
	LogOutput             io.Writer
	LogVerbosity          vlatte.LogVerbosity
	LogLevel              vlatte.LogLevel
	LogPretty             bool
	LogBodyMaxSize        int64
	Debug                 bool
	Colors                bool
	Listeners             *vlatte.Listener
	GlobalEvents          *vlatte.Events
	TemplateDataProviders []TemplateDataProvider
	DebugFn               DebugFn

	// Matchers builds the matcher lists of mock files, and of the admin API's request queries: the built-in matchers
	// and custom ones. Nil builds the built-in matchers only.
	Matchers *matchbuild.Registry

	// TemplateEngine compiles every template of the server's mocks. Nil uses a vlatte.GoTemplateEngine.
	TemplateEngine vlatte.TemplateEngine

	// TemplateEnv names the environment variables templates may read with env, from the setting template.env. It
	// configures the vlatte.GoTemplateEngine the server makes without a TemplateEngine, so setting both is an error:
	// allow them on that engine with vlatte.WithEnv.
	TemplateEnv []string

	// TemplateKeys are the keys templates sign tokens with, jwt, and publish, jwks, from the setting template.keys:
	// "kid=ALG" generates a key when the server is made, a new one each time, and "kid=ALG:path/to/key.pem" reads one,
	// a relative path starting at RootDir. Like TemplateEnv, it configures the default engine only: add keys to an
	// engine of your own with vlatte.WithSigningKey.
	TemplateKeys []string

	// ConfigSources lists where settings are read from after code, lowest precedence first.
	// Nil reads DefaultConfigSources(nil): the config file, then VLATTE_* environment variables.
	// An empty, non-nil slice reads nothing, so only code and defaults apply.
	ConfigSources []ConfigSource

	// ReadTimeout bounds reading an entire request, headers and body included, on the default backend and
	// intercepted HTTPS connections. Zero or negative leaves it unbounded. It does not limit response writes.
	// It follows [http.Server.ReadTimeout]: for HTTP/2, the body timeout starts after the request headers arrive.
	ReadTimeout time.Duration

	// ReadHeaderTimeout bounds reading HTTP/1.x request headers. Zero uses ReadTimeout; negative disables the bound.
	// It follows [http.Server.ReadHeaderTimeout], which does not impose a per-stream header timeout on HTTP/2.
	ReadHeaderTimeout time.Duration

	// IdleTimeout bounds the wait for the next request on a keep-alive connection, after the response ends.
	// Zero uses ReadTimeout; negative disables the idle bound. It does not limit an active response stream.
	IdleTimeout time.Duration

	Addr                           string
	Listener                       net.Listener // in place of listening on Addr: see ConfigBuilder.Listener
	UseHTTP2                       bool
	RequestWasNotMatchedStatusCode int
	ErrorStatusCode                int
	RequestBodyParsers             []RequestBodyParser
	MaxBodyParsingLimit            int64
	NoBodyParsing                  bool
	NoDebugHeaders                 bool
	NoNearMisses                   bool
	Middlewares                    []func(http.Handler) http.Handler
	CORS                           *CORSConfig
	BackendFactory                 BackendFactory
	HandlerDecorator               func(handler http.Handler) http.Handler
	MockFileSearchPatterns         []string
	Loaders                        []Loader
	Proxy                          *ProxyConfig
	Record                         *RecordConfig
	Admin                          AdminAPI
	AdminStore                     AdminStore
	Journal                        *JournalConfig
	MockFileHandlers               []MockFileHandler
	HeaderNamesToRedact            map[string]struct{}
	UseHTTPS                       bool

	// NoMatchRenderer answers the requests no mock matches. Nil uses [DefaultNoMatchRenderer] in NoMatchFormat.
	NoMatchRenderer NoMatchRenderer

	// NoMatchFormat is the format of the default no-match renderer, from the setting no_match_format. It configures
	// the renderer the server makes without a NoMatchRenderer, so setting both is an error: pass the format to
	// [DefaultNoMatchRenderer].
	NoMatchFormat NoMatchFormat

	// Transport sends what the server sends: the requests of proxy replies, of the recording target, of the forward
	// proxy and of webhooks. Each takes its own transport first, when it has one: ProxyReply.Transport,
	// RecordConfig.Transport, ProxyConfig.Transport or webhook.WithTransport. For upstreams with different needs,
	// give each its own, or pass one that picks a transport by req.URL.Host. It is the caller's: the server never
	// closes it.
	//
	// Nil leaves each to a transport it makes, and closes with the server. Only the transports it makes for proxy
	// replies, the recording target and the forward proxy follow its TLS client certificates and CAs: the one of
	// webhooks has the settings of http.DefaultTransport. A setting that only shapes those, and that a transport of the
	// caller's would ignore, fails instead: a proxy reply's SSLVerify or SkipSSLVerify fails its mock,
	// RecordConfig.SkipSSLVerify fails the recording, and the forward proxy's Via or SSLVerify fails New. The forward
	// proxy's CONNECT tunnels don't go through a transport: with one of the caller's, they dial their host, and else
	// they go through the proxy the transport the server makes picks, Via or the proxy of the environment.
	Transport http.RoundTripper

	// OutboundAllow and OutboundDeny limit the addresses the server connects to, for its proxy replies, the recording
	// target, the forward proxy and its tunnels, and webhooks: an address in OutboundDeny is refused, and so is one
	// outside OutboundAllow when it isn't empty. Deny wins, and either one refuses the unspecified address, 0.0.0.0 or
	// ::, which reaches this host. They check the address after DNS resolution, so a host name that resolves into a
	// refused range is refused, and through a proxy on the way, Via or the proxy of the environment, they check the
	// proxy's. An IPv4 range doesn't hold IPv6 addresses: deny ::1/128 with 127.0.0.0/8. A refused connection fails
	// with [vlatte.ErrOutboundRefused]. Empty, the default, refuses nothing. A transport of the caller's, such as
	// [Config.Transport], dials on its own, and they don't apply.
	OutboundAllow []netip.Prefix
	OutboundDeny  []netip.Prefix
	// contains filtered or unexported fields
}

Config holds the configuration of an HTTP mock Server.

func (*Config) Apply

func (c *Config) Apply(conf *Config) error

Apply implements Option: it sets every field of conf to c's, its zero values included. Setup sets only what its methods set, so its options compose.

func (*Config) Path

func (c *Config) Path(p string) string

Path returns where the file or pattern p of the server is: a leading WorkDirVar is the server's work directory, and a relative path starts at Config.RootDir. Path(WorkDirVar) is the work directory itself.

type ConfigBuilder

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

ConfigBuilder builds the configuration of a Server with a fluent API. Each method sets one setting, and Apply sets only those: the options passed to New compose, so a later one changes only what it sets.

func Setup

func Setup() *ConfigBuilder

Setup initialize a new ConfigBuilder. Entrypoint to start a new custom configuration for HTTP mock servers.

func (*ConfigBuilder) Addr

func (cb *ConfigBuilder) Addr(addr string) *ConfigBuilder

Addr sets a custom address for the mock HTTP server.

func (*ConfigBuilder) Admin

func (cb *ConfigBuilder) Admin(api AdminAPI) *ConfigBuilder

Admin serves the admin API api, such as admin.MustNew(admin.Addr("127.0.0.1:8081")), on an HTTP server of its own. Server.AdminURL returns where it listens.

func (*ConfigBuilder) AdminStore

func (cb *ConfigBuilder) AdminStore(store AdminStore) *ConfigBuilder

AdminStore keeps the mocks the admin API adds in the persistent store store makes, such as FileStore(dir): each change the admin API makes reaches it at once, and the server serves what it holds when it starts and on each Reload, so changes made to it directly take effect too. Without one, those mocks stay in memory, as long as the server runs. It needs an admin API: see Admin.

func (*ConfigBuilder) Apply

func (cb *ConfigBuilder) Apply(conf *Config) error

Apply implements Option: it sets, in order, what the methods of cb set, and leaves the rest of conf as it is.

func (*ConfigBuilder) BackendFactory

func (cb *ConfigBuilder) BackendFactory(factory BackendFactory) *ConfigBuilder

BackendFactory configures a custom BackendFactory used to build the underlying HTTP mock Backend for a Server.

func (*ConfigBuilder) CORS

func (cb *ConfigBuilder) CORS(options ...CORSConfigurer) *ConfigBuilder

CORS configures CORS for the mock server. An answer that sends a CORS header, such as a proxied one, answers CORS by itself: the server's CORS headers aren't sent with it. A Handler reply writes its answer on top of the server's CORS headers: it should Set its CORS headers, or Del the server's.

func (*ConfigBuilder) Colors

func (cb *ConfigBuilder) Colors(v bool) *ConfigBuilder

Colors enable/disable use of ANSI colors in logs.

func (*ConfigBuilder) ConfigSources

func (cb *ConfigBuilder) ConfigSources(sources ...ConfigSource) *ConfigBuilder

ConfigSources sets where settings are read from after code, lowest precedence first, replacing DefaultConfigSources. With no arguments, only code and defaults apply. A Config applied later resets it, since it sets every field.

func (*ConfigBuilder) DebugFn

func (cb *ConfigBuilder) DebugFn(dfn DebugFn) *ConfigBuilder

DebugFn sets the debug function.

func (*ConfigBuilder) ErrorStatusCode

func (cb *ConfigBuilder) ErrorStatusCode(code int) *ConfigBuilder

ErrorStatusCode defines the status code of a response vlatte makes when serving a request fails, such as a reply that fails. It defaults to StatusNoMatch, as no-match does: the VLatte-Error header tells them apart.

func (*ConfigBuilder) EventListeners

func (cb *ConfigBuilder) EventListeners(listeners *vlatte.Listener) *ConfigBuilder

EventListeners sets the registry of named event listeners, such as one several servers share. The listeners registered with OnCompleteListener, before or after, are registered in it too, so none is dropped. Nil gives each server a registry of its own again.

func (*ConfigBuilder) GlobalEvents

func (cb *ConfigBuilder) GlobalEvents(events *vlatte.Events) *ConfigBuilder

GlobalEvents sets the events that run for every mock.

func (*ConfigBuilder) HandlerDecorator

func (cb *ConfigBuilder) HandlerDecorator(fn func(handler http.Handler) http.Handler) *ConfigBuilder

HandlerDecorator configures a custom HTTP handler using the default mock handler. The journal, the logs and the events tell the status it sends, when it answers in place of a mock, such as on a timeout.

func (*ConfigBuilder) IdleTimeout added in v1.1.0

func (cb *ConfigBuilder) IdleTimeout(timeout time.Duration) *ConfigBuilder

IdleTimeout sets the wait for another request on a keep-alive connection: see Config.IdleTimeout.

func (*ConfigBuilder) Journal

func (cb *ConfigBuilder) Journal(dir string) *ConfigBuilder

Journal keeps a journal of the requests the server serves, in dir, across restarts: see JournalConfig. Empty keeps it in a temporary directory, which Close removes, as a test wants: a named one keeps the requests of earlier runs.

func (*ConfigBuilder) KV

func (cb *ConfigBuilder) KV(kv vlatte.KV) *ConfigBuilder

KV sets the key-value store templates read as .KV: {{ .KV.Get "key" }}. Without one, the server keeps the values in memory.

func (*ConfigBuilder) Listener

func (cb *ConfigBuilder) Listener(l net.Listener) *ConfigBuilder

Listener sets an already bound listener for the mock HTTP server to serve instead of listening on Addr. Start takes it: Close, or a Start that fails, closes it, so nothing listens without a server behind it.

func (*ConfigBuilder) Loader

func (cb *ConfigBuilder) Loader(loader Loader) *ConfigBuilder

Loader configures an additional Loader.

func (*ConfigBuilder) LogBodyMaxSize

func (cb *ConfigBuilder) LogBodyMaxSize(size int64) *ConfigBuilder

LogBodyMaxSize sets the max size of the response body to be logged.

func (*ConfigBuilder) LogLevel

func (cb *ConfigBuilder) LogLevel(l vlatte.LogLevel) *ConfigBuilder

LogLevel sets the level of the zerolog.Logger.

func (*ConfigBuilder) LogOutput

func (cb *ConfigBuilder) LogOutput(w io.Writer) *ConfigBuilder

LogOutput sets where the server writes its logs, its debug output and the requests echo replies log, in place of the standard output, such as for a program that keeps the standard output for something else. A Logger writes where it was told to.

func (*ConfigBuilder) LogPretty

func (cb *ConfigBuilder) LogPretty(v bool) *ConfigBuilder

LogPretty enable/disable pretty logging.

func (*ConfigBuilder) LogVerbosity

func (cb *ConfigBuilder) LogVerbosity(l vlatte.LogVerbosity) *ConfigBuilder

LogVerbosity sets the verbosity of informative logs.

func (*ConfigBuilder) Logger

func (cb *ConfigBuilder) Logger(l *zerolog.Logger) *ConfigBuilder

Logger sets a custom zerolog.Logger.

func (*ConfigBuilder) Matchers

func (cb *ConfigBuilder) Matchers(r *matchbuild.Registry) *ConfigBuilder

Matchers sets the registry that builds the matcher lists of the server's mock files, such as one that holds custom matchers: matchbuild.WithMatcher. Servers can share a registry. Nil builds the built-in matchers only.

func (*ConfigBuilder) MaxBodyParsingLimit

func (cb *ConfigBuilder) MaxBodyParsingLimit(n int64) *ConfigBuilder

MaxBodyParsingLimit sets the limit of bytes that request body parsers should read. Zero means no limit.

func (*ConfigBuilder) MockFileHandlers

func (cb *ConfigBuilder) MockFileHandlers(handlers ...MockFileHandler) *ConfigBuilder

MockFileHandlers sets MockFileHandler implementations.

func (*ConfigBuilder) MockFilePatterns

func (cb *ConfigBuilder) MockFilePatterns(patterns ...string) *ConfigBuilder

MockFilePatterns sets custom Glob patterns to load mock from the file system, which may start with WorkDirVar. Defaults to ConfigMockFilePattern.

func (*ConfigBuilder) MockNotFoundStatusCode

func (cb *ConfigBuilder) MockNotFoundStatusCode(code int) *ConfigBuilder

MockNotFoundStatusCode defines the status code to be used when no mock matches with an HTTP request.

func (*ConfigBuilder) Name

func (cb *ConfigBuilder) Name(name string) *ConfigBuilder

Name sets a name to the mock server, which its logs show. It names the folder of its files too, in DefaultWorkDir, unless WorkDir sets another: a path inside it, which doesn't start with _, as vlatte's own folders do.

func (*ConfigBuilder) NoBodyParsing

func (cb *ConfigBuilder) NoBodyParsing() *ConfigBuilder

NoBodyParsing disables request body parsing.

func (*ConfigBuilder) NoDebugHeaders

func (cb *ConfigBuilder) NoDebugHeaders() *ConfigBuilder

NoDebugHeaders turns off the debug headers, such as VLatte-Matched-Mock-Id, that the server adds to its answers. VLatte-Error stays: it tells the server's own answers from a mock's.

func (*ConfigBuilder) NoMatchFormat

func (cb *ConfigBuilder) NoMatchFormat(format NoMatchFormat) *ConfigBuilder

NoMatchFormat sets the format of the answers to requests no mock matches: NoMatchAuto, the default, negotiates it with the request's Accept header. Building a server with both a format other than NoMatchAuto and a NoMatchRenderer fails.

func (*ConfigBuilder) NoMatchRenderer

func (cb *ConfigBuilder) NoMatchRenderer(r NoMatchRenderer) *ConfigBuilder

NoMatchRenderer sets the renderer of the answers to requests no mock matches, in place of DefaultNoMatchRenderer. See NoMatchRenderer for what the server does around it.

Example
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/caffeine-projects/vlatte/match"
	"github.com/caffeine-projects/vlatte/mockhttp"
)

// apiNoMatch answers the requests no mock matched under /api/ in the error shape of the API it stands in for, and
// hands the others to the default renderer.
type apiNoMatch struct {
	fallback mockhttp.NoMatchRenderer
}

func (a apiNoMatch) RenderNoMatch(w http.ResponseWriter, nm *mockhttp.NoMatch) {
	if !strings.HasPrefix(nm.Request.URL.Path, "/api/") {
		a.fallback.RenderNoMatch(w, nm)
		return
	}

	w.Header().Set(mockhttp.HeaderContentType, mockhttp.MIMEApplicationJSON)
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintf(w, `{"code":"NOT_FOUND","closest":%d}`, len(nm.NearMisses))
}

func main() {
	m := mockhttp.MustNew(mockhttp.Setup().Silent().
		NoMatchRenderer(apiNoMatch{fallback: mockhttp.DefaultNoMatchRenderer(mockhttp.NoMatchAuto)}))
	m.MustStart()
	defer m.Close()

	m.MustMock(mockhttp.Getf("/api/users").Header("X-Tenant", match.Equal("a")).Reply(mockhttp.OK()))

	for _, path := range []string{"/api/users", "/health"} {
		res, err := http.Get(m.URL(path))
		if err != nil {
			panic(err)
		}

		body, err := io.ReadAll(res.Body)
		res.Body.Close()

		if err != nil {
			panic(err)
		}

		firstLine, _, _ := strings.Cut(string(body), "\n")
		fmt.Println(res.StatusCode, res.Header.Get(mockhttp.HeaderVlatteError), firstLine)
	}
}
Output:
404 no-match {"code":"NOT_FOUND","closest":1}
418 no-match # Request did not match

func (*ConfigBuilder) NoNearMisses

func (cb *ConfigBuilder) NoNearMisses() *ConfigBuilder

NoNearMisses turns off the report of the mocks closest to a request no mock matched, which the answer to it lists. The report runs no matcher twice: it runs those matching never reached, such as the action of a match.Peek after the part a mock differs in.

func (*ConfigBuilder) OnCompleteListener

func (cb *ConfigBuilder) OnCompleteListener(name string, listener vlatte.EventListener[vlatte.OnComplete]) *ConfigBuilder

OnCompleteListener registers an on-complete event listener by name, for the servers built from the builder from then on: a server built before doesn't get it. Without EventListeners, it goes in the server's registry, or in the one an earlier option set. A name registered twice fails the server's New, with vlatte.ErrEventAlreadyRegistered.

func (*ConfigBuilder) OutboundAllow

func (cb *ConfigBuilder) OutboundAllow(prefixes ...netip.Prefix) *ConfigBuilder

OutboundAllow adds the ranges the server may connect to: once set, it refuses every other address. See Config.OutboundAllow.

func (*ConfigBuilder) OutboundDeny

func (cb *ConfigBuilder) OutboundDeny(prefixes ...netip.Prefix) *ConfigBuilder

OutboundDeny adds ranges the server refuses to connect to, such as 169.254.0.0/16. See Config.OutboundAllow.

func (*ConfigBuilder) Port

func (cb *ConfigBuilder) Port(port int) *ConfigBuilder

Port sets a custom port to the mock HTTP server. If none is provided, a random port number will be used.

func (*ConfigBuilder) Proxy

func (cb *ConfigBuilder) Proxy(options ...ProxyConfigurer) *ConfigBuilder

Proxy configures the mock server as a proxy server. Non-Matched requests will be routed based on the proxy configuration.

func (*ConfigBuilder) ReadHeaderTimeout added in v1.1.0

func (cb *ConfigBuilder) ReadHeaderTimeout(timeout time.Duration) *ConfigBuilder

ReadHeaderTimeout sets the bound for reading request headers: see Config.ReadHeaderTimeout.

func (*ConfigBuilder) ReadTimeout added in v1.1.0

func (cb *ConfigBuilder) ReadTimeout(timeout time.Duration) *ConfigBuilder

ReadTimeout sets the bound for reading each request, including its headers and body: see Config.ReadTimeout.

func (*ConfigBuilder) Record

func (cb *ConfigBuilder) Record(options ...RecordConfigurer) *ConfigBuilder

Record configures recording.

func (*ConfigBuilder) RedactHeader

func (cb *ConfigBuilder) RedactHeader(names ...string) *ConfigBuilder

RedactHeader hides the values of the given HTTP headers in logs and recordings. A recording writes <redacted> for the values of a response header, and matches a request header that RecordRequestHeaders names by its presence.

func (*ConfigBuilder) RequestBodyParsers

func (cb *ConfigBuilder) RequestBodyParsers(bp ...RequestBodyParser) *ConfigBuilder

RequestBodyParsers adds a custom list of RequestBodyParsers.

func (*ConfigBuilder) RootDir

func (cb *ConfigBuilder) RootDir(rootDir string) *ConfigBuilder

RootDir sets the directory that relative mock file patterns and recording paths start at. Absolute ones are used as they are.

func (*ConfigBuilder) Silent

func (cb *ConfigBuilder) Silent() *ConfigBuilder

Silent turns the server's logs off: it sets the log level to vlatte.LogLevelDisabled. Echo replies set with EchoReply.Log still write requests to the log output.

func (*ConfigBuilder) TLSCertKeyPair

func (cb *ConfigBuilder) TLSCertKeyPair(certFile, keyFile string) *ConfigBuilder

TLSCertKeyPair sets a custom public/private key pair. If none is provided, default values will be used when starting the server with Server.StartTLS or Server.MustStartTLS. If TLSConfig is set, this option will be ignored.

func (*ConfigBuilder) TLSCertificates

func (cb *ConfigBuilder) TLSCertificates(certs []tls.Certificate) *ConfigBuilder

TLSCertificates sets the server TLS certificates.

func (*ConfigBuilder) TLSClientCAs

func (cb *ConfigBuilder) TLSClientCAs(pool *x509.CertPool) *ConfigBuilder

TLSClientCAs sets the certificate authorities used to verify client certificates (mutual TLS).

func (*ConfigBuilder) TLSConfig

func (cb *ConfigBuilder) TLSConfig(c *tls.Config) *ConfigBuilder

TLSConfig defines custom TLS configurations.

func (*ConfigBuilder) TLSMutual

func (cb *ConfigBuilder) TLSMutual(certFile, keyFile, clientCert string) *ConfigBuilder

TLSMutual defines the set of root certificate authorities that the server will use. If TLSConfig is set, this option will be ignored.

func (*ConfigBuilder) TemplateDataProviders

func (cb *ConfigBuilder) TemplateDataProviders(sdp []TemplateDataProvider) *ConfigBuilder

TemplateDataProviders sets template data providers.

func (*ConfigBuilder) TemplateEngine

func (cb *ConfigBuilder) TemplateEngine(e vlatte.TemplateEngine) *ConfigBuilder

TemplateEngine sets the engine that compiles every template of the server's mocks: reply bodies, headers and body file names, multipart parts, and the parameters of events such as webhooks. Without one, the server uses a vlatte.GoTemplateEngine. To give Go templates more functions, set one made with vlatte.WithTemplateFuncs.

func (*ConfigBuilder) TemplateEnv

func (cb *ConfigBuilder) TemplateEnv(names ...string) *ConfigBuilder

TemplateEnv allows the templates of the server's default engine to read the environment variables names with env. See Config.TemplateEnv.

func (*ConfigBuilder) TemplateKeys

func (cb *ConfigBuilder) TemplateKeys(specs ...string) *ConfigBuilder

TemplateKeys sets the keys the templates of the server's default engine sign and publish with: see Config.TemplateKeys.

func (*ConfigBuilder) Transport

func (cb *ConfigBuilder) Transport(rt http.RoundTripper) *ConfigBuilder

Transport sets the transport of what the server sends. See Config.Transport.

func (*ConfigBuilder) Use

func (cb *ConfigBuilder) Use(fn ...func(handler http.Handler) http.Handler) *ConfigBuilder

Use adds middlewares that wrap the mock handler, to intercept requests. They run in the order they are added, across calls. The journal, the logs and the events tell the status a middleware sends, when it answers in place of a mock.

func (*ConfigBuilder) UseDescriptiveLogger

func (cb *ConfigBuilder) UseDescriptiveLogger() *ConfigBuilder

UseDescriptiveLogger enable/disable the use of a more descriptive logger.

func (*ConfigBuilder) WorkDir

func (cb *ConfigBuilder) WorkDir(dir string) *ConfigBuilder

WorkDir sets the directory of the server's own files: the mock files, recordings, admin mocks and journal of its defaults, whose paths start with WorkDirVar. Empty is DefaultWorkDir, or DefaultWorkDir/<name> for a named server. A relative dir starts at RootDir.

type ConfigFlag

type ConfigFlag = config.Flag

ConfigFlag describes the command-line flag of a server setting; see ConfigFlags.

func ConfigFlags

func ConfigFlags() []ConfigFlag

ConfigFlags describes the command-line flag of every server setting, for example to register shell completions.

type ConfigSource

type ConfigSource = config.Source

ConfigSource is a place server settings are read from: see ConfigFile, ConfigEnv, ConfigArgs and ConfigBuilder.ConfigSources.

func ConfigArgs

func ConfigArgs(args []string) ConfigSource

ConfigArgs reads server settings from command-line arguments, such as --log-level=debug. It never reads os.Args: pass the arguments, such as os.Args[1:].

func ConfigEnv

func ConfigEnv() ConfigSource

ConfigEnv reads server settings from VLATTE_* environment variables, such as VLATTE_LOG_LEVEL for log.level. Any other VLATTE_* variable is an error, except VLATTE_DOCKER_HOST, which the vlatte command reads, and the VLATTE_GRPC_* ones, the gRPC server's: see mockgrpc.ConfigEnv.

func ConfigFile

func ConfigFile(path string, dirs ...string) ConfigSource

ConfigFile reads server settings from a JSON or YAML file, chosen by its extension: .json, .yaml or .yml.

With no dirs, path is the file to read, and it must exist. With dirs, path is a base name, such as DefaultConfigFileName, looked up in each dir; finding none is fine. A --config flag or VLATTE_CONFIG variable from a later source names the file to read instead of the lookup.

func DefaultConfigSources

func DefaultConfigSources(args []string) []ConfigSource

DefaultConfigSources lists the sources a server reads when Config.ConfigSources is nil, lowest precedence first: the config file, VLATTE_* environment variables, then args.

type DebugFn

type DebugFn func(string, any)

DebugFn is a function for debug logging.

type EchoReply

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

EchoReply configures a reply that writes the request back, as it came. It is a ReplierFactory.

func Echo

func Echo() *EchoReply

Echo returns a reply that writes the request back, as it came. Mock files have no echo reply: describing a mock with it fails, so the admin API can't show the mock, nor save or store it.

func (*EchoReply) Describe

func (e *EchoReply) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive. Mock files have no echo reply: encoding the description fails.

func (*EchoReply) Log

func (e *EchoReply) Log() *EchoReply

Log makes the reply also write each request to the server's log output, whatever its log level: see ConfigBuilder.LogOutput.

func (*EchoReply) NewReplier

func (e *EchoReply) NewReplier(app *Server) (Replier, error)

NewReplier implements ReplierFactory.

type Event

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

Event is an event of an event stream. Start one with NewEvent.

Its fields go on the wire as the event stream format reads them: data with line breaks becomes a data line per line, so clients read it back whole. An event type or id with a line break, or an id with a NUL, makes building the mock fail, or, in a templated stream, the reply that renders it. An event without data isn't dispatched by clients, though its id still counts.

func NewEvent

func NewEvent() *Event

NewEvent starts an event.

func (*Event) Comment

func (ev *Event) Comment(text string) *Event

Comment sets the comment of the event, sent first, a comment line per line, which clients skip. An event with only a comment is a comment.

func (*Event) Data

func (ev *Event) Data(text string) *Event

Data sets the data of the event, a template when the stream is templated. Like every data setter, it replaces the data an earlier one set.

func (*Event) DataJSON

func (ev *Event) DataJSON(v any) *Event

DataJSON sets the data of the event to the JSON of v. A value that doesn't marshal makes building the mock fail.

func (*Event) Delay

func (ev *Event) Delay(d time.Duration) *Event

Delay waits d before the event, in place of the stream's EventDelay: the events before it are sent and flushed first, so the client reads them while it waits.

func (*Event) ID

func (ev *Event) ID(id string) *Event

ID sets the id of the event, which clients send back as Last-Event-ID when they reconnect. An empty id is sent too: it resets the client's last event ID.

func (*Event) Name

func (ev *Event) Name(name string) *Event

Name sets the event type, the event field. Clients dispatch an event without one as a message.

func (*Event) Raw

func (ev *Event) Raw(text string) *Event

Raw sends text as it is in place of the event's fields, which it can't be set with, to test what the fields can't write: CRLF or CR line endings, a byte order mark, an event without the blank line that ends it, unknown fields. An id line in the text is sent but has no id for EventStream.ResumeFromLastEventID, which reads only Event.ID. A byte order mark counts only as the first bytes of the stream: not after the stream's retry, set with EventStream.Retry, or a heartbeat.

func (*Event) Retry

func (ev *Event) Retry(d time.Duration) *Event

Retry sets the retry field of the event: how long the client waits before it reconnects from now on.

type EventStream

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

EventStream is a body of Server-Sent Events, for a reply: the text/event-stream body of the WHATWG HTML standard, which the reply sends event by event, each flushed to the client as it goes. Start one with NewEventStream, and set it with Reply.EventStream.

The stream ends after its last event, unless it keeps open: see EventStream.KeepOpen. The mock counts the request once the stream starts, so Builder.Once serves one client and a scenario moves on while it is open. It runs its callbacks and on_complete events once the stream ends, with all it sent.

func NewEventStream

func NewEventStream(events ...*Event) *EventStream

NewEventStream starts an event stream with events, sent in order. The events are copied: changing one afterwards doesn't change the stream.

func (*EventStream) EventDelay

func (es *EventStream) EventDelay(d vlatte.Delay) *EventStream

EventDelay chooses the wait before each event without a delay of its own. Nil disables it. An evaluation error ends the stream and is reported as a reply failure.

func (*EventStream) Heartbeat

func (es *EventStream) Heartbeat(d time.Duration) *EventStream

Heartbeat sends a comment, which clients skip, each time the stream waits d without sending anything: while it waits for an event, and while it keeps open. Proxies and clients that drop idle connections keep it.

func (*EventStream) KeepOpen

func (es *EventStream) KeepOpen() *EventStream

KeepOpen keeps the stream open after its last event, until the client leaves or the server closes.

func (*EventStream) ResumeFromLastEventID

func (es *EventStream) ResumeFromLastEventID() *EventStream

ResumeFromLastEventID makes a request with a Last-Event-ID header, as a client sends when it reconnects, get only the events after the one with that id. A request with an id no event has gets them all. The retry field is sent either way.

func (*EventStream) Retry

func (es *EventStream) Retry(d time.Duration) *EventStream

Retry sends d first, as the retry field: how long a client waits before it reconnects once the stream ends. Clients read it in whole milliseconds.

func (*EventStream) Template

func (es *EventStream) Template() *EventStream

Template makes the text of the events templates, compiled with the template engine of the server and rendered with the data of each request: their types, ids, comments and text data. JSON data and raw events are sent as they are. The mock's description keeps JSON data as JSON: built back, the stream sends it compact, with its object keys sorted. JSON with a number past int64, which a file can't hold, is written as its text, a template then.

type FilePattern

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

FilePattern is what a file of a multipart form must have to match: its name, content type, headers and content. Start one with FileWith, and match it with Builder.FormFile. The files are the ones http.Request.ParseMultipartForm reads: parts with a field name and a filename.

func FileWith

func FileWith() *FilePattern

FileWith starts a FilePattern. With no condition set, it matches any file.

func (*FilePattern) Body

func (p *FilePattern) Body(matchers ...vlatte.Matcher) *FilePattern

Body sets matchers of the file's content, which all must match. The content is text, so an empty file reads "". It panics without a matcher.

func (*FilePattern) BodyFile

func (p *FilePattern) BodyFile(filename string) *FilePattern

BodyFile matches a file whose content equals the named file's. The named file is read now: an error reading it makes Builder.Build fail.

func (*FilePattern) ContentType

func (p *FilePattern) ContentType(m vlatte.Matcher) *FilePattern

ContentType sets a matcher of the media type of the file's Content-Type: in lower case and without parameters, as mime.ParseMediaType reads it, or "" when the file has none.

func (*FilePattern) Every

func (p *FilePattern) Every() *FilePattern

Every makes the pattern match when the field has one file at least, and every one of them matches it.

func (*FilePattern) Filename

func (p *FilePattern) Filename(m vlatte.Matcher) *FilePattern

Filename sets a matcher of the file's name, as Go reads it: multipart.FileHeader.Filename, the base of the name sent.

func (*FilePattern) Header

func (p *FilePattern) Header(name string, m vlatte.Matcher) *FilePattern

Header adds a matcher of a header of the file's part: its first value, or "" when it has none.

type FromTypes

type FromTypes interface{ ~string | *url.URL }

FromTypes are the types of the target From takes: a URL, as text, of a string type of any name, or parsed.

type FuncReply

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

FuncReply is a reply that builds the response using the given function. It is a ReplierFactory: every mock built with it calls the same function, so whatever the function keeps is shared by those mocks.

func Func

Func returns a reply that builds the response using the given function. The context of its RawRequest also ends when a pipe of the mock cuts the answer. A mock file can't hold a function: describing a mock with it fails, so the admin API can't show the mock, nor save or store it.

func Handler

func Handler(h http.HandlerFunc) *FuncReply

Handler returns a reply that delegates to the given http.HandlerFunc. The context of its request also ends when a pipe of the mock cuts the answer. Describing a mock with it fails, as with Func.

func (*FuncReply) Describe

func (r *FuncReply) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive. A mock file can't hold a function: encoding the description fails.

func (*FuncReply) NewReplier

func (r *FuncReply) NewReplier(*Server) (Replier, error)

NewReplier implements ReplierFactory.

type JournalConfig

type JournalConfig struct {
	// Dir is where the journal keeps its files, across restarts: a server that starts again finds the requests it
	// served before. Relative paths start at RootDir, and WorkDirVar at the server's work directory, as in
	// "{workdir}/_journal". Empty keeps them in a temporary directory, which Close removes.
	Dir string

	// MaxEntries is how many requests the journal keeps, the newest. 0 keeps them all.
	MaxEntries int

	// MaxBodySize is how many bytes of a request's body the journal keeps. 0 keeps whole bodies.
	MaxBodySize int64
}

JournalConfig configures the journal of a server: the requests its mocks get, of every outcome, which tests and the admin API verify and search, while the server runs: Close closes it. The requests the server answers before its mocks get them, such as CORS preflights, and those a middleware answers, aren't in it. A nil *JournalConfig keeps none.

type Kit

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

Kit is the vlatte.Kit of HTTP mocks: the server's template engine, logger and webhook transport, the template data of the request, and the directory of the mock file of the event it serves.

func (*Kit) Data

func (k *Kit) Data() any

Data implements vlatte.Kit: the template data of the request, as the templates of its reply read it.

func (*Kit) Dir

func (k *Kit) Dir() string

Dir implements vlatte.Kit: the directory of the mock file that defines the event, or "" for the working directory, as for events defined in Go and global events.

func (*Kit) Logger

func (k *Kit) Logger() *zerolog.Logger

Logger implements vlatte.Kit: the server's logger.

func (*Kit) TemplateEngine

func (k *Kit) TemplateEngine() vlatte.TemplateEngine

TemplateEngine implements vlatte.Kit: the server's template engine.

func (*Kit) Transport

func (k *Kit) Transport() http.RoundTripper

Transport implements vlatte.Kit: the server's Config.Transport, or else a transport the server makes and closes with it.

type Loader

type Loader interface {
	Load(app *Server) error
}

Loader loads mocks from outside the code, such as mock files. Load runs on the first Start and on every Reload, so it replaces the mocks its last run added, which Server.Remock does in one step. At Start, the server listens already, so URL is set, and serves once the loaders return.

type Mapper

type Mapper func(requestValues *RequestValues, res *Response) error

Mapper is the function definition to be used to map a Mock response MockedResponse before serving it. The response is the mapper's to change, but for its Body bytes, which other responses of the mock can share: replace them, don't change them in place.

type MatcherSpec

type MatcherSpec []any

MatcherSpec is a matcher as mock files write it, such as ["eqj", "{...}"] or ["not", "present"].

type Mock

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

Mock holds metadata and expectations to be matched against HTTP requests in order to serve mocked responses. This is the core entity of this project, and most features work based on it. A Builder makes it; afterwards only its enabled state and hits change.

func DecodeMock

func DecodeMock(app *Server, data []byte, format string) (*Mock, error)

DecodeMock builds the mock data describes in format, as EncodeMock wrote it, for the server app, as a mock the admin API added: a reset of the server removes it, unless its store holds it still. Its relative body files open from the working directory. When data has problems, the error lists each.

func (*Mock) Called

func (m *Mock) Called() bool

Called checks if the Mock was called at least once.

func (*Mock) Close

func (m *Mock) Close() error

Close releases what the mock's reply holds, such as the idle connections of a proxy's HTTP client. The store closes a mock when it leaves the server, and Server.Close closes the mocks still stored. Only the first call does anything.

func (*Mock) Describe

func (m *Mock) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive: the mock in the mock file format. It leaves out callbacks, and pipes that don't describe themselves. Delay description errors propagate. A reply a mock file can't hold, such as Echo, stays, so encoding the description fails.

func (*Mock) Disable

func (m *Mock) Disable()

Disable disables the Mock. The Mock will not be eligible to be matched.

func (*Mock) Enable

func (m *Mock) Enable()

Enable enables the Mock. The Mock will be eligible to be matched.

func (*Mock) Enabled

func (m *Mock) Enabled() bool

Enabled reports whether the mock may match requests.

func (*Mock) Events

func (m *Mock) Events() vlatte.Events

Events returns the events the mock runs once it replied, its callbacks included.

func (*Mock) Hits

func (m *Mock) Hits() int64

Hits returns the amount of time this Mock was matched to a request and served.

func (*Mock) ID

func (m *Mock) ID() string

ID returns the ID of the mock: the one set with Builder.ID, or one generated when it was built.

func (*Mock) Inc

func (m *Mock) Inc()

Inc increment one Mock call.

func (*Mock) MarshalJSON

func (m *Mock) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler: it encodes the mock's Mock.Describe description, and fails when the description holds a reply a mock file can't, such as Echo.

func (*Mock) Name

func (m *Mock) Name() string

Name returns the name of the mock, or "" when it has none.

func (*Mock) Origin

func (m *Mock) Origin() string

Origin returns where the mock comes from, such as the mock file that describes it, or "" for a mock built in Go.

func (*Mock) Pipes

func (m *Mock) Pipes() []vlatte.Pipe

Pipes returns the pipes that the body of each answer of the mock passes through: see Builder.Pipe.

func (*Mock) Priority

func (m *Mock) Priority() int

Priority returns the priority of the mock: mocks with a lower one match first.

func (*Mock) String

func (m *Mock) String() string

String names the mock as "Mock [id] name", as assertion messages do.

func (*Mock) Switch

func (m *Mock) Switch(state bool)

Switch enables the mock when state is true, and disables it otherwise.

func (*Mock) UpstreamPipes

func (m *Mock) UpstreamPipes() []vlatte.Pipe

UpstreamPipes returns the pipes that what the mock sends on passes through: see Builder.UpstreamPipe.

func (*Mock) WirePipes

func (m *Mock) WirePipes() []vlatte.Pipe

WirePipes returns the pipes that the bytes of each answer of the mock pass through: see Builder.WirePipe.

type MockFileHandler

type MockFileHandler interface {
	// Handle reads fields, the ext object of a mock file, and sets the mock through b.
	// Keys are as written. Objects are map[string]any and lists []any; whole numbers that fit int64 are int64,
	// and other numbers float64, from JSON and YAML alike.
	// An error is a problem of the mock file's ext key.
	Handle(fields map[string]any, b *Builder) error
}

MockFileHandler reads the ext object of mock files, so users can add settings of their own to mock files.

type Multipart

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

Multipart is a multipart body, for a reply or a webhook: its subtype, boundary and parts, written with mime/multipart.Writer. Start one with MultipartForm, MultipartMixed or NewMultipart.

func MultipartForm

func MultipartForm(parts ...*Part) *Multipart

MultipartForm starts a multipart/form-data body. Each of its parts needs a name.

func MultipartMixed

func MultipartMixed(parts ...*Part) *Multipart

MultipartMixed starts a multipart/mixed body.

func NewMultipart

func NewMultipart(subtype string, parts ...*Part) *Multipart

NewMultipart starts a body of multipart/<subtype>, such as related, alternative, byteranges or x-mixed-replace. The parts are copied: changing one afterwards doesn't change the body.

func (*Multipart) Boundary

func (mp *Multipart) Boundary(boundary string) *Multipart

Boundary sets the boundary between the parts. Without one, a random boundary is drawn when the mock is built.

func (*Multipart) Check

func (mp *Multipart) Check(engine vlatte.TemplateEngine) error

Check checks the body and compiles its templates with engine, as Encode does, without writing it: a webhook checks its body when its mock is built.

func (*Multipart) Describe

func (mp *Multipart) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive, as the parameters of a webhook write the body: under multipart, or multipart_template when its text is templates. A reply describes its body itself.

func (*Multipart) Encode

func (mp *Multipart) Encode(engine vlatte.TemplateEngine, data any) (contentType string, body []byte, err error)

Encode writes the whole body, with its templates compiled with engine and rendered with data, under a boundary drawn now when none is set. It returns the body's Content-Type and bytes. engine can be nil when the body isn't templated. A body written at once can't pause, so a part with a delay is an error: delays apply to replies only.

func (*Multipart) Param

func (mp *Multipart) Param(name, value string) *Multipart

Param adds a parameter to the Content-Type, such as type and start for multipart/related.

func (*Multipart) Template

func (mp *Multipart) Template() *Multipart

Template makes the text of the parts templates, compiled with the template engine of the server and rendered with the data of each reply: their names, filenames, content types, header values, text bodies and body file names. Byte and JSON bodies, and the content of body files, are written as they are.

type NoMatch

type NoMatch struct {
	// Request is the request no mock matched.
	Request *RequestValues

	// NearMisses are the mocks that came closest to matching the request, closest first, as the journal records them.
	// It is empty when the server reports none, as with [ConfigBuilder.NoNearMisses]. They are a copy: changing them
	// changes neither the journal nor the events.
	NearMisses []vlatte.NearMiss

	// Status is the status the server answers a request no mock matched with: [StatusNoMatch] unless
	// [ConfigBuilder.MockNotFoundStatusCode] sets another.
	Status int
}

NoMatch is what the server knows of a request no mock matched, which a NoMatchRenderer answers.

type NoMatchFormat

type NoMatchFormat int

NoMatchFormat is the format of the answer DefaultNoMatchRenderer gives a request no mock matched.

const (
	// NoMatchAuto picks the format the request's Accept header prefers, and adds Accept to the Vary header:
	// NoMatchJSON for application/json or a type such as application/vnd.api+json, NoMatchProblem only when Accept
	// prefers application/problem+json to application/json, NoMatchMarkdown for text/markdown, and NoMatchText
	// otherwise, as for a request without Accept or one that accepts only */*. Of types Accept weighs the same, the
	// one a more specific range names wins, such as application/json over */*, then the one Accept lists first.
	NoMatchAuto NoMatchFormat = iota
	// NoMatchText is a Markdown document sent as text/plain, which reads as well as it renders.
	NoMatchText
	// NoMatchMarkdown is the document of NoMatchText sent as text/markdown.
	NoMatchMarkdown
	// NoMatchJSON is an RFC 9457 problem details object sent as application/json. Next to the standard members, it
	// has request_id, request, with its method and url, and near_misses.
	NoMatchJSON
	// NoMatchProblem is the object of NoMatchJSON sent as application/problem+json.
	NoMatchProblem
)

No-match formats.

type NoMatchRenderer

type NoMatchRenderer interface {
	RenderNoMatch(w http.ResponseWriter, nm *NoMatch)
}

NoMatchRenderer writes the answer to a request no mock matched. The server calls it for many requests at once.

The server sets the VLatte-Error header before it calls RenderNoMatch: it tells a client that the server answered, not a mock, so a renderer should keep it. It sets X-Content-Type-Options: nosniff too, so a browser takes the answer, which can echo the request, for the Content-Type the renderer sets. A renderer that writes nothing answers with NoMatch.Status and no body. The journal, the events and the logs record the request whatever the renderer sends.

func DefaultNoMatchRenderer

func DefaultNoMatchRenderer(format NoMatchFormat) NoMatchRenderer

DefaultNoMatchRenderer returns the renderer of the answers to requests no mock matched in format, the one a server uses unless ConfigBuilder.NoMatchRenderer sets another. A custom renderer can hand it the requests it doesn't answer itself. It panics when format is not one of the NoMatch* formats.

type OnComplete

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

OnComplete implements vlatte.OnComplete for HTTP mocks. Listeners, and the callbacks of Builder.Callback, get it once the mock replied, and the response waits for them, but for those set to run after it. It's read-only: the listeners of a request run at the same time. The request's body was read: read it from Request, not from RawRequest.Body. Listeners use the context they get: it has the request's values, and the client leaving doesn't end it, as it ends the request's.

func (*OnComplete) Dir

func (i *OnComplete) Dir() string

Dir is where relative files of the event's parameters open from: the directory of the mock file that defines the event, or "" for the working directory, as for events defined in Go and global events.

func (*OnComplete) Kind

func (i *OnComplete) Kind() vlatte.Kind

Kind implements vlatte.EventArgs: Kind, for HTTP mocks.

func (*OnComplete) Kit

func (i *OnComplete) Kit() vlatte.Kit

Kit implements vlatte.EventArgs: a *Kit.

func (*OnComplete) Logger

func (i *OnComplete) Logger() *zerolog.Logger

Logger is the server's logger, so listeners such as webhooks log where the server does, and as little.

func (*OnComplete) Mock

func (i *OnComplete) Mock() vlatte.Mock

Mock implements vlatte.OnComplete: the *Mock that replied.

func (*OnComplete) Parameters

func (i *OnComplete) Parameters() vlatte.Parameters

Parameters implements vlatte.EventArgs: the parameters of the event, as its listener prepared them.

func (*OnComplete) Request

func (i *OnComplete) Request() *RequestValues

Request returns the request the mock replied to.

func (*OnComplete) Response

func (i *OnComplete) Response() *Response

Response returns the response the mock replied with, or nil for a reply that wrote its answer itself, such as Echo.

func (*OnComplete) Transport

func (i *OnComplete) Transport() http.RoundTripper

Transport is the server's Config.Transport, or else a transport the server makes and closes with it, so listeners such as webhooks send through it when they have none of their own, and their connections don't outlive the server.

type Option

type Option = vlatte.Configurer[*Config]

Option configures a Server. Both Config and ConfigBuilder are options.

type Part

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

Part is a part of a multipart body. Start one with NewPart.

func NewPart

func NewPart() *Part

NewPart starts a part.

func (*Part) Body

func (p *Part) Body(b []byte) *Part

Body sets the body of the part, written as it is. Like every body setter, it replaces the body an earlier one set.

func (*Part) BodyFile

func (p *Part) BodyFile(filename string) *Part

BodyFile sets the body of the part to the content of a file, read at each reply. Relative paths start at the working directory, or at the mock file's directory for mock files.

func (*Part) BodyJSON

func (p *Part) BodyJSON(v any) *Part

BodyJSON sets the body of the part as the JSON of v. A value that doesn't marshal makes building the mock fail.

func (*Part) BodyText

func (p *Part) BodyText(text string) *Part

BodyText sets the body of the part as text, a template when the body is templated.

func (*Part) ContentType

func (p *Part) ContentType(contentType string) *Part

ContentType sets the Content-Type of the part. Without one, a JSON body is application/json, and a part with a filename application/octet-stream.

func (*Part) Delay

func (p *Part) Delay(d time.Duration) *Part

Delay makes a reply wait d before writing the part: the parts before it are sent and flushed first, so a client reads them while it waits, as in multipart/x-mixed-replace streams.

func (*Part) Filename

func (p *Part) Filename(filename string) *Part

Filename sets the file name of the part, in its Content-Disposition.

func (*Part) Header

func (p *Part) Header(key, value string) *Part

Header adds a header to the part.

func (*Part) Name

func (p *Part) Name(name string) *Part

Name sets the name of the part, in its Content-Disposition. Every part of a form-data body needs one.

type Problem

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

Problem builds an RFC 9457 problem details object, the body Reply.Problem sends. Every member is optional: one that is never set is left out of the JSON, and a missing type means "about:blank" to clients.

func NewProblem

func NewProblem() *Problem

NewProblem creates a new, empty Problem.

func (*Problem) Detail

func (p *Problem) Detail(detail string) *Problem

Detail sets the human-readable explanation of this occurrence of the problem.

func (*Problem) Extension

func (p *Problem) Extension(name string, value any) *Problem

Extension sets an extension member, encoded as JSON next to the standard members. Setting a name again replaces its value. A name of a standard member (type, title, status, detail or instance) makes building the mock that replies with the problem fail.

func (*Problem) Instance

func (p *Problem) Instance(uri string) *Problem

Instance sets the URI reference that identifies this occurrence of the problem.

func (*Problem) Status

func (p *Problem) Status(status int) *Problem

Status sets the HTTP status code of the problem. Reply.Problem gives the response this status too. Zero leaves it out.

func (*Problem) Title

func (p *Problem) Title(title string) *Problem

Title sets the short, human-readable summary of the problem type.

func (*Problem) Type

func (p *Problem) Type(uri string) *Problem

Type sets the URI reference that identifies the problem type.

type ProxyConfig

type ProxyConfig struct {
	// Via sets the URL, http or https, of another proxy server to send the requests through, with the transport the
	// proxy makes. Its credentials go in its URL: a client's Proxy-Authorization is for this proxy, and doesn't go on.
	// Over https, set SSLVerify too, so they go to that proxy only. Without Via, the transport the proxy makes goes
	// through the proxy of the environment, HTTP_PROXY, HTTPS_PROXY and NO_PROXY, which leaves out localhost.
	Via string

	// Timeout bounds the wait for the response headers of the host, connecting and sending the request included, with
	// any transport, and the opening of a tunnel. 0 sets no bound of its own: the transport the proxy makes, and the
	// tunnels, still give up connecting after 30s, and a TLS handshake after 10s. Setup().Proxy and the settings
	// default it to 30s, as for proxy replies: a ProxyConfig without Timeout keeps it, and only the setting
	// proxy.timeout sets 0.
	Timeout time.Duration

	// SSLVerify sets whether the transport the proxy makes, and the tunnels, verify the TLS certificates of the hosts,
	// and of an https proxy on the way, Via or the one of the environment. They aren't verified by default.
	SSLVerify bool

	// Intercept serves the TLS of the CONNECT tunnels no mock matches itself, with a certificate for each host, signed
	// by CA: the requests within are served as the server's own, so mocks answer them and recordings record them, and
	// the proxy sends the rest on to their hosts. Clients must trust CA. A connection that doesn't start with TLS goes
	// to its host through a tunnel.
	Intercept bool

	// CA is the CA that signs the certificates of the hosts Intercept serves. Without it, the server makes a CA of its
	// own, which Server.ProxyCA returns, for clients to trust.
	CA *tls.Certificate

	// Transport sends the requests the proxy passes on, in place of the server's Config.Transport. It is the caller's:
	// the server never closes it. With neither, the proxy makes a transport, which Via, Timeout and SSLVerify shape:
	// Via and SSLVerify fail New with a transport of the caller's, which would ignore them. The tunnels of CONNECT
	// requests go through the proxy the transport the proxy makes picks, Via or the proxy of the environment, and dial
	// their hosts with a transport of the caller's.
	Transport http.RoundTripper
}

ProxyConfig configures a proxy.

func (*ProxyConfig) Apply

func (p *ProxyConfig) Apply(c *ProxyConfig) error

Apply sets the fields of p that aren't zero on c, so configs compose: Setup().Proxy(&ProxyConfig{SSLVerify: true}) keeps the default Timeout. A config turns no setting off.

type ProxyConfigurer

type ProxyConfigurer interface {
	Apply(config *ProxyConfig) error
}

ProxyConfigurer lets users configure the proxy.

type ProxyReply

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

ProxyReply represents a response stub that will be the response "proxied" from the specified target. Use From to init a new ProxyReply. It is a ReplierFactory: each mock built with it gets a proxy of its own. It sends through the reply's Transport, or else the server's Config.Transport, or else a transport of its own, whose idle connections close when the mock leaves the server or the server closes.

func From

func From[T FromTypes](target T) *ProxyReply

From creates a ProxyReply with the given target. The target's path and query come before the request's: with http://api/v1?tenant=a, a request to /users?page=2 goes to http://api/v1/users?tenant=a&page=2. It panics when target is a nil *url.URL, or text that url.Parse fails on.

func (*ProxyReply) Describe

func (r *ProxyReply) Describe() vlatte.Descriptor

Describe describes the reply in the mock file format. The target is described as it was set, its credentials included, so the description loads back as the same reply: errors and logs hide them. ssl_verify is described only when it was set, so the description loads back on a server whose Config.Transport would refuse it.

func (*ProxyReply) Header

func (r *ProxyReply) Header(key, value string) *ProxyReply

Header adds a value to a response header, which replaces the target's values of that name.

func (*ProxyReply) Headers

func (r *ProxyReply) Headers(header http.Header) *ProxyReply

Headers adds the values of response headers, which replace the target's values of those names.

func (*ProxyReply) NewReplier

func (r *ProxyReply) NewReplier(app *Server) (Replier, error)

NewReplier implements ReplierFactory. Each mock gets a proxy of its own: copies of the target and the headers, and, without the reply's Transport or the server's, a transport of its own.

func (*ProxyReply) PreserveHost

func (r *ProxyReply) PreserveHost() *ProxyReply

PreserveHost sends the target the Host the client asked for, in place of the target's own, as for a target that serves several hosts, or that checks which host it is asked for.

func (*ProxyReply) RemoveRequestHeaders

func (r *ProxyReply) RemoveRequestHeaders(header ...string) *ProxyReply

RemoveRequestHeaders removes the given headers from the request before it is sent to the proxy target.

func (*ProxyReply) RequestHeader

func (r *ProxyReply) RequestHeader(key, value string) *ProxyReply

RequestHeader adds a value to a header sent to the proxy target, which replaces the client's values of that name. A hop-by-hop header, such as Connection or Upgrade, fails the build of the mock: it is about one connection, and a proxy doesn't make one up. A client's request to switch protocols goes on as the client asked. "Te: trailers" is the exception.

func (*ProxyReply) RequestHeaders

func (r *ProxyReply) RequestHeaders(header http.Header) *ProxyReply

RequestHeaders adds the values of headers sent to the proxy target, which replace the client's values of those names. A hop-by-hop header, such as Connection or Upgrade, fails the build of the mock, as for RequestHeader.

func (*ProxyReply) SSLVerify

func (r *ProxyReply) SSLVerify(v bool) *ProxyReply

SSLVerify sets whether the target's TLS certificate is verified, and the certificate of an https proxy on the way, from HTTPS_PROXY. They aren't by default, so a target with a self-signed certificate answers: set it for a target that gets credentials, such as https://user:pass@api.

func (*ProxyReply) SkipSSLVerify

func (r *ProxyReply) SkipSSLVerify() *ProxyReply

SkipSSLVerify skips the verification of the target's TLS certificate, as a ProxyReply does unless SSLVerify(true).

func (*ProxyReply) Timeout

func (r *ProxyReply) Timeout(timeout time.Duration) *ProxyReply

Timeout sets how long to wait for the response headers of the target, from the call: connecting and sending the request count too. The body then streams to the client as the target sends it, for as long as the client waits. 0 waits forever. Defaults to 30s.

func (*ProxyReply) Transport

func (r *ProxyReply) Transport(rt http.RoundTripper) *ProxyReply

Transport sets the transport that sends the requests to the target, in place of the server's Config.Transport. It is the caller's: the proxy never closes it. It decides on its own whether it verifies the target, so SSLVerify and SkipSSLVerify fail the build of the mock with it, as with the server's Config.Transport.

func (*ProxyReply) TrimPrefix

func (r *ProxyReply) TrimPrefix(prefix string) *ProxyReply

TrimPrefix removes the given prefix from the request path, before the target's path is added. It trims whole segments: "/api" turns "/api/users" into "/users", and "/api" into "", and leaves "/apiary" as it is.

func (*ProxyReply) TrimSuffix

func (r *ProxyReply) TrimSuffix(suffix string) *ProxyReply

TrimSuffix removes the given suffix from the request path, before the target's path is added. It trims text, such as an extension: ".json" turns "/users.json" into "/users".

func (*ProxyReply) XForwarded

func (r *ProxyReply) XForwarded() *ProxyReply

XForwarded sets the X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto headers of the requests the target gets, as httputil.ProxyRequest.SetXForwarded does: the client's address, after those of the proxies the request came through, the host the client asked for, and its scheme. Without it, the target gets the client's, if any.

type RandomReply

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

RandomReply configures replies served at random, one per request. It is a ReplierFactory: each mock built with it picks from replies of its own.

func Rand

func Rand(reply ...ReplierFactory) *RandomReply

Rand initializes a new RandomReply.

func RandWith

func RandWith(random *rand.Rand, reply ...ReplierFactory) *RandomReply

RandWith creates a new RandomReply that picks replies with the given *rand.Rand. Every mock built with the reply picks with it.

func RandWithSeed

func RandWithSeed(seed int64, reply ...ReplierFactory) *RandomReply

RandWithSeed creates a new RandomReply that picks replies in a sequence reproducible by the given seed. Each mock built with the reply picks with a generator of its own, from the seed, so each one picks in the same order.

func (*RandomReply) Add

func (rep *RandomReply) Add(reply ...ReplierFactory) *RandomReply

Add adds a new Replier to the random list.

func (*RandomReply) Describe

func (rep *RandomReply) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive: the reply in the mock file format. It leaves out the replies that don't implement vlatte.SelfDescriptive, and the generator of RandWith.

func (*RandomReply) NewReplier

func (rep *RandomReply) NewReplier(app *Server) (Replier, error)

NewReplier implements ReplierFactory. It makes the Replier of each reply, so each mock picks from replies of its own.

type Recipe

type Recipe = vlatte.Recipe[*Mock, *Server]

Recipe prepares a Server, for example by adding a set of mocks; see Server.Prep.

type RecordConfig

type RecordConfig struct {
	// Dir is the directory of the recordings. Relative paths start at Config.RootDir. Defaults to
	// testdata/_mocks_recorded.
	Dir string

	// Format is the format of the recorded mock files: json, yaml or yml. Defaults to json.
	Format string

	// Target is the server to record: the requests the recording takes go to it, before any mock, and its answers are
	// recorded. It is an absolute http or https URL without a path, query or fragment, such as
	// https://api.example.com. Without one, the recording takes what the forward proxy and proxy replies answer.
	Target string

	// Methods are the methods of the requests the recording takes, in any case. None takes every method.
	Methods []string

	// Paths are glob patterns of the paths of the requests the recording takes, such as /v1/*, where * matches a "/"
	// too. None takes every path.
	Paths []string

	// Filter is a request pattern the requests the recording takes must match, made with Request(), such as
	// Request().Header("X-Record", match.Equal("yes")). The recording uses its request matchers only.
	Filter *Builder

	// SkipSSLVerify skips the verification of the Target's TLS certificate, such as for a self-signed one. A recording
	// sends the target its requests, credentials included, so the transport it makes verifies the target by default.
	SkipSSLVerify bool

	// Transport sends the requests to the Target, in place of the server's Config.Transport, such as one that trusts
	// the target's private CA. It is the caller's: the recording never closes it. It decides on its own whether it
	// verifies the target, so SkipSSLVerify fails the recording with it, as with the server's Config.Transport.
	Transport http.RoundTripper

	// RequestHeaders are the request headers a recording matches: the first value each had, or its absence. One that
	// ConfigBuilder.RedactHeader names matches by its presence, so its value isn't written. A recording matches no
	// other header.
	RequestHeaders []string

	// ExcludeResponseHeaders are the response headers a recording leaves out, in any case. Defaults to Set-Cookie, so
	// mock files hold no session of the service. A list replaces the default.
	ExcludeResponseHeaders []string

	// BodyFiles writes every response body to a file of its own, next to the mock file, instead of inline.
	BodyFiles bool

	// MaxInlineBody is how many bytes of a body stay in memory while it is recorded: a larger one goes to a file as
	// it streams, at the pace of the disk, which it waits for a second in all at most: a disk slower than that drops
	// the recording, never the answer. A text body that stays in memory is written inline in the mock file. 0 means
	// 1 MiB.
	MaxInlineBody int64

	// MaxBodySize bounds the response bodies recorded: a call with a larger one isn't recorded. 0 means 1 GiB, and a
	// negative value means no limit.
	MaxBodySize int64

	// Repeats is what a recording keeps of a request that comes again: every response, in order, or the first one.
	// Defaults to vlatte.RecordSequence.
	Repeats vlatte.RecordRepeats

	// IncludeMocked records the answers of mocks too. Without it, only proxied answers are recorded: those of the
	// forward proxy and of proxy replies, such as From.
	IncludeMocked bool

	// Transforms change each recording before it is written, in order. A transform that fails skips the recording,
	// and so do transforms that leave it no response.
	Transforms []func(*RecordedMock) error
}

RecordConfig configures recording: where the recordings go, what they match and what they keep. See Server.StartRecording.

func (*RecordConfig) Apply

func (r *RecordConfig) Apply(c *RecordConfig) error

Apply sets the fields of r that aren't zero on c, and adds r's Transforms to c's, so configs compose. A config turns no setting off: options such as RecordBodyFiles(false) do.

type RecordConfigurer

type RecordConfigurer interface {
	Apply(c *RecordConfig) error
}

RecordConfigurer lets users configure recording.

func RecordBodyFiles

func RecordBodyFiles(v bool) RecordConfigurer

RecordBodyFiles sets whether every response body goes to a file of its own, instead of inline.

func RecordDir

func RecordDir(dir string) RecordConfigurer

RecordDir sets the directory of the recordings. Relative paths start at Config.RootDir.

func RecordExcludeResponseHeaders

func RecordExcludeResponseHeaders(names ...string) RecordConfigurer

RecordExcludeResponseHeaders sets the response headers recordings leave out, in any case, in place of the default Set-Cookie. With no names, recordings keep every response header.

func RecordFilter

func RecordFilter(filter *Builder) RecordConfigurer

RecordFilter sets a request pattern the requests the recording takes must match, made with Request(). See RecordConfig.Filter.

func RecordFormat

func RecordFormat(format string) RecordConfigurer

RecordFormat sets the format of the recorded mock files: json, yaml or yml.

func RecordIncludeMocked

func RecordIncludeMocked(v bool) RecordConfigurer

RecordIncludeMocked sets whether the answers of mocks are recorded too, not only proxied ones.

func RecordMaxBodySize

func RecordMaxBodySize(n int64) RecordConfigurer

RecordMaxBodySize bounds the response bodies recorded. See RecordConfig.MaxBodySize.

func RecordMaxInlineBody

func RecordMaxInlineBody(n int64) RecordConfigurer

RecordMaxInlineBody sets how many bytes of a body stay in memory while it is recorded. See RecordConfig.MaxInlineBody.

func RecordMethods

func RecordMethods(methods ...string) RecordConfigurer

RecordMethods sets the methods of the requests the recording takes, in any case.

func RecordPaths

func RecordPaths(globs ...string) RecordConfigurer

RecordPaths sets glob patterns of the paths of the requests the recording takes, such as /v1/*, where * matches a "/" too.

func RecordRepeats

func RecordRepeats(repeats vlatte.RecordRepeats) RecordConfigurer

RecordRepeats sets what a recording keeps of a request that comes again: vlatte.RecordSequence, the default, or vlatte.RecordFirst.

func RecordRequestHeaders

func RecordRequestHeaders(names ...string) RecordConfigurer

RecordRequestHeaders sets the request headers recordings match: the first value each had, or its absence.

func RecordSkipSSLVerify

func RecordSkipSSLVerify(v bool) RecordConfigurer

RecordSkipSSLVerify sets whether the verification of the target's TLS certificate is skipped. See RecordConfig.SkipSSLVerify.

func RecordTarget

func RecordTarget(target string) RecordConfigurer

RecordTarget sets the server to record. See RecordConfig.Target.

func RecordTransform

func RecordTransform(transform func(*RecordedMock) error) RecordConfigurer

RecordTransform adds a transform, which changes each recording before it is written. A transform that fails skips the recording.

func RecordTransport

func RecordTransport(rt http.RoundTripper) RecordConfigurer

RecordTransport sets the transport that sends the requests to the target. See RecordConfig.Transport.

type RecordedFile

type RecordedFile struct {
	Filename    string      `json:"filename"`
	ContentType string      `json:"content_type,omitempty"`
	Body        MatcherSpec `json:"body,omitempty"`
	BodyFile    string      `json:"body_file,omitempty"`
}

RecordedFile is a file of a recorded multipart form: a form_file pattern.

type RecordedMock

RecordedMock is a mock a recording made, as RecordConfig.Transforms change it; see vlatte.RecordedMock.

type RecordedRequest

type RecordedRequest struct {
	Method string `json:"method"`

	// URL is the path and query, which must be the same: the parameters in any order, each with its values in order.
	URL string `json:"url"`

	// Header matches the request headers RecordConfig.RequestHeaders names, and the media type of a body.
	Header map[string]MatcherSpec `json:"header,omitempty"`

	// FormFile matches the files of a multipart form, by field name.
	FormFile map[string][]RecordedFile `json:"form_file,omitempty"`

	// Body matches the body. A recording matches no body it couldn't read, such as one that isn't text.
	Body MatcherSpec `json:"body,omitempty"`
}

RecordedRequest is what a recording matches: the request section of its mock file.

type RecordedResponse

type RecordedResponse struct {
	Status  int                 `json:"status"`
	Header  map[string][]string `json:"header,omitempty"`
	Trailer map[string][]string `json:"trailer,omitempty"`

	// Body is a text body, written inline. A body that isn't text, or is larger than RecordConfig.MaxInlineBody, goes
	// to BodyFile, next to the mock file.
	Body     string `json:"body,omitempty"`
	BodyFile string `json:"body_file,omitempty"`

	// Encoding is gzip for a gzip body recorded decoded: it is compressed again when it is served.
	Encoding string `json:"encoding,omitempty"`
}

RecordedResponse is a response a recording replies with: a response section of its mock file.

type Replier

type Replier = vlatte.Replier[ReplyInput, *Response]

Replier builds the response of a mock. Each mock has its own, made by a ReplierFactory.

type ReplierFactory

type ReplierFactory = vlatte.ReplierFactory[ReplyInput, *Response, *Server]

ReplierFactory makes the Replier of each mock: see vlatte.ReplierFactory. Reply, SequentialReply, RandomReply, ProxyReply, FuncReply and EchoReply are factories, and Shared turns any Replier into one.

func Shared

func Shared(r Replier) ReplierFactory

Shared returns a ReplierFactory that gives r to every mock built with it: those mocks share r, and whatever it keeps. Use it for a Replier that keeps no state, such as one from another package. A Replier that keeps state, such as a counter, should come from a ReplierFactory of its own that makes one for each mock. The mocks never close r: when it implements io.Closer, closing it is the caller's.

type Reply

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

Reply describes the response of a mock: its status, headers, trailers, cookies and body, any of them templates. It is a ReplierFactory: each mock built with it gets a Replier of its own, compiled with the template engine of its server, so a Reply can serve many mocks and servers, and changing it after Mock changes only the mocks built afterwards.

A Reply keeps the values it is given, such as body bytes, template data and a multipart body, without copying them, and the mocks built with it read them at each request: don't change them afterwards. Call the methods of the Reply instead, which reach the mocks built afterwards.

func Accepted

func Accepted() *Reply

Accepted creates a new Reply with http.StatusAccepted already.

func BadGateway

func BadGateway() *Reply

BadGateway creates a new Reply with http.StatusBadGateway already.

func BadRequest

func BadRequest() *Reply

BadRequest creates a new Reply with http.StatusBadRequest already.

func Created

func Created() *Reply

Created creates a new Reply with http.StatusCreated already.

func Forbidden

func Forbidden() *Reply

Forbidden creates a new Reply with http.StatusForbidden already.

func GatewayTimeout

func GatewayTimeout() *Reply

GatewayTimeout creates a new Reply with http.StatusGatewayTimeout already.

func InternalServerError

func InternalServerError() *Reply

InternalServerError creates a new Reply with http.StatusInternalServerError already.

func MethodNotAllowed

func MethodNotAllowed() *Reply

MethodNotAllowed creates a new Reply with http.StatusMethodNotAllowed already.

func MovedPermanently

func MovedPermanently(location string) *Reply

MovedPermanently creates a new Reply with http.StatusMovedPermanently already.

func MultipleChoices

func MultipleChoices() *Reply

MultipleChoices creates a new Reply with http.StatusMultipleChoices already.

func NewReply

func NewReply() *Reply

NewReply creates a new Reply. Prefer to use factory functions for each status code.

func NoContent

func NoContent() *Reply

NoContent creates a new Reply with http.StatusNoContent already.

func NotFound

func NotFound() *Reply

NotFound creates a new Reply with http.StatusNotFound already.

func NotImplemented

func NotImplemented() *Reply

NotImplemented creates a new Reply with http.StatusNotImplemented already.

func NotModified

func NotModified() *Reply

NotModified creates a new Reply with http.StatusNotModified already.

func OK

func OK() *Reply

OK creates a new Reply with http.StatusOK already.

func PartialContent

func PartialContent() *Reply

PartialContent creates a new Reply with http.StatusPartialContent already.

func ServiceUnavailable

func ServiceUnavailable() *Reply

ServiceUnavailable creates a new Reply with http.StatusServiceUnavailable already.

func Status

func Status(status int) *Reply

Status creates a new Reply with the given HTTP status code.

func Unauthorized

func Unauthorized() *Reply

Unauthorized creates a new Reply with http.StatusUnauthorized already.

func UnprocessableEntity

func UnprocessableEntity() *Reply

UnprocessableEntity creates a new Reply with http.StatusUnprocessableEntity already.

func (*Reply) Body

func (rep *Reply) Body(value []byte) *Reply

Body defines the response body using a []byte. Like every body setter, it replaces the body an earlier one set.

func (*Reply) BodyFile

func (rep *Reply) BodyFile(filename string) *Reply

BodyFile loads the body content from the given filename.

func (*Reply) BodyFileWithTemplate

func (rep *Reply) BodyFileWithTemplate(filename string) *Reply

BodyFileWithTemplate loads the body content from the given filename.

func (*Reply) BodyJSON

func (rep *Reply) BodyJSON(data any) *Reply

BodyJSON defines the response body encoding the given value using json.Encoder.

func (*Reply) BodyReader

func (rep *Reply) BodyReader(reader io.Reader) *Reply

BodyReader defines the response body using the given io.Reader.

func (*Reply) BodyTemplate

func (rep *Reply) BodyTemplate(content string) *Reply

BodyTemplate defines the response body using a template. The parameter content must be the actual template content that should be parsed and rendered. Use BodyFileWithTemplate function to load the template from a file.

func (*Reply) BodyText

func (rep *Reply) BodyText(text string) *Reply

BodyText defines the response body using a string.

func (*Reply) ContentType

func (rep *Reply) ContentType(mime string) *Reply

ContentType sets the response content-type misc.Header

func (*Reply) Cookie

func (rep *Reply) Cookie(cookie *http.Cookie) *Reply

Cookie adds an http.Cookie to the response, sent as given: vlatte adds no attribute. Set Secure only on a mock served over HTTPS: a client doesn't send a Secure cookie back over plain HTTP.

func (*Reply) Describe

func (rep *Reply) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive: the reply in the mock file format. A body that isn't valid UTF-8 is described in base64.

func (*Reply) EventStream

func (rep *Reply) EventStream(es *EventStream) *Reply

EventStream defines the response body as a stream of Server-Sent Events, sent event by event. It sets the Content-Type to text/event-stream and Cache-Control to no-cache, unless the reply sets them; a HEAD request gets those headers only. Building the mock fails with a status that has no body, 1xx, 204 or 304, and with response mappers, which read the whole body.

func (*Reply) ExpireCookie

func (rep *Reply) ExpireCookie(cookie *http.Cookie) *Reply

ExpireCookie expires a cookie. It expires a copy, so the given cookie stays as it was.

func (*Reply) Gzip

func (rep *Reply) Gzip() *Reply

Gzip indicates that the response should be gzip encoded.

func (*Reply) Header

func (rep *Reply) Header(key, value string) *Reply

Header adds a header to the MockedResponse.

func (*Reply) HeaderArr

func (rep *Reply) HeaderArr(key string, values ...string) *Reply

HeaderArr adds a header with multiple values to the MockedResponse.

func (*Reply) HeaderArrTemplate

func (rep *Reply) HeaderArrTemplate(key string, values ...string) *Reply

HeaderArrTemplate adds a header with multiple values that can have its value changed using templates.

func (*Reply) HeaderTemplate

func (rep *Reply) HeaderTemplate(key, value string) *Reply

HeaderTemplate adds a header that can have its value changed using templates.

func (*Reply) JSON

func (rep *Reply) JSON(payload any) *Reply

JSON sets the response to application/json.

func (*Reply) Multipart

func (rep *Reply) Multipart(mp *Multipart) *Reply

Multipart defines the response body as a multipart body. The body sets the Content-Type, with its boundary: setting a Content-Type too, with Header or HeaderTemplate, makes building the mock fail.

func (*Reply) NewReplier

func (rep *Reply) NewReplier(app *Server) (Replier, error)

NewReplier implements ReplierFactory. It compiles the templates of the reply with the template engine of app into a new Replier, and leaves the reply as it was.

func (*Reply) PlainText

func (rep *Reply) PlainText(text string) *Reply

PlainText defines a text/plain response with the given text body.

func (*Reply) Problem

func (rep *Reply) Problem(p *Problem) *Reply

Problem defines an RFC 9457 problem details response: it sets the Content-Type to MIMEApplicationProblemJSON and the body to p encoded as JSON. When p has a status, it sets the response status too, as the RFC asks them to match; a later call to Reply.Status overrides it. A nil p encodes as {}. An extension of p named after a standard member makes building the mock fail.

func (*Reply) SetTemplateData

func (rep *Reply) SetTemplateData(data any) *Reply

SetTemplateData sets the data model to be used by templates during response building.

func (*Reply) Status

func (rep *Reply) Status(status int) *Reply

Status sets the HTTP status code for the MockedResponse.

func (*Reply) Trailer

func (rep *Reply) Trailer(key, value string) *Reply

Trailer adds a trailer header to the response.

func (*Reply) TrailerArr

func (rep *Reply) TrailerArr(key string, values ...string) *Reply

TrailerArr adds a trailer with multiple values to the response.

type ReplyInput

type ReplyInput struct {
	RequestValues *RequestValues
	Writer        http.ResponseWriter
	// contains filtered or unexported fields
}

ReplyInput is the input passed to Replier.Reply for HTTP.

type RequestBodyParser

type RequestBodyParser interface {
	// CanParse checks if the current request body should be parsed.
	// The first parameter is the incoming content type.
	CanParse(contentType string, r *http.Request) bool

	// Parse parses the request body.
	Parse(body []byte, r *http.Request) (any, error)
}

RequestBodyParser parses the request body if CanParse returns true. Multiple implementations of RequestBodyParser can be provided via configuration.

type RequestValues

type RequestValues struct {
	// ReqID identifies the request (e.g. for logging). Set by the request parser.
	ReqID string

	// StartedAtTime indicates when the request arrived.
	StartedAtTime time.Time

	// RawRequest is the original incoming http.Request.
	RawRequest *http.Request

	// URL is the full request url.URL, including scheme, host, port: those a request in absolute form, as a forward
	// proxy gets, or an intercepted one names, and the server's otherwise.
	URL *url.URL

	// URLPathSegments stores path segments, each decoded: an escaped "/" stays in its segment.
	// Eg.: /test/100 -> []string{"test", "100"}, and /files/a%2Fb -> []string{"files", "a/b"}
	URLPathSegments []string

	// RawBodyBytes is the HTTP request body bytes.
	RawBodyBytes []byte

	// ParsedBodyData is the parsed http.Request body parsed by a RequestBodyParser instance.
	// It'll be nil if the HTTP request does not contain a body.
	ParsedBodyData any

	// App exposes application instance associated with the incoming HTTP request.
	App *Server

	// Mock is the matched Mock for the current HTTP request.
	Mock *Mock

	// Explanation holds what the matchers of Mock recorded when it matched, a block for each of them, such as why the
	// matcher under a [github.com/caffeine-projects/vlatte/match.Not] didn't match. It is nil when no mock matched.
	Explanation *vlatte.Explanation

	Data any
	// contains filtered or unexported fields
}

RequestValues groups HTTP request data, including the parsed body. It is used by several components during the request matching phase.

func (*RequestValues) ID

func (r *RequestValues) ID() string

ID returns the ID the server gave the request, as its logs and journal name it.

func (*RequestValues) OriginalRequest

func (r *RequestValues) OriginalRequest() *http.Request

OriginalRequest returns the request as the server got it.

func (*RequestValues) ParsedBody

func (r *RequestValues) ParsedBody() any

ParsedBody returns the request body as a RequestBodyParser parsed it, or nil when none did.

func (*RequestValues) RawBody

func (r *RequestValues) RawBody() []byte

RawBody returns the request body the server read, at most ConfigBuilder.MaxBodyParsingLimit bytes: nil for GET and HEAD requests, and with ConfigBuilder.NoBodyParsing.

func (*RequestValues) StartedAt

func (r *RequestValues) StartedAt() time.Time

StartedAt returns when the request arrived.

type Response

type Response struct {
	StatusCode   int
	Header       http.Header
	Trailer      http.Header
	Cookies      []*http.Cookie
	Body         []byte
	BodyCloser   io.ReadCloser
	BodyFilename string
	Encoding     string
	// contains filtered or unexported fields
}

Response defines the HTTP response that will be served once a Mock is matched with an HTTP Request.

func (*Response) Gunzip

func (r *Response) Gunzip() ([]byte, error)

Gunzip decompresses Gzip body.

func (*Response) Render

func (r *Response) Render(ctx context.Context, w http.ResponseWriter) error

Render writes the response to w. ctx is the request's: a streamed body stops waiting when it ends. An error comes after the status and headers are sent, so it can't change the response.

type Scope

type Scope = vlatte.Scope[*Mock]

Scope holds the mocks added by one Mock call; see vlatte.Scope.

type SequentialReply

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

SequentialReply configures a sequence of replies, served one per request, in order, then the one set with OnSequenceEnded. It is a ReplierFactory: each mock built with it runs the sequence on its own, from the first reply.

func Seq

func Seq(reply ...ReplierFactory) *SequentialReply

Seq creates a new SequentialReply.

func (*SequentialReply) Add

Add adds a new replier to the sequence.

func (*SequentialReply) Describe

func (r *SequentialReply) Describe() vlatte.Descriptor

Describe implements vlatte.SelfDescriptive: the reply in the mock file format. It leaves out the replies that don't implement vlatte.SelfDescriptive.

func (*SequentialReply) NewReplier

func (r *SequentialReply) NewReplier(app *Server) (Replier, error)

NewReplier implements ReplierFactory. It makes the Replier of each reply of the sequence, so each mock has replies and a place in the sequence of its own.

func (*SequentialReply) OnSequenceEnded

func (r *SequentialReply) OnSequenceEnded(reply ReplierFactory) *SequentialReply

OnSequenceEnded sets a replier to be used once the sequence is over.

type Server

type Server struct {
	*vlatte.Base[*Mock, *Server]
	*verify.Verifier[*Mock, *Server]
	// contains filtered or unexported fields
}

Server is the base for the mock server.

func MustNew

func MustNew(config ...Option) *Server

MustNew is like New but panics if any error occurs.

func New

func New(config ...Option) (*Server, error)

New creates a new HTTP mock Server with the given configurations. Parameter config accepts a Config or a ConfigBuilder implementation. If no configuration is provided, a default one will be used. If no port is set, it will start the server on localhost using a random port. It returns an error if a configuration fails to apply or the server cannot be built.

func (*Server) AdminURL

func (app *Server) AdminURL() string

AdminURL returns the base URL of the admin API, or "" when the server serves none, or hasn't started: see ConfigBuilder.Admin.

func (*Server) Backend

func (app *Server) Backend() Backend

Backend returns the Backend implementation being used by this application.

func (*Server) Close

func (app *Server) Close()

Close closes the mock server. It closes the admin API first, which waits for the operations it serves. It cancels the on_complete events still running, such as a webhook waiting for its delay or its target, so the requests waiting for them end, and waits for those requests and for the events that run after the response. It stops the recording, and waits until it wrote what it took, and closes the forward proxy's open tunnels. It closes the idle connections of the transports it made, such as the one of webhooks. Last, it closes the journal, and removes a temporary one: verify the requests before Close, as t.Cleanup(m.Close) leaves a test to. A closed server doesn't start again.

func (*Server) Config

func (app *Server) Config() *Config

Config returns the mock server Config.

func (*Server) Data

func (app *Server) Data() map[string]any

Data returns the data templates read as .Data. Requests read the map, so don't change it: set new data instead.

func (*Server) DescribeConfig

func (app *Server) DescribeConfig() string

DescribeConfig describes key configurations of this Server.

func (*Server) IsRecording

func (app *Server) IsRecording() bool

IsRecording reports whether a recording takes calls.

func (*Server) KV

func (app *Server) KV() vlatte.KV

KV returns the key-value store templates read as .KV: the one ConfigBuilder.KV set, or the memory store the server made without one, which Config.KV holds too.

func (*Server) Logger

func (app *Server) Logger() *zerolog.Logger

Logger returns the zerolog.Logger of this application.

func (*Server) MustReload

func (app *Server) MustReload()

MustReload reloads mocks from external sources, like the filesystem. Coded mocks will be kept. It panics if any error occurs.

func (*Server) MustStart

func (app *Server) MustStart()

MustStart starts the mock server. It fails immediately if any error occurs.

func (*Server) MustStartTLS

func (app *Server) MustStartTLS()

MustStartTLS starts TLS on a mock server. It fails immediately if any error occurs.

func (*Server) Name

func (app *Server) Name() string

Name returns mock server name.

func (*Server) Prep

func (app *Server) Prep(ctx context.Context, recipes ...Recipe) error

Prep runs the given recipes on this mock server, in order. It stops at the first recipe that fails and returns its error.

func (*Server) ProxyCA

func (app *Server) ProxyCA() *x509.Certificate

ProxyCA returns the certificate of the CA that signs the certificates of the hosts the forward proxy intercepts, for clients to trust, or nil when it doesn't intercept. See ProxyConfig.Intercept.

func (*Server) RecordingStatus

func (app *Server) RecordingStatus() vlatte.RecordStatus

RecordingStatus counts the calls of the recording, or returns a zero status when there is none.

func (*Server) Reload

func (app *Server) Reload() error

Reload loads the mocks of external sources, such as mock files and the admin API's persistent store, again. Each loader replaces the mocks it added before; mocks added in code are kept. The mocks of the mock files and of the persistent store are swapped in one step, and stay as they were when a file has problems, or the persistent store can't be read or its mocks served. The loaders of Config.Loaders run after.

func (*Server) RequestPattern

func (app *Server) RequestPattern(b vlatte.Builder[*Mock, *Server]) (verify.Pattern, error)

RequestPattern returns the pattern of journal entries that the request part of b matches, as it matches a request: b is a *Builder, such as Request().Query("page", match.Equal("2")), whose reply counts for nothing. Times, Once and scenarios match no request served before, so a pattern has none. It implements verify.Patterns, for VerifyRequests().Matching.

func (*Server) ResetScenario

func (app *Server) ResetScenario(name string, in ...matchscenario.Instance)

ResetScenario moves the scenario name back to matchscenario.StateStarted: every instance of it, or only the one of a key in, such as matchscenario.Key("t1"). An instance nothing moved and none set is there already: the admin API's events get no move of it.

func (*Server) ResetScenarios

func (app *Server) ResetScenarios()

ResetScenarios moves every scenario back to matchscenario.StateStarted.

func (*Server) Scenarios

func (app *Server) Scenarios(ctx context.Context) ([]matchscenario.Scenario, error)

Scenarios returns every scenario, by name: those the server's mocks name, with their states and the moves of their mocks, and those set without a mock. A disabled mock counts, as it matches again once enabled.

func (*Server) SetData

func (app *Server) SetData(data map[string]any)

SetData sets the data templates read as .Data, such as the URL of another server: {{ .Data.target }}. The server keeps a copy of the map, and requests read the data in force when they arrive.

func (*Server) SetScenario

func (app *Server) SetScenario(ctx context.Context, name, state string, in ...matchscenario.Instance) error

SetScenario moves the scenario name to state: its shared instance, or the one of a key in, such as matchscenario.Key("t1"). The mocks that require state match next. It returns an error that wraps matchscenario.ErrUnknownState when no mock of the scenario names state, or state is empty. A scenario no mock names moves to any other state.

func (*Server) Start

func (app *Server) Start() error

Start starts the mock server. It listens, so loaders can read URL, loads the mocks and starts the recording the config sets, then serves: the first request finds them. A server starts once: Start returns vlatte.ErrStarted once it started, and http.ErrServerClosed once it closed. Start is all or nothing: a start that fails to listen, load the mocks, start the recording or the admin API, or serve, stops what started and closes the server, so nothing listens, the listener of Config.Listener included.

func (*Server) StartRecording

func (app *Server) StartRecording(options ...RecordConfigurer) error

StartRecording starts recording what the server proxies as mock files, which answer the same requests the same way: see RecordConfig. It starts from the server's record settings, or the defaults, which options change. It returns vlatte.ErrRecording while another recording runs, or still writes what it took.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/caffeine-projects/vlatte/mockhttp"
)

func main() {
	// A target answers, and the server records what it proxies to it.
	target := mockhttp.MustNew(mockhttp.Setup().Silent())
	target.MustStart()
	defer target.Close()
	target.MustMock(mockhttp.Getf("/items").Reply(mockhttp.OK().JSON(map[string]any{"items": []int{1, 2}})))

	dir, err := os.MkdirTemp("", "recordings")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	m := mockhttp.MustNew(mockhttp.Setup().Silent())
	m.MustStart()
	defer m.Close()
	m.MustMock(mockhttp.AnyMethod().Reply(mockhttp.From(target.URL())))

	if err := m.StartRecording(mockhttp.RecordDir(dir), mockhttp.RecordTransform(func(r *mockhttp.RecordedMock) error {
		r.Name = "the items"
		return nil
	})); err != nil {
		panic(err)
	}

	res, err := http.Get(m.URL("/items?page=2"))
	if err != nil {
		panic(err)
	}
	res.Body.Close()

	// The recordings are written once StopRecording returns.
	recorded, err := m.StopRecording(context.Background())
	if err != nil {
		panic(err)
	}

	for _, r := range recorded.Recordings {
		fmt.Println(r.Name, filepath.Base(r.File))
	}

	// A server that loads the recordings answers without the target.
	target.Close()

	replay := mockhttp.MustNew(mockhttp.Setup().Silent().MockFilePatterns(filepath.Join(dir, "*.mock.json")))
	replay.MustStart()
	defer replay.Close()

	res, err = http.Get(replay.URL("/items?page=2"))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(body))
}
Output:
the items GET-items-page-2-a59dfd52f96e8038.mock.json
200 {"items":[1,2]}

func (*Server) StartTLS

func (app *Server) StartTLS() error

StartTLS starts the mock server with TLS, as Start does.

func (*Server) StopRecording

func (app *Server) StopRecording(ctx context.Context) (*vlatte.RecordResult, error)

StopRecording stops the recording, waits until it wrote what it took, and returns what it wrote. The server then serves the recordings: its mock files load again, with the recording's directory, so the hits of file mocks count from 0. When ctx ends first, it returns ctx's error, and the recording goes on writing: a later StopRecording waits again, and a StartRecording once it wrote everything ends it. Either serves it. It returns vlatte.ErrNotRecording when there is no recording. The error joins the calls and mocks that couldn't be recorded, and why the recordings aren't served, such as a mock ID they share with a mock file, or the server closing first.

func (*Server) URL

func (app *Server) URL(paths ...string) string

URL returns the base URL of the mock server. With paths, it joins them to it as path elements, with url.JoinPath: URL("/users", "1") is <base>/users/1, and "%3F" is a "?" in the path. A "?" or "#" in the last element starts the query or the fragment, which are appended as given, so they must already be escaped: URL("/users/1?active=true#top"). Go's http.Client doesn't send the fragment. With paths, it panics when url.JoinPath fails on the base URL.

type TemplateDataProvider

type TemplateDataProvider = vlatte.TemplateDataProvider[*TemplateDataProviderInput]

TemplateDataProvider adds data to the templates of HTTP mocks, which read it as .Provided.<Key>.

type TemplateDataProviderInput

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

TemplateDataProviderInput is what a TemplateDataProvider receives for each request.

func (*TemplateDataProviderInput) Request

Request returns the request being served, its matched mock in RequestValues.Mock.

Directories

Path Synopsis
e2e
internal/githubapp
Package githubapp is a small web app that signs users in with GitHub, through the OAuth web flow of an OAuth app with PKCE, and reads their profile, repositories and issues with the GitHub REST API.
Package githubapp is a small web app that signs users in with GitHub, through the OAuth web flow of an OAuth app with PKCE, and reads their profile, repositories and issues with the GitHub REST API.
internal/oidcapp
Package oidcapp is a small web app that signs users in with an OpenID Connect provider, through the authorization code flow with PKCE, and reads their profile from the provider's userinfo endpoint.
Package oidcapp is a small web app that signs users in with an OpenID Connect provider, through the authorization code flow with PKCE, and reads their profile from the provider's userinfo endpoint.
internal/testcert command
Command testcert writes a self-signed certificate and its key, cert.pem and key.pem, to the working directory.
Command testcert writes a self-signed certificate and its key, cert.pem and key.pem, to the working directory.
internal
mid
Package mid contains utilities to handle middlewares and also common middlewares used internally.
Package mid contains utilities to handle middlewares and also common middlewares used internally.

Jump to

Keyboard shortcuts

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