runner

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 40 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package runner executes parsed requests: it resolves variables, sends the request, evaluates captures and assertions, and persists captured values to the session.

Index

Constants

View Source
const (
	ExitOK        = 0
	ExitAssert    = 1 // an assertion or capture failed
	ExitUsage     = 2 // parse error, unknown request, missing variable
	ExitTransport = 3 // could not reach the server, timeout, TLS failure
)

Exit codes returned by the CLI.

View Source
const Base64 = "base64"

Base64 is Response.BodyEncoding for a body that is not text.

View Source
const DefaultMaxBodyBytes int64 = 64 << 20

DefaultMaxBodyBytes caps how much of a response apic reads into memory when apic.yaml does not say otherwise.

apic buffers a whole response before it can select, assert or render it, and holds it more than once while doing so, so an unbounded read turns one oversized or hostile response into a dead process. 64 MiB is far above any response a human reads in a terminal and still leaves the tool honest about what it cannot handle.

View Source
const DocsURL = "https://apic.sh/errors/"

DocsURL is where docs/errors.md is published; an entry's anchor is its code in lower case.

View Source
const Masked = "***"

Masked is what a hidden value is replaced with in output.

Variables

View Source
var Catalogue = []Entry{
	{CodeMissingVariable, ExitUsage, "missing variable",
		"Pass it with --var name=value, add it to an env file, or run the request that captures it first.",
		"A `{{placeholder}}` in the request has no value from any source: `--var`, the environment's entry in the env files, `.env`, the session, or a request earlier in the same run. The message names each missing variable and, when another request's `# @capture` provides it, that request. A `# @ref` to that request makes it run first by itself; `apic describe <request>` shows where every variable comes from."},
	{CodeBuild, ExitUsage, "request cannot be built",
		"Check the placeholder, URL, header or body the message names.",
		"The request's text could not be turned into a request: a built-in with bad arguments (`{{$randomInt 5 1}}`), an unknown built-in, a URL that does not parse once its placeholders are filled in, or a GraphQL body whose variables are not a JSON object."},
	{CodeInvalidFile, ExitUsage, "request file has errors",
		"Run apic validate to see every problem with its line and column.",
		"The `.http` file failed to parse where the request is: a malformed directive, a multipart body without a boundary, a GraphQL request without a query. apic refuses to send from a file with errors rather than guess; `apic validate` lists them all."},
	{CodeDirective, ExitUsage, "bad directive value",
		"Fix the directive's value; https://apic.sh/format/ lists what each takes.",
		"A directive is well formed but its value cannot be used: `# @timeout soon`, `# @retry 0`, `# @sleep -1s`, an `# @assert` that does not parse, an HTTP version other than HTTP/1.1 or HTTP/2 on the request line, or `HTTP/2` over plain `http://`."},
	{CodeAuth, ExitUsage, "authentication failed",
		"Check the # @auth spec (or auth.default), its credentials, and the token endpoint.",
		"The request's auth could not be applied: an `# @auth` spec that does not parse, `# @auth exec` without `auth.allowExec`, an OAuth2 token endpoint that refused the grant, a browser sign-in with no terminal, or a JetBrains `Security.Auth` configuration that does not exist or cannot be used."},
	{CodeBodyFile, ExitUsage, "body file problem",
		"Check that the file exists, relative to the .http file, and lies inside the project.",
		"A file the request reads could not be used: a `< file` body, a multipart part's file, or a schema for `matchesSchema`. Paths are relative to the `.http` file and must resolve (symlinks included) inside the project root, so a request file cannot read something outside it."},
	{CodeRef, ExitUsage, "@ref problem",
		"Point # @ref at exactly one request, and break any cycle.",
		"A `# @ref` or `# @forceRef` names no request, several requests, or leads back to the request it started from. `apic validate` reports these as `bad-ref` and `ref-cycle` before anything runs."},
	{CodeOther, ExitUsage, "error",
		"The message says what went wrong; if it is unclear, please open an issue.",
		"An error without a more specific code. It should be rare: if you meet one, the message is worth an issue so it can get a code of its own."},
	{CodeUnknownRequest, ExitUsage, "unknown request",
		"Run apic list to see the request ids, and use name, file.http, file.http#name or file.http#N.",
		"The target names no request: no `# @name` of that name, no such `.http` file, or no request at that position in the file. When a known name is close to the one given (a typo, the wrong case, `_` for `-`), the message asks \"did you mean\" and the `--json` object lists them under `suggestions`, best first; otherwise the message lists what there is: the request ids, the files, or the named requests of the file given."},
	{CodeAmbiguous, ExitUsage, "several requests match",
		"Pick one with file.http#name, or give the command a single request.",
		"The command works on one request (`describe`, `curl`, `snippet`) and the target names a whole file or a name used in several files."},
	{CodeFlag, ExitUsage, "bad flag or argument",
		"Check the command's flags with apic <command> --help.",
		"A flag has a value the command cannot use, two flags cannot be combined (`--output` with a flow or `--data`, `--use-session` with `--no-session`), an argument is missing or extra, a history entry number names no entry, or the command does not exist."},
	{CodeEnvironment, ExitUsage, "unknown environment",
		"Use one of the environments the message lists, or add it to http-client.env.json.",
		"`--env` (or `env:` in `apic.yaml`) names an environment that neither env file declares, or there are no env files at all. The message lists the environments found and, when one is close to the name given, asks \"did you mean\"; the `--json` object lists those under `suggestions`. `apic env` shows each environment with its files."},
	{CodeProject, ExitUsage, "project configuration problem",
		"Fix apic.yaml or the env file the message names; apic validate helps.",
		"The project could not be loaded: `apic.yaml` or an env file is not valid YAML/JSON, or a setting in it (a timeout, a retry policy) cannot be read."},
	{CodeTLSConfig, ExitUsage, "TLS configuration problem",
		"Check the CA file, client certificate and key the message names.",
		"A TLS setting cannot be used: a CA file with no PEM certificates, a certificate or key that does not load, a key that is world-readable or needs a passphrase apic cannot supply, or a path outside the project."},
	{CodeProxy, ExitUsage, "proxy configuration problem",
		"Give the proxy as an http, https, socks5 or socks5h URL.",
		"`--proxy`, `proxy:` in `apic.yaml` or `HTTP(S)_PROXY` holds a URL apic cannot use. apic refuses the request rather than send it directly."},
	{CodeSession, ExitUsage, "session or cookie store problem",
		"Check .apic/ is writable, or run with --no-session.",
		"`.apic/session.json`, the cookie jar or the response history in `.apic/history` could not be read or written, or a session command ran with `--no-session`."},
	{CodeData, ExitUsage, "bad data file",
		"Give --data a CSV file with a header row, or a JSON array of objects.",
		"The rows for `apic run --data` could not be read: an empty file, a header column without a name, a row with the wrong number of fields, or JSON that is not an array of objects."},
	{CodeFile, ExitUsage, "cannot read or write a file",
		"Check the path and its permissions.",
		"A file named on the command line (a report, a data file, a file to format, stdin) could not be read or written."},
	{CodeImport, ExitUsage, "import failed",
		"Check the input is an OpenAPI 3 document, a Postman v2 collection or a curl command.",
		"`apic import` could not read what it was given, or refused to overwrite files without `--force`."},
	{CodeFeatures, ExitUsage, "feature file problem",
		"Check the feature files, the step text and the tag expression.",
		"`apic test` could not run the features: no `.feature` files, a feature that does not parse, an invalid tag expression, a step table or variable name it cannot use, or a step naming a target that is not a request."},
	{CodeTerminal, ExitUsage, "needs a terminal",
		"Run apic ui in a terminal; use apic run or apic list --json in scripts.",
		"`apic ui` is interactive: it refuses `--json` and a stdout that is not a terminal."},
	{CodeServer, ExitUsage, "server could not start",
		"Check the address or port is free and allowed.",
		"`apic mcp --http` or `apic demo` could not listen where it was asked to."},
	{CodeTransport, ExitTransport, "request failed",
		"The message has the underlying error; check the URL and the network.",
		"The request could not complete for a reason none of the E3xx codes below describes."},
	{CodeConnect, ExitTransport, "could not connect",
		"Check the host name, the port and that the server is running.",
		"The host name did not resolve, the connection was refused or reset, or the network is unreachable. Nothing reached the server."},
	{CodeTimeout, ExitTransport, "timed out",
		"Raise --timeout, # @timeout or timeout: in apic.yaml, or check the server.",
		"The server did not answer within the timeout (30 seconds unless `--timeout`, `timeout:` in `apic.yaml` or `# @timeout` says otherwise)."},
	{CodeTLS, ExitTransport, "TLS handshake failed",
		"Trust the server's CA with --cacert or tls.caFile, or check the client certificate.",
		"The TLS handshake failed: the server's certificate is not trusted, has the wrong name or has expired, or the server refused the client certificate. `--insecure` skips verification for one command, as a last resort."},
	{CodeProtocol, ExitTransport, "protocol problem",
		"Check the server speaks what the request asks for.",
		"The server's answer could not be used: it did not negotiate HTTP/2 for a request line that asks for it, the response was malformed, or the body was larger than apic reads."},
	{CodeCancelled, ExitTransport, "cancelled",
		"Run the command again.",
		"The run was interrupted (Ctrl-C, or `esc` in the UI) while a request, a `# @sleep` or a retry wait was in progress. A flow prints its summary so far, the session and the history keep what the completed requests captured and returned, and `--report` is still written. A second Ctrl-C ends the process at once."},
}

