Documentation
¶
Overview ¶
Package httpfile parses the common subset of the `.http` request file format used by VS Code REST Client, JetBrains HTTP Client, kulala.nvim and httpyac, plus apic's own `# @capture` / `# @assert` comment directives.
Index ¶
- Constants
- Variables
- func Format(src string) string
- func FormatRequest(src, name string) (out string, ok bool)
- func GraphQLEnvelope(query, variables string) (string, error)
- func Parse(path, content string) (*File, []Diagnostic)
- func ParseFile(path string) (*File, []Diagnostic, error)
- func ParseRetry(s string) (n int, interval time.Duration, err error)
- func ParseSleep(s string) (time.Duration, error)
- func QuoteParam(s string) string
- func Span(line, sub string, after int) (col, end int)
- func SplitGraphQL(body string) (query, variables string)
- func ValidCaptureName(name string) bool
- type Assert
- type Capture
- type Diagnostic
- type Directive
- type File
- type FileRef
- type Header
- type Multipart
- type Part
- type Ref
- type Request
- func (r *Request) BodyFiles() []FileRef
- func (r *Request) Directive(key string) (string, bool)
- func (r *Request) DirectiveSpan(key string) (line, col, end int)
- func (r *Request) Disabled() bool
- func (r *Request) GraphQL() (query, variables string, err error)
- func (r *Request) Header(name string) (string, bool)
- func (r *Request) ID() string
- func (r *Request) IsGraphQL() bool
- func (r *Request) IsMultipart() bool
- func (r *Request) Multipart() (*Multipart, error)
- func (r *Request) Protocol() (string, error)
- func (r *Request) Refs() []Ref
- func (r *Request) Sleep() (time.Duration, error)
- func (r *Request) Steps() []string
- type SaveTo
- type Var
Constants ¶
const ( HTTP1 = "HTTP/1.1" HTTP2 = "HTTP/2" )
The HTTP versions a request line can ask for.
const DefaultRetryInterval = time.Second
DefaultRetryInterval is the wait between attempts when a retry policy gives none.
const GraphQLHeader = "X-REQUEST-TYPE"
GraphQLHeader is the REST Client header that marks a GraphQL request. It is never sent on the wire.
Variables ¶
var Codes = map[string]string{
"orphan-directives": "directives that are not followed by a request line",
"bad-name": "`# @name` without a value",
"bad-capture": "`# @capture` that is not `name = selector`",
"bad-assert": "`# @assert` that is not `selector op value`",
"bad-header": "a line in the header section that is not `Name: value`",
"unknown-directive": "a `# @directive` apic does not know (ignored)",
"editor-script": "an editor-only script or redirect block (skipped, not sent)",
"duplicate-name": "a request name used more than once in the project",
"bad-auth": "an `# @auth` spec that does not parse",
"exec-disabled": "`# @auth exec` without auth.allowExec in apic.yaml",
"bad-config-auth": "auth.default in apic.yaml does not parse",
"bad-step": "a `# @step` phrase that does not parse",
"ambiguous-step": "a `# @step` phrase that matches the same text as another step",
"bad-ref": "a `# @ref` or `# @forceRef` whose target is not one request in the project",
"ref-cycle": "a `# @ref` chain that leads back to the request it started from",
"bad-retry": "a `# @retry` (or retry in apic.yaml) that is not `<attempts> [interval]`",
"bad-sleep": "a `# @sleep` whose value is not a duration such as 500ms or 2s",
"bad-http-version": "a request line whose HTTP version is not HTTP/1.1 or HTTP/2",
"bad-auth-config": "a JetBrains `Security.Auth` configuration in an env file that apic cannot use (not OAuth2, the Implicit grant, a missing Token URL or Client ID)",
"unknown-auth-key": "a field of a `Security.Auth` configuration that apic does not act on",
"unknown-selector": "a selector that is not status, statusText, duration, header.*, cookie.*, body or body.$*, or a body path apic cannot read",
"missing-body-file": "a `< file` body, or a `< file` part of a multipart body, whose file does not exist",
"bad-multipart": "a multipart/form-data body without a boundary, or whose parts are not laid out between `--boundary` delimiters",
"bad-graphql": "a GraphQL request (GRAPHQL method or X-REQUEST-TYPE: GraphQL) without a query, or whose variables block is not a JSON object",
"bad-save-path": "a `>> file` after the body with no path, a path outside the project, or a second one on the same request",
"missing-schema-file": "a `# @assert … matchesSchema <file>` whose schema file does not exist or lies outside the project",
}
Codes are the diagnostic codes apic reports, with a one-line description each. They are part of the `validate --json` contract: a code never changes meaning, and new ones are only added.
var KnownDirectives = map[string]string{
"name": "request name used on the command line",
"description": "one-line description shown by list/describe",
"capture": "store a response value: `# @capture name = selector`",
"assert": "assert on the response: `# @assert selector op value`",
"auth": "authentication: `# @auth bearer|basic|aws|oauth2|exec|none ...`",
"step": "Gherkin phrase that runs this request: `# @step a user named {name} exists`",
"ref": "run another request first when a variable is missing: `# @ref login`",
"forceRef": "run another request first, every time: `# @forceRef login`",
"no-redirect": "do not follow redirects",
"no-session": "do not persist captures from this request",
"no-cookies": "send no cookies with this request and keep none it sets",
"timeout": "per-request timeout, e.g. `10s`",
"retry": "re-send until the assertions pass: `# @retry <attempts> [interval]`, e.g. `# @retry 10 2s`",
"sleep": "wait before sending, e.g. `# @sleep 2s`",
"disabled": "skip the request when its file runs as a flow; `apic run <name>` still sends it",
"note": "free text, ignored (REST Client compatibility)",
"prompt": "REST Client prompt, ignored (pass with --var instead)",
}
KnownDirectives are the `# @key` directives apic understands. Others are reported as warnings by validate but otherwise ignored.
Functions ¶
func Format ¶
Format rewrites .http content in its canonical form. It works on the lines rather than the AST so that everything the parser skips (comments, unknown directives, editor script blocks) is kept verbatim:
- one blank line between blocks, `### Title` on its own line;
- directives in a fixed order (name, description, step, auth, ref, forceRef, retry, timeout, no-redirect, no-session, no-cookies, assert, capture, then unknown ones as written), each `# @key value`; comments keep their place among the directives;
- `@name = value` file variables with single spaces;
- the request line with single spaces, query continuations indented four spaces, header names in canonical case;
- a JSON body pretty-printed with two spaces when it parses and holds no {{placeholders}}; every other body byte for byte as written, since the body is what the request sends;
- trailing whitespace removed outside bodies, blank lines after a body dropped, one final newline.
Formatting is idempotent: Format(Format(s)) == Format(s).
func FormatRequest ¶
FormatRequest formats one request of a file and leaves every other byte as written: the request whose `# @name` is name, or the n-th request of the file when name is a number, counted as the parser and so `apic run file.http#3` count them (the text before the first `###` is a request when it holds a request line; a `###` block without one is not). ok is false when nothing matches. It is for an agent (or an editor) that added or changed one request in a file it does not own, so the change stays that request's.
func GraphQLEnvelope ¶
GraphQLEnvelope is the body sent for a GraphQL request: the query as a JSON string and the variables object, when there is one. The variables must be a JSON object by then.
func Parse ¶
func Parse(path, content string) (*File, []Diagnostic)
Parse parses .http content. path is used only for diagnostics and IDs.
func ParseFile ¶
func ParseFile(path string) (*File, []Diagnostic, error)
ParseFile reads and parses a .http file from disk.
func ParseRetry ¶
ParseRetry parses a retry policy, "<attempts> [interval]": how many times to send a request until its assertions pass, and how long to wait between attempts (a Go duration such as 500ms or 2s; default 1s). Attempts must be at least 1. It is the value of `# @retry`, of `--retry` and of retry in apic.yaml.
func ParseSleep ¶
ParseSleep reads the value of `# @sleep`: a Go duration such as 500ms or 2s, not negative.
func QuoteParam ¶
QuoteParam quotes a Content-Disposition parameter value the way RFC 2616 quoted-strings are written: only backslash and the double quote are escaped, so a non-ASCII name or filename survives mime.ParseMediaType (Go's %q would write \u escapes it reads as literal letters).
func Span ¶
Span returns the 1-based byte columns [col, end) of sub within line, or zeros when sub is empty or not found. after is the offset to start searching from, so a value that also appears in the directive key is found in the right place.
func SplitGraphQL ¶
SplitGraphQL separates a GraphQL body into the query and the variables: the variables are the JSON object after the last blank line, when what follows that line starts with `{`. The variables are "" when there are none. Both halves keep their placeholders.
func ValidCaptureName ¶
ValidCaptureName reports whether name is one `# @capture` would accept.
Types ¶
type Assert ¶
Assert is a raw assertion expression: `# @assert status == 200`. Column is where Expr starts on the line.
type Capture ¶
Capture declares that a value selected from the response should be stored under Name for later requests: `# @capture token = body.$.access_token`. Column is where Selector starts on the line.
type Diagnostic ¶
type Diagnostic struct {
Path string `json:"path"`
Line int `json:"line"`
Column int `json:"column,omitempty"`
EndLine int `json:"end_line,omitempty"`
EndColumn int `json:"end_column,omitempty"`
Severity string `json:"severity"` // "error" or "warning"
Code string `json:"code,omitempty"`
Message string `json:"message"`
}
Diagnostic is a non-fatal problem found while parsing or validating.
Line and Column are 1-based; Column counts bytes from the start of the line. EndLine and EndColumn mark the end of the span, exclusive, so a diagnostic on the word "nope" at column 12 has EndColumn 16. The columns are zero when the problem has no useful span (a whole file, or apic.yaml). Code is a stable identifier from Codes that tools can key fixes on.
func (Diagnostic) String ¶
func (d Diagnostic) String() string
type Directive ¶
Directive is a `# @key value` comment placed before a request line. Column is the 1-based byte column where Value starts on the line, or where `@key` starts when there is no value.
type FileRef ¶
FileRef is a `< path` or `<@ path` reference in a request: the whole body, or one part of a multipart body.
type Part ¶
type Part struct {
Headers []Header
Name string // from Content-Disposition
Filename string // from Content-Disposition, when the part is a file
ContentType string // the part's own Content-Type header, when present
Body string // literal content (a template), empty when File is set
File string // `< path`: the file whose bytes are the content
// FileTemplated is `<@ path`: substitute {{vars}} inside the file too.
FileTemplated bool
FileLine int // line of the `< path` reference
FileColumn int // column where the path starts on that line
Line int // line of the delimiter that opens the part
}
Part is one part of a multipart/form-data body, as written in the file: its headers, then either literal content or a `< file` reference.
type Ref ¶
Ref is a `# @ref` or `# @forceRef` directive: another request to run before this one. A ref runs only when this request is missing a variable; a forceRef runs every time.
type Request ¶
type Request struct {
File *File
Index int // 1-based position within the file
Name string // from `# @name`, may be empty
Title string // free text after `###`
Description string // from `# @description`, else Title
Directives []Directive
Captures []Capture
Asserts []Assert
Method string
URL string // raw template
HTTPVersion string
Headers []Header
Body string // raw template, empty when none
BodyLine int // line of the first body line, 0 when there is no body
BodyFile string // set when the body is `< ./file`
BodyFileTemplated bool // `<@ ./file`: substitute {{vars}} inside the file too
BodyFileLine int // line of the `< ./file` reference, for diagnostics
BodyFileColumn int // column where the path starts on that line
SaveTo *SaveTo // `>> ./file` after the body: where the response body goes
Line int // line number of the request line
}
Request is one request block within a file.
func (*Request) BodyFiles ¶
BodyFiles returns every file the request's body reads: the whole-body `< file`, or the `< file` parts of a multipart body. A multipart body that does not parse contributes nothing; validate reports it.
func (*Request) DirectiveSpan ¶
DirectiveSpan returns the line and the [col, end) columns of the value of the first directive with the given key, or zeros when there is none.
func (*Request) Disabled ¶
Disabled reports `# @disabled`: the request is skipped when its file runs as a flow, and still sent when it is asked for by name.
func (*Request) GraphQL ¶
GraphQL returns the query and the variables of a GraphQL request as written, and an error when the request has no query or the variables hold no placeholders and are not a JSON object.
func (*Request) Header ¶
Header returns the value of the first header with the given name, case-insensitively.
func (*Request) ID ¶
ID returns the stable identifier used on the command line: the request's name when it has one, else `<file>#<index>`.
func (*Request) IsGraphQL ¶
IsGraphQL reports whether the request is written as a GraphQL query: the `GRAPHQL` method, or an `X-REQUEST-TYPE: GraphQL` header.
func (*Request) IsMultipart ¶
IsMultipart reports whether the request declares a multipart/form-data Content-Type. The body then holds parts (see Multipart) rather than one template.
func (*Request) Multipart ¶
Multipart parses the body of a multipart/form-data request into its parts. It returns nil, nil for a request that is not multipart, or whose whole body is a `< file`; an error names what is wrong with the body.
func (*Request) Protocol ¶
Protocol is the HTTP version the request line asks for: "" when it names none, HTTP1 (HTTP/1.0 is sent as 1.1) or HTTP2. HTTP/3 and anything else is an error, which validate reports as bad-http-version.
func (*Request) Refs ¶
Refs returns every `# @ref` and `# @forceRef` declared on the request, in order.