Catalogue is every code, in order. docs/errors.md is generated from it (task docs:errors), so a message and its documentation cannot drift.

View Source
var Version = "dev"

Version is stamped by the CLI for the User-Agent header.

Functions

func ExitCode

func ExitCode(err error) int

ExitCode maps an error to the CLI exit code.

The exit codes are a public contract, so this unwraps rather than switching on the concrete type: wrapping a TransportError with %w anywhere on the way up would otherwise turn a documented 3 into a 2.

func HistoryKey

func HistoryKey(p *project.Project, req *httpfile.Request) string

HistoryKey is what a request's history is kept under: its name, or file#name when the name is used in more than one file, so two requests that share a name never share a history.

func RedactExpr

func RedactExpr(expr string) string

RedactExpr keeps the selector and operator of an assertion expression and hides the expected value.

Types

type AuthConfigInfo

type AuthConfigInfo struct {
	Name       string   `json:"name"`
	Spec       string   `json:"spec,omitempty"` // the oauth2 spec it maps to
	UseIDToken bool     `json:"use_id_token,omitempty"`
	Files      []string `json:"files"`
	Ignored    []string `json:"ignored,omitempty"` // fields apic does not act on
	Error      string   `json:"error,omitempty"`   // why it cannot be used
}

AuthConfigInfo is one Security.Auth configuration, for apic env: secrets masked, placeholders as written.

type Code

type Code string

Code identifies a kind of error apic reports. Codes are stable: a script or an agent can branch on one, and docs/errors.md (generated from Catalogue) explains each.

const (
	CodeOther           Code = "E200"
	CodeMissingVariable Code = "E101"
	CodeBuild           Code = "E102"
	CodeInvalidFile     Code = "E103"
	CodeDirective       Code = "E104"
	CodeAuth            Code = "E105"
	CodeBodyFile        Code = "E106"
	CodeRef             Code = "E107"
	CodeUnknownRequest  Code = "E201"
	CodeAmbiguous       Code = "E202"
	CodeFlag            Code = "E203"
	CodeEnvironment     Code = "E204"
	CodeProject         Code = "E205"
	CodeTLSConfig       Code = "E206"
	CodeProxy           Code = "E207"
	CodeSession         Code = "E208"
	CodeData            Code = "E209"
	CodeFile            Code = "E210"
	CodeImport          Code = "E211"
	CodeFeatures        Code = "E212"
	CodeTerminal        Code = "E213"
	CodeServer          Code = "E214"
	CodeTransport       Code = "E300"
	CodeConnect         Code = "E301"
	CodeTimeout         Code = "E302"
	CodeTLS             Code = "E303"
	CodeProtocol        Code = "E304"
	CodeCancelled       Code = "E305"
)

The codes. E1xx is the request as written, E2xx the command and the project around it, E3xx the network.

func CodeOf

func CodeOf(err error) Code

CodeOf is the catalogue code for an error: its own when it carries one, CodeOther for any other.

func (Code) URL

func (c Code) URL() string

URL is the entry's address on the documentation site.

type Description

type Description struct {
	Name        string            `json:"name,omitempty"`
	ID          string            `json:"id"`
	File        string            `json:"file"`
	Line        int               `json:"line"`
	Description string            `json:"description,omitempty"`
	Method      string            `json:"method"`
	URLTemplate string            `json:"url_template"`
	URL         string            `json:"url"` // resolved as far as possible
	Headers     map[string]string `json:"headers"`
	Body        string            `json:"body,omitempty"`
	BodyFile    string            `json:"body_file,omitempty"`
	SaveTo      string            `json:"save_to,omitempty"` // `>> file` after the body, relative to the .http file
	Variables   []VarInfo         `json:"variables"`
	Captures    []string          `json:"captures,omitempty"`
	Asserts     []string          `json:"asserts,omitempty"`
	Steps       []string          `json:"steps,omitempty"`        // # @step phrases
	Refs        []string          `json:"refs,omitempty"`         // # @ref and # @forceRef targets
	Sleep       string            `json:"sleep,omitempty"`        // # @sleep: the wait before sending
	Disabled    bool              `json:"disabled,omitempty"`     // # @disabled: skipped by flows
	HTTPVersion string            `json:"http_version,omitempty"` // HTTP/1.1 or HTTP/2 from the request line
	Auth        string            `json:"auth,omitempty"`         // auth spec template
	AuthSource  string            `json:"auth_source,omitempty"`  // "request" or "apic.yaml"
	TLS         *TLSInfo          `json:"tls,omitempty"`          // non-default TLS setup for the request's host
	Proxy       *ProxyInfo        `json:"proxy,omitempty"`        // the proxy in effect, when one is configured
	Ready       bool              `json:"ready"`                  // every variable resolves, or a # @ref supplies it
}

Description is what `apic describe` shows.

type Entry

type Entry struct {
	Code  Code
	Exit  int
	Title string // a few words, e.g. "missing variable"
	Hint  string // one line: what to do about it
	About string // what it means and how it comes about, for docs/errors.md
}

Entry is one row of the error catalogue.

func Lookup

func Lookup(c Code) (Entry, bool)

Lookup returns a code's entry.

type ErrorInfo

type ErrorInfo struct {
	Code    Code   `json:"code"`
	Title   string `json:"title"`
	Message string `json:"message"`
	Hint    string `json:"hint"`
	Exit    int    `json:"exit"`
	URL     string `json:"url"`
	// Suggestions are the names the user probably meant, best first,
	// when the error is about one that matches nothing: an unknown
	// request (E201, or E107 when a `# @ref` names it) or environment
	// (E204). Absent otherwise.
	Suggestions []string `json:"suggestions,omitempty"`
}

ErrorInfo is an error as --json, MCP and a result report it: the catalogue entry plus the message. It is part of the --json contract.

func Info

func Info(err error) *ErrorInfo

Info describes err with its catalogue entry. The exit status is the entry's, which is what ExitCode gives for the same error.

type FormPart

type FormPart struct {
	Name        string
	Filename    string
	ContentType string
	Value       string
	File        string
	Size        int
}

FormPart is one part of a resolved multipart/form-data body. Value is the rendered text of a text part; File is the path of a file part, relative to the project root, as `apic curl` needs it.

type Iteration

type Iteration struct {
	Index int               `json:"index"` // 1-based
	Total int               `json:"total"`
	Row   map[string]string `json:"row"`
}

Iteration places a result in a data-driven run: which row of how many, and the row's values (the variables it supplied).

type Options

type Options struct {
	Env       string            // environment name from http-client.env.json
	Vars      map[string]string // --var overrides
	NoSession bool              // do not read or write .apic/session.json
	Timeout   time.Duration     // default per-request timeout
	Insecure  bool              // skip TLS verification
	KeepGoing bool              // in a flow, continue after a failure
	Redact    bool              // mask every request value and capture in output (for CI logs)
	// Asserts and Captures are added to each request Run is called for,
	// not to the dependencies it pulls in through `# @ref`: `apic run
	// --assert` and `--capture`, which the caller has checked.
	Asserts  []httpfile.Assert
	Captures []httpfile.Capture
	// Output saves the response body of the request Run is called for to
	// this path (relative to the working directory, overwriting), as a
	// `>>! file` in the request would; `apic run --output`. Dependencies
	// the request pulls in through `# @ref` keep their own `>>` lines.
	Output string
	// MaxBodyBytes caps the response body read into memory; zero means
	// apic.yaml's maxBodyBytes, then DefaultMaxBodyBytes.
	MaxBodyBytes int64
	Session      *session.Store // use this store instead of opening .apic/session.json (tests use session.NewMemory())
	// Cookies switches the cookie jar on (--cookies); apic.yaml's `cookies:
	// true` does the same. CookieJar is the jar to use instead of opening
	// .apic/cookies.json (tests and `apic test` scenarios pass their own).
	Cookies   bool
	CookieJar *session.Jar
	// Retry is the default retry policy ("<n> [interval]", see ParseRetry)
	// for requests without `# @retry`; empty means apic.yaml's retry, then
	// none. NoRetry switches every retry off.
	Retry   string
	NoRetry bool
	// CACert, Cert and Key are the --cacert, --cert and --key flags: a PEM
	// bundle to trust and a client certificate to present. They override
	// apic.yaml's tls section and the environment's SSLConfiguration.
	CACert string
	Cert   string
	Key    string
	// Proxy is the --proxy flag, an http, https or socks5 URL that beats
	// apic.yaml's proxy and the environment; NoProxy (--no-proxy) sends
	// every request directly, whatever is configured.
	Proxy   string
	NoProxy bool
	// NoHistory records no responses whatever apic.yaml's history says:
	// `apic test` and the iterations of `apic run --data` set it, so a
	// test suite or a data file does not push a request's history out.
	NoHistory bool
}

Options controls a Runner.

type Progress

type Progress struct {
	Req     *httpfile.Request
	Attempt int    // the attempt that just failed, from 1
	Max     int    // attempts the policy allows
	Failure string // why it failed: the first failed assertion, or the error
}

Progress reports one failed attempt of a request that is being retried, before the runner waits and sends it again.

type ProxyInfo

type ProxyInfo struct {
	// URL is the proxy with any userinfo replaced by ***. Empty when Off.
	URL string `json:"url,omitempty"`
	// Source is where the setting came from: "--proxy", "apic.yaml", the
	// environment variable that named it, "--no-proxy", or "noProxy" when
	// the host is excluded by apic.yaml's noProxy list (or NO_PROXY for a
	// proxy from the environment).
	Source string `json:"source"`
	// Off means no proxy will be used although one is configured.
	Off bool `json:"off,omitempty"`
	// Error says the setting could not be used; the request is refused
	// with it rather than sent directly.
	Error string `json:"error,omitempty"`
	// contains filtered or unexported fields
}

ProxyInfo is the proxy in effect for one request, for `describe`, `env --json`, the verbose run output and `apic curl`.

func (*ProxyInfo) Raw

func (p *ProxyInfo) Raw() *url.URL

Raw returns the proxy URL as it will be dialled, credentials included, for a curl export that must stay runnable. It is nil when Off.

func (*ProxyInfo) String

func (p *ProxyInfo) String() string

String renders the proxy the way describe and -v show it.

type Resolved

type Resolved struct {
	Name    string            `json:"name,omitempty"`
	File    string            `json:"file"`
	Line    int               `json:"line"`
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers []httpfile.Header `json:"-"`
	Body    string            `json:"-"`
	Auth    string            `json:"auth,omitempty"` // auth type applied, e.g. "aws"
	// HTTPVersion is the version the request line asks for, HTTP/1.1 or
	// HTTP/2; empty when it names none and the protocol is negotiated.
	HTTPVersion string `json:"http_version,omitempty"`
	// TLS is the non-default TLS setup for this request's host: a private
	// CA, a client certificate or no verification.
	TLS *TLSInfo `json:"tls,omitempty"`
	// Proxy is the proxy the request goes through, when one is configured
	// by flag, apic.yaml or the environment.
	Proxy    *ProxyInfo `json:"proxy,omitempty"`
	AuthSpec *auth.Spec `json:"-"` // rendered spec (contains secrets)
	// SecretHeaders names headers whose value came from a secret source
	// (private env file, .env, session or a capture).
	SecretHeaders map[string]bool `json:"-"`
	// Parts are the parts of a multipart/form-data body, for renderers and
	// the curl exporter; Body then holds a one-line summary of them.
	Parts []FormPart `json:"-"`
	// contains filtered or unexported fields
}

Resolved is a request with every placeholder substituted.

func (Resolved) BodyBytes

func (r Resolved) BodyBytes() []byte

BodyBytes returns the bytes the request sends: the assembled multipart body when there is one, else the rendered body.

func (Resolved) DisplayBody

func (r Resolved) DisplayBody(redact bool) string

DisplayBody returns the body, or the mask when redacting.

func (Resolved) DisplayHeaders

func (r Resolved) DisplayHeaders(redact bool) []httpfile.Header

DisplayHeaders returns the request headers with sensitive values masked; with redact set every value is masked.

func (Resolved) DisplayURL

func (r Resolved) DisplayURL(redact bool) string

DisplayURL returns the URL with query values masked when redacting.

func (Resolved) MarshalJSON

func (r Resolved) MarshalJSON() ([]byte, error)

MarshalJSON renders headers as an object (sensitive values masked) and the body as a string. Result.MarshalJSON applies --redact on top.

type Response

type Response struct {
	Status     int               `json:"status"`
	StatusText string            `json:"status_text"`
	Headers    map[string]string `json:"headers"`
	Body       any               `json:"body"` // parsed JSON when the body is JSON, else a string
	// BodyEncoding is Base64 when the body is not text (not valid UTF-8),
	// in which case Body is the base64 of the bytes; empty otherwise.
	// Renderers read it to show a size instead of the bytes.
	BodyEncoding string `json:"body_encoding,omitempty"`
	// BodyTruncated says Body is the first Result.BodyLimit bytes of the
	// response, as text, because the caller asked for a bounded body
	// (`apic run --body-limit`); Size is still the whole body's.
	BodyTruncated bool  `json:"body_truncated,omitempty"`
	DurationMs    int64 `json:"duration_ms"`
	Size          int   `json:"size"`
	// Proto is the protocol the response came over: "HTTP/1.1", "HTTP/2.0".
	Proto string `json:"proto,omitempty"`
	// Timings is where the round trip went, from net/http/httptrace.
	Timings *Timings `json:"timings,omitempty"`
}

Response is the JSON-friendly view of a response.

func (*Response) DisplayHeaders

func (r *Response) DisplayHeaders(redact bool) map[string]string

DisplayHeaders returns the response headers with every value masked when redacting, and sensitive values masked either way.

type Result

type Result struct {
	OK       bool              `json:"ok"`
	Request  Resolved          `json:"request"`
	Response *Response         `json:"response,omitempty"`
	Captures map[string]string `json:"captures,omitempty"`
	Asserts  []assert.Result   `json:"asserts,omitempty"`
	Errors   []string          `json:"errors,omitempty"`
	// Warnings are problems that did not fail the request, such as a
	// response history that could not be written.
	Warnings []string `json:"warnings,omitempty"`
	// Error is the error that stopped the request, with its catalogue
	// code, when one did; Errors keeps the message too.
	Error *ErrorInfo `json:"error,omitempty"`
	// DryRun marks a result from DryRun: the request as it would be sent,
	// with no response because nothing was.
	DryRun bool `json:"dry_run,omitempty"`
	// Recorded says the response history took this response, under
	// RecordKey (see HistoryKey), so `apic select` can read it; otherwise
	// Unrecorded says why not. Set by record, read by the renderers.
	Recorded   bool   `json:"-"`
	RecordKey  string `json:"-"`
	Unrecorded string `json:"-"`
	// BodyLimit, when set, bounds the body the displays show (the JSON,
	// --body-only and the report) to that many bytes, marking the
	// response BodyTruncated. It is for a caller whose context the body
	// goes into, an agent above all; the response history keeps the
	// whole body, which `apic select` reads.
	BodyLimit int `json:"-"`
	// Attempts is how many times the request was sent under a `# @retry`
	// policy (or --retry, or retry in apic.yaml); zero when none applied.
	Attempts int `json:"attempts,omitempty"`
	// SavedTo is where the response body was written, for a request with a
	// `>> file` line or a run with --output: relative to the project root
	// when inside it, else as given.
	SavedTo string `json:"saved_to,omitempty"`
	// Deps are the results of the requests `# @ref` and `# @forceRef` ran
	// first, in run order; a dependency's own dependencies nest under it.
	Deps []*Result `json:"ran_first,omitempty"`
	// Skipped says why a flow did not send the request: "disabled" for
	// `# @disabled`. A skipped result is OK and has no response.
	Skipped string `json:"skipped,omitempty"`
	// Iteration is the row of `apic run --data` this result belongs to.
	Iteration *Iteration `json:"iteration,omitempty"`
	Redact    bool       `json:"-"` // set from Options.Redact
	// contains filtered or unexported fields
}

Result is the outcome of running one request.

func ParseResult

func ParseResult(data []byte) (*Result, error)

ParseResult reads a result back from the JSON `apic run --json` prints, as the response history stores it, so the renderers can show it as they show a fresh one. What was masked when it was written stays masked; the request's own name for each header is the one stored.

func (*Result) AuthNote

func (r *Result) AuthNote() string

AuthNote reports what the request's auth did on the wire, for verbose output: "digest: 401 challenge answered (2 requests)" and the like. Empty for the header-setting types.

func (Result) DisplayAsserts

func (r Result) DisplayAsserts() []assert.Result

DisplayAsserts returns the assertion results with the values they carry masked when redacting. An assertion like "# @assert body.$.token == {{token}}" bakes the rendered secret into Expr, Expected and Actual, so all three are hidden; Pass and Error are structural and survive.

func (Result) DisplayCaptures

func (r Result) DisplayCaptures() map[string]string

DisplayCaptures returns captures, masked when redacting.

func (*Result) DisplayRawBody

func (r *Result) DisplayRawBody() []byte

DisplayRawBody returns the raw response body for renderers, masked when redacting.

func (Result) DisplayResponse

func (r Result) DisplayResponse() *Response

DisplayResponse returns the response as it should be shown: status, timing and size survive because they are not secrets and CI needs them, while the body and header values are masked when redacting.

func (Result) MarshalJSON

func (r Result) MarshalJSON() ([]byte, error)

MarshalJSON masks sensitive request and response headers always, and everything (headers, bodies, query values, captures and assertion values) when Redact is set.

The shadowing fields sit at a shallower depth than the embedded alias, so encoding/json picks them over the originals.

func (*Result) Problem

func (r *Result) Problem() string

Problem is the one-line reason a result is not OK: the first failed assertion with what it got, else the first error, else "".

func (*Result) Raw

func (r *Result) Raw() *selector.Response

Raw returns the underlying response for renderers.

func (*Result) Req

func (r *Result) Req() *httpfile.Request

Req returns the request this result is for, so a caller holding results of dependencies (Deps) can map them back to the requests that produced them. It is nil for results built by hand.

type Runner

type Runner struct {
	Project *project.Project
	Envs    *env.Environments
	Session *session.Store
	// Jar is the cookie jar, nil unless cookies are switched on. It is
	// in-memory under --no-session and persisted to .apic/cookies.json
	// otherwise.
	Jar *session.Jar
	// History records each named request's response when apic.yaml sets
	// `history: N`; nil when it does not, under --no-session, or with
	// Options.NoHistory.
	History *history.Store
	Opts    Options
	Stderr  io.Writer // interactive prompts such as device-code sign-in; nil means os.Stderr
	// Interactive says a person is at the terminal: an OAuth2 grant that
	// needs a browser may open one. The CLI sets it when stdin and stderr
	// are terminals and --json is off; MCP and apic test leave it off.
	Interactive bool
	// Progress, when set, is called after each failed attempt of a request
	// that will be retried.
	Progress func(Progress)
	// OnResult, when set, is called by RunAll as each request finishes,
	// with its result (never nil) and the error, if any, that stopped it.
	OnResult func(*Result, error)

	// Now is the clock the time built-ins read; nil means time.Now.
	// Tests set it to pin `$timestamp` and friends.
	Now func() time.Time
	// contains filtered or unexported fields
}

Runner executes requests for one project.

func New

func New(p *project.Project, opts Options) (*Runner, error)

New builds a Runner, loading env files and the session.

func (*Runner) AuthConfig

func (r *Runner) AuthConfig(name string) (AuthConfigInfo, bool)

AuthConfig describes one configuration without resolving anything.

func (*Runner) AuthConfigs

func (r *Runner) AuthConfigs() []AuthConfigInfo

AuthConfigs lists the Security.Auth configurations of the current environment, by name.

func (*Runner) AuthSource

func (r *Runner) AuthSource(req *httpfile.Request) (raw, source string)

AuthSource reports the auth spec template for describe: the raw text and where it was declared.

func (*Runner) Capture

func (r *Runner) Capture(name, value string)

Capture stores a value in the capture layer, below --var and shell overrides and above the environment files, exactly like `# @capture`.

func (*Runner) Captured

func (r *Runner) Captured() map[string]string

Captured returns a copy of the values captured during this run.

func (*Runner) Describe

func (r *Runner) Describe(req *httpfile.Request) *Description

Describe reports a request's variables and where each comes from.

func (*Runner) DryRun

func (r *Runner) DryRun(req *httpfile.Request) (*Result, error)

DryRun resolves a request as Run would and stops there: no dependency runs, no auth is applied, nothing is sent and nothing is captured. A variable a `# @ref` dependency would capture is left as its placeholder with a warning saying so, since the run would supply it; any other missing variable is the error the run would give. The result carries the request and DryRun set, for an agent (or a person) to look at before a call that changes something.

func (*Runner) EnvVars

func (r *Runner) EnvVars() []VarInfo

EnvVar lists the effective variables for the current environment, for `apic env`.

func (*Runner) MissingError

func (r *Runner) MissingError(req *httpfile.Request, missing []string) error

MissingError explains unresolved variables with a hint on how to provide them.

func (*Runner) ProjectFile

func (r *Runner) ProjectFile(rel string) ([]byte, error)

ProjectFile reads a file named relative to the project root, confined to it: a schema a feature step names, which has no .http file to be relative to.

func (*Runner) ProxyInfo

func (r *Runner) ProxyInfo(rawURL string) *ProxyInfo

ProxyInfo reports the proxy in effect for a request URL. It is nil when no proxy is configured anywhere, so the field stays out of the output in the common case. An empty or unparsable URL reports the setting for an https request, which is what `apic env` wants.

func (*Runner) Render

func (r *Runner) Render(s string) (string, error)

Render substitutes {{placeholders}} in arbitrary text using the runner's variables (no file-level @vars, since no request is in scope).

func (*Runner) Resolve

func (r *Runner) Resolve(req *httpfile.Request) (*Resolved, error)

Resolve substitutes variables in a request without sending it.

func (*Runner) Results

func (r *Runner) Results() map[string]*Result

Results returns the named responses of this run, for `{{name.response...}}` references.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, req *httpfile.Request) (*Result, error)

Run resolves, sends and evaluates a single request. A non-nil error is a usage or transport problem; assertion failures are reported in Result.OK.

Requests the request declares with `# @forceRef` run first every time; those declared with `# @ref` run first only when a variable is missing, and once per Runner. Their results ride in Result.Deps. A dependency that fails stops the request: the result is not OK and names it.

func (*Runner) RunAll

func (r *Runner) RunAll(ctx context.Context, reqs []*httpfile.Request) ([]*Result, error)

RunAll runs requests in order as a flow, stopping at the first failure unless KeepGoing is set. Results for requests that ran are always returned. A `# @disabled` request is skipped, with a result that says so, unless Target resolved it by name.

func (*Runner) SetResult

func (r *Runner) SetResult(name string, res *Result)

SetResult registers a named response, e.g. one carried over from another runner.

func (*Runner) SetVar

func (r *Runner) SetVar(name, value string)

SetVar adds or overrides a variable at --var precedence.

func (*Runner) Target

func (r *Runner) Target(target string) ([]*httpfile.Request, error)

Target resolves a command-line target as Project.Resolve does. A target that names one request (get-user, users.http#get-user, users.http#3) is remembered, so RunAll sends it even when it is # @disabled: that directive only keeps a request out of a file's flow.

type Suggester added in v0.1.4

type Suggester interface {
	Suggestions() []string
}

Suggester is an error that can name what the user probably meant. project.NotFoundError is one; Usagef and Info read it.

type TLSInfo

type TLSInfo struct {
	CAFile   string `json:"ca_file,omitempty"`
	CertFile string `json:"cert_file,omitempty"`
	KeyFile  string `json:"key_file,omitempty"`
	Insecure bool   `json:"insecure,omitempty"` // server certificate not verified
}

TLSInfo is the TLS setup of a request as shown in output and mapped by `apic curl`. Paths are as configured: relative to the project root, or absolute when they came from a flag.

func (*TLSInfo) String

func (t *TLSInfo) String() string

String is the one-line description `describe` and verbose runs print.

type Timings

type Timings struct {
	DNSMs     int64 `json:"dns_ms"`
	ConnectMs int64 `json:"connect_ms"`
	TLSMs     int64 `json:"tls_ms"`
	TTFBMs    int64 `json:"ttfb_ms"`
	TotalMs   int64 `json:"total_ms"`
	Reused    bool  `json:"reused"`
}

Timings breaks a round trip down: name resolution, the TCP connection, the TLS handshake, the wait for the first response byte, and the total including the body. A reused connection has no DNS, connect or TLS time. Redirects and a digest challenge add their hops' times together.

type TransportError

type TransportError struct {
	Code Code // set where the cause is known; otherwise classified from Err
	Err  error
}

TransportError is a network-level failure.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) ErrorCode

func (e *TransportError) ErrorCode() Code

ErrorCode is the catalogue code for the failure.

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type UsageError

type UsageError struct {
	Code Code // the catalogue entry; empty reads as CodeOther
	Msg  string
	// Suggestions are the names the user probably meant, best first, when
	// the one they gave matches nothing (an unknown request or
	// environment). They reach --json and MCP as the error's
	// `suggestions`, so an agent can retry without listing.
	Suggestions []string
}

UsageError is a problem with the request definition or invocation.

func Usage

func Usage(code Code, msg string) *UsageError

Usage builds a UsageError with its code.

func Usagef

func Usagef(code Code, format string, args ...any) *UsageError

Usagef is Usage with a format. When one of args is itself an error that carries a code (a missing variable inside a header, say), that code is kept: it says more than the outer one. Suggestions an inner error carries are kept the same way, so Usagef(code, "%v", err) codes an error without losing them.

func (*UsageError) Error

func (e *UsageError) Error() string

type VarInfo

type VarInfo struct {
	Name       string `json:"name"`
	Value      string `json:"value,omitempty"`
	Source     string `json:"source"`
	Secret     bool   `json:"secret,omitempty"`
	Missing    bool   `json:"missing,omitempty"`
	CapturedBy string `json:"captured_by,omitempty"` // request that would provide it
	RefRuns    bool   `json:"ref_runs,omitempty"`    // CapturedBy is a `# @ref` of the request, so it runs first
}

VarInfo describes where a variable's value came from.

Jump to

Keyboard shortcuts

